text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as dispose from 'app/client/lib/dispose'; import * as dom from 'app/client/lib/dom'; import {timeFormat} from 'app/common/timeFormat'; import * as ko from 'knockout'; import map = require('lodash/map'); import koArray from 'app/client/lib/koArray'; import {KoArray} from 'app/client/lib/koArray'; import * as koDom from 'app/client/lib/koDom'; import * as koForm from 'app/client/lib/koForm'; import {GristDoc} from 'app/client/components/GristDoc'; import {ActionGroup} from 'app/common/ActionGroup'; import {ActionSummary, asTabularDiffs, defunctTableName, getAffectedTables, LabelDelta} from 'app/common/ActionSummary'; import {CellDelta} from 'app/common/TabularDiff'; import {IDomComponent} from 'grainjs'; /** * * Actions that are displayed in the log get a state observable * to track if they are undone/buried. * * Also for each table shown in the log, we create an observable * to track its name. References to these observables are stored * with each action, by the name of the table at that time (the * name of a table can change). * */ export interface ActionGroupWithState extends ActionGroup { state?: ko.Observable<string>; // is action undone/buried tableFilters?: {[tableId: string]: ko.Observable<string>}; // current names of tables affectedTableIds?: Array<ko.Observable<string>>; // names of tables affecting this ActionGroup } const gristNotify = (window as any).gristNotify; // Action display state enum. const state = { UNDONE: 'undone', BURIED: 'buried', DEFAULT: 'default' }; export class ActionLog extends dispose.Disposable implements IDomComponent { private _displayStack: KoArray<ActionGroupWithState>; private _gristDoc: GristDoc|null; private _selectedTableId: ko.Computed<string>; private _showAllTables: ko.Observable<boolean>; // should all tables be visible? private _pending: ActionGroupWithState[] = []; // cache for actions that arrive while loading log private _loaded: boolean = false; // flag set once log is loaded private _loading: ko.Observable<boolean>; // flag set while log is loading /** * Create an ActionLog. * @param options - supplies the GristDoc holding the log, if we have one, so that we * can cross-reference with it. We may not have a document, if used from the * command line renderActions utility, in which case we don't set up cross-references. */ public create(options: {gristDoc: GristDoc|null}) { // By default, just show actions for the currently viewed table. this._showAllTables = ko.observable(false); // We load the ActionLog lazily now, when it is first viewed. this._loading = ko.observable(false); this._gristDoc = options.gristDoc; // TODO: _displayStack grows without bound within a single session. // Stack of actions as they should be displayed to the user. this._displayStack = koArray<ActionGroupWithState>(); // Computed for the tableId of the table currently being viewed. if (!this._gristDoc) { this._selectedTableId = this.autoDispose(ko.computed(() => "")); } else { this._selectedTableId = this.autoDispose(ko.computed( () => this._gristDoc!.viewModel.activeSection().table().tableId())); } } public buildDom() { return this._buildLogDom(); } /** * Pushes actions as they are received from the server to the display stack. * @param {Object} actionGroup - ActionGroup instance from the server. */ public pushAction(ag: ActionGroupWithState): void { if (this._loading()) { this._pending.push(ag); return; } this._setupFilters(ag, this._displayStack.at(0) || undefined); const otherAg = ag.otherId ? this._displayStack.all().find(a => a.actionNum === ag.otherId) : null; if (otherAg) { // Undo/redo action. if (otherAg.state) { otherAg.state(ag.isUndo ? state.UNDONE : state.DEFAULT); } } else { // Any (non-link) action. if (ag.fromSelf) { // Bury all undos immediately preceding this action since they can no longer // be redone. This is triggered by normal actions and undo/redo actions whose // targets are not recent (not in the stack). for (let i = 0; i < this._displayStack.peekLength; i++) { const prevAction = this._displayStack.at(i)!; if (!prevAction.state) { continue; } const prevState = prevAction.state(); if (prevAction.fromSelf && prevState === state.DEFAULT) { // When a normal action is found, stop looking to bury previous actions. break; } else if (prevAction.fromSelf && prevState === state.UNDONE) { // The previous action was undone, so now it has become buried. prevAction.state(state.BURIED); } } } if (!ag.otherId) { ag.state = ko.observable(state.DEFAULT); this._displayStack.unshift(ag); } } } /** * Render a description of an action prepared on the server. * @param {TabularDiffs} act - a collection of table changes * @param {string} txt - a textual description of the action * @param {ActionGroupWithState} ag - the full action information we have */ public renderTabularDiffs(sum: ActionSummary, txt: string, ag?: ActionGroupWithState) { const act = asTabularDiffs(sum); const editDom = dom('div', this._renderTableSchemaChanges(sum, ag), this._renderColumnSchemaChanges(sum, ag), map(act, (tdiff, table) => { if (tdiff.cells.length === 0) { return dom('div'); } return dom('table.action_log_table', koDom.show(() => this._showForTable(table, ag)), dom('caption', this._renderTableName(table)), dom('tr', dom('th'), tdiff.header.map(diff => { return dom('th', this._renderCell(diff)); })), tdiff.cells.map(row => { return dom('tr', dom('td', this._renderCell(row[0])), row[2].map((diff, idx: number) => { return dom('td', this._renderCell(diff), dom.on('click', () => { return this._selectCell(row[1], act[table].header[idx], table, ag ? ag.actionNum : 0); })); })); })); }), dom('span.action_comment', txt)); return editDom; } /** * Decorate an ActionGroup with observables for controlling visibility of any * table information rendered from it. Observables are shared with the previous * ActionGroup, and simply stored under a new name as needed. */ private _setupFilters(ag: ActionGroupWithState, prev?: ActionGroupWithState): void { const filt: {[name: string]: ko.Observable<string>} = ag.tableFilters = {}; // First, bring along observables for tables from previous actions. if (prev) { // Tables are renamed from time to time - prepare dictionary of updates. const renames = new Map(ag.actionSummary.tableRenames); for (const name of Object.keys(prev.tableFilters!)) { if (name.startsWith('-')) { // skip } else if (renames.has(name)) { const newName = renames.get(name) || defunctTableName(name); filt[newName] = prev.tableFilters![name]; filt[newName](newName); // Update the observable with the new name. } else { filt[name] = prev.tableFilters![name]; } } } // Add any more observables that we need for this action. const names = getAffectedTables(ag.actionSummary); for (const name of names) { if (!filt[name]) { filt[name] = ko.observable(name); } } // Record the observables that affect this ActionGroup specifically ag.affectedTableIds = names.map(name => ag.tableFilters![name]).filter(obs => obs); } /** * Helper function that returns true if any table touched by the ActionGroup * is set to be visible. */ private _hasSelectedTable(ag: ActionGroupWithState): boolean { if (!this._gristDoc) { return true; } return ag.affectedTableIds!.some(tableId => tableId() === this._selectedTableId()); } /** * Return a koDom.show clause that activates when the named table is not * filtered out. */ private _showForTable(tableName: string, ag?: ActionGroupWithState): boolean { if (!ag) { return true; } const obs = ag.tableFilters![tableName]; return this._showAllTables() || !obs || obs() === this._selectedTableId(); } private _buildLogDom() { this._loadActionSummaries().catch((error) => gristNotify(`Action Log failed to load`)); return dom('div.action_log', dom('div.preference_item', koForm.checkbox(this._showAllTables, dom.testId('ActionLog_allTables'), dom('span.preference_desc', 'All tables'))), dom('div.action_log_load', koDom.show(() => this._loading()), 'Loading...'), koDom.foreach(this._displayStack, (ag: ActionGroupWithState) => { const timestamp = ag.time ? timeFormat("D T", new Date(ag.time)) : ""; let desc = ag.desc || ""; if (ag.actionSummary) { desc = this.renderTabularDiffs(ag.actionSummary, desc, ag); } return dom('div.action_log_item', koDom.cssClass(ag.state), koDom.show(() => this._showAllTables() || this._hasSelectedTable(ag)), dom('div.action_info', dom('span.action_info_action_num', `#${ag.actionNum}`), ag.user ? dom('span.action_info_user', ag.user, koDom.toggleClass('action_info_from_self', ag.fromSelf) ) : '', dom('span.action_info_timestamp', timestamp)), dom('span.action_desc', desc) ); }) ); } /** * Fetch summaries of recent actions (with summaries) from the server. */ private async _loadActionSummaries() { if (this._loaded || !this._gristDoc) { return; } this._loading(true); // Returned actions are ordered with earliest actions first. const result = await this._gristDoc.docComm.getActionSummaries(); this._loading(false); this._loaded = true; // Add the actions to our action log. result.forEach(item => this.pushAction(item)); // Add any actions that came in while we were fetching. Unlikely, but // perhaps possible? const top = result.length > 0 ? result[result.length - 1].actionNum : 0; for (const item of this._pending) { if (item.actionNum > top) { this.pushAction(item); } } this._pending.length = 0; } /** * Prepare dom element(s) for a cell that has been created, destroyed, * or modified. * * @param {CellDelta|string|null} cell - a structure with before and after values, * or a plain string, or null * */ private _renderCell(cell: CellDelta|string|null) { // we'll show completely empty cells as "..." if (cell === null) { return "..."; } // strings are shown as themselves if (typeof(cell) === 'string') { return cell; } // by elimination, we have a TabularDiff.CellDelta with before and after values. const [pre, post] = cell; if (!pre && !post) { // very boring before + after values :-) return ""; } else if (pre && !post) { // this is a cell that was removed return dom('span.action_log_cell_remove', pre[0]); } else if (post && (pre === null || (pre[0] === null || pre[0] === ''))) { // this is a cell that was added, or modified from a previously empty value return dom('span.action_log_cell_add', post[0]); } else if (pre && post) { // a modified cell return dom('div', dom('span.action_log_cell_remove.action_log_cell_pre', pre[0]), dom('span.action_log_cell_add', post[0])); } return JSON.stringify(cell); } /** * Choose a table name to show. For now, we show diffs of metadata tables also. * For those tables, we show "_grist_Foo_bar" as "[Foo.bar]". * @param {string} name - tableId of table * @returns {string} a friendlier name for the table */ private _renderTableName(name: string): string { if (name.indexOf('_grist_') !== 0) { // Ordinary data table. Ideally, we would look up // a friendly name from a raw data view - TODO. return name; } const metaName = name.split('_grist_')[1].replace(/_/g, '.'); return `[${metaName}]`; } /** * Show an ActionLog item when a column or table is renamed, added, or removed. * Make sure the item is only shown when the affected table is not filtered out. * * @param scope: blank for tables, otherwise "<tablename>." * @param pair: the rename/addition/removal in LabelDelta format: [null, name1] * for addition of name1, [name2, null] for removal of name2, [name1, name2] * for a rename of name1 to name2. * @return a filtered dom element. */ private _renderSchemaChange(scope: string, pair: LabelDelta, ag?: ActionGroupWithState) { const [pre, post] = pair; // ignore addition/removal of manualSort column if ((pre || post) === 'manualSort') { return dom('div'); } return dom('div.action_log_rename', koDom.show(() => this._showForTable(post || defunctTableName(pre!), ag)), (!post ? ["Remove ", scope, dom("span.action_log_rename_pre", pre)] : (!pre ? ["Add ", scope, dom("span.action_log_rename_post", post)] : ["Rename ", scope, dom("span.action_log_rename_pre", pre), " to ", dom("span.action_log_rename_post", post)]))); } /** * Show any table additions/removals/renames. */ private _renderTableSchemaChanges(sum: ActionSummary, ag?: ActionGroupWithState) { return dom('div', sum.tableRenames.map(pair => this._renderSchemaChange("", pair, ag))); } /** * Show any column additions/removals/renames. */ private _renderColumnSchemaChanges(sum: ActionSummary, ag?: ActionGroupWithState) { return dom('div', Object.keys(sum.tableDeltas).filter(key => !key.startsWith('-')).map(key => dom('div', koDom.show(() => this._showForTable(key, ag)), sum.tableDeltas[key].columnRenames.map(pair => this._renderSchemaChange(key + ".", pair))))); } /** * Move cursor to show a given cell of a given table. Uses primary view of table. */ private async _selectCell(rowId: number, colId: string, tableId: string, actionNum: number) { if (!this._gristDoc) { return; } // Find action in the stack. const index = this._displayStack.peek().findIndex(a => a.actionNum === actionNum); if (index < 0) { throw new Error(`Cannot find action ${actionNum} in the action log.`); } // Found the action. Now trace forward to find current tableId, colId, rowId. for (let i = index; i >= 0; i--) { const action = this._displayStack.at(i)!; const sum = action.actionSummary; // Check if this table was renamed / removed. const tableRename: LabelDelta|undefined = sum.tableRenames.find(r => r[0] === tableId); if (tableRename) { const newName = tableRename[1]; if (!newName) { // TODO - find a better way to send informative notifications. gristNotify(`Table ${tableId} was subsequently removed in action #${action.actionNum}`); return; } tableId = newName; } const td = sum.tableDeltas[tableId]; if (!td) { continue; } // Check is this row was removed - if so there's no reason to go on. if (td.removeRows.indexOf(rowId) >= 0) { // TODO - find a better way to send informative notifications. gristNotify(`This row was subsequently removed in action #${action.actionNum}`); return; } // Check if this column was renamed / added. const columnRename: LabelDelta|undefined = td.columnRenames.find(r => r[0] === colId); if (columnRename) { const newName = columnRename[1]; if (!newName) { // TODO - find a better way to send informative notifications. gristNotify(`Column ${colId} was subsequently removed in action #${action.actionNum}`); return; } colId = newName; } } // Find the table model of interest. const tableModel = this._gristDoc.getTableModel(tableId); if (!tableModel) { return; } // Get its "primary" view. const viewRow = tableModel.tableMetaRow.primaryView(); const viewId = viewRow.getRowId(); // Switch to that view. await this._gristDoc.openDocPage(viewId); // Now let's pick a reasonable section in that view. const viewSection = viewRow.viewSections().peek().find((s: any) => s.table().tableId() === tableId); if (!viewSection) { return; } const sectionId = viewSection.getRowId(); // Within that section, find the column of interest if possible. const fieldIndex = viewSection.viewFields().peek().findIndex((f: any) => f.colId.peek() === colId); // Finally, move cursor position to the section, column (if we found it), and row. this._gristDoc.moveToCursorPos({rowId, sectionId, fieldIndex}).catch(() => { /* do nothing */ }); } }
the_stack
import { GroupService } from './../group/group.service' import { defaultGroupId, defaultRobotId, FILE_SAVE_PATH, IMAGE_SAVE_PATH, defaultGroupMessageTime } from './../../common/constant/global' import { AuthService } from './../auth/auth.service' import { MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, ConnectedSocket } from '@nestjs/websockets' import { Server, Socket } from 'socket.io' import { InjectRepository } from '@nestjs/typeorm' import { Repository, getRepository } from 'typeorm' import { Group, GroupMap } from '../group/entity/group.entity' import { GroupMessage } from '../group/entity/groupMessage.entity' import { UserMap } from '../friend/entity/friend.entity' import { FriendMessage } from '../friend/entity/friendMessage.entity' import { createWriteStream } from 'fs' import { join } from 'path' import { RCode } from 'src/common/constant/rcode' import { formatBytes, nameVerify } from 'src/common/tool/utils' import { defaultPassword } from 'src/common/constant/global' import { getElasticData } from 'src/common/middleware/elasticsearch' import { UseGuards } from '@nestjs/common' import { User } from './../user/entity/user.entity' import { WsJwtGuard } from './../../common/guards/WsJwtGuard' const nodejieba = require('nodejieba') // const axios = require('axios'); @WebSocketGateway() export class ChatGateway { constructor( @InjectRepository(User) private readonly userRepository: Repository<User>, @InjectRepository(Group) private readonly groupRepository: Repository<Group>, @InjectRepository(GroupMap) private readonly groupUserRepository: Repository<GroupMap>, @InjectRepository(GroupMessage) private readonly groupMessageRepository: Repository<GroupMessage>, @InjectRepository(UserMap) private readonly friendRepository: Repository<UserMap>, @InjectRepository(FriendMessage) private readonly friendMessageRepository: Repository<FriendMessage>, private readonly authService: AuthService, private readonly groupService: GroupService ) {} @WebSocketServer() server: Server // socket连接钩子 async handleConnection(client: Socket): Promise<string> { const token = client.handshake.query.token const user = this.authService.verifyUser(token) const { userId } = user // 连接默认加入DEFAULG_GROUP // TODO 待优化 client.join(defaultGroupId) // 进来统计一下在线人数 console.log('用户上线', userId) // 上线提醒广播给所有人 client.broadcast.emit('userOnline', { code: RCode.OK, msg: 'userOnline', data: userId }) // 用户独有消息房间 根据userId if (userId) { client.join(userId) } return '连接成功' } // socket断连钩子 async handleDisconnect(client: Socket): Promise<any> { const userId = client.handshake.query.userId console.log('用户下线', userId) // 下线提醒广播给所有人 client.broadcast.emit('userOffline', { code: RCode.OK, msg: 'userOffline', data: userId }) } // 创建群组 @UseGuards(WsJwtGuard) @SubscribeMessage('addGroup') async addGroup( @ConnectedSocket() client: Socket, @MessageBody() data: GroupDto ): Promise<any> { const isUser = await this.userRepository.findOne({ userId: data.userId }) if (isUser) { const isHaveGroup = await this.groupRepository.findOne({ groupName: data.groupName }) if (isHaveGroup) { this.server.to(data.userId).emit('addGroup', { code: RCode.FAIL, msg: '该群名字已存在', data: isHaveGroup }) return } if (!nameVerify(data.groupName)) { return } data = await this.groupRepository.save(data) client.join(data.groupId) const group = await this.groupUserRepository.save(data) const member = isUser as FriendDto member.online = 1 member.isManager = 1 data.members = [member] this.server.to(group.groupId).emit('addGroup', { code: RCode.OK, msg: `成功创建群${data.groupName}`, data: group }) } else { this.server .to(data.userId) .emit('addGroup', { code: RCode.FAIL, msg: `你没资格创建群` }) } } // 加入群组 @UseGuards(WsJwtGuard) @SubscribeMessage('joinGroup') async joinGroup( @ConnectedSocket() client: Socket, @MessageBody() data: GroupMap ): Promise<any> { const isUser = await this.userRepository.findOne({ userId: data.userId }) if (isUser) { const group = await this.groupRepository.findOne({ groupId: data.groupId }) let userGroup = await this.groupUserRepository.findOne({ groupId: group.groupId, userId: data.userId }) const user = await this.userRepository.findOne({ userId: data.userId }) if (group && user) { if (!userGroup) { data.groupId = group.groupId userGroup = await this.groupUserRepository.save(data) } client.join(group.groupId) const res = { group: group, user: user } this.server.to(group.groupId).emit('joinGroup', { code: RCode.OK, msg: `${user.username}加入群${group.groupName}`, data: res }) } else { this.server .to(data.userId) .emit('joinGroup', { code: RCode.FAIL, msg: '进群失败', data: '' }) } } else { this.server .to(data.userId) .emit('joinGroup', { code: RCode.FAIL, msg: '你没资格进群' }) } } // 加入群组的socket连接 @UseGuards(WsJwtGuard) @SubscribeMessage('joinGroupSocket') async joinGroupSocket( @ConnectedSocket() client: Socket, @MessageBody() data: GroupMap ): Promise<any> { const group = await this.groupRepository.findOne({ groupId: data.groupId }) const user = await this.userRepository.findOne({ userId: data.userId }) if (group && user) { client.join(group.groupId) const res = { group: group, user: user } this.server.to(group.groupId).emit('joinGroupSocket', { code: RCode.OK, msg: `${user.username}加入群${group.groupName}`, data: res }) } else { this.server.to(data.userId).emit('joinGroupSocket', { code: RCode.FAIL, msg: '进群失败', data: '' }) } } // 发送群消息 @UseGuards(WsJwtGuard) @SubscribeMessage('groupMessage') async sendGroupMessage(@MessageBody() data: GroupMessageDto): Promise<any> { const isUser = await this.userRepository.findOne({ userId: data.userId }) console.log(data) if (isUser) { const userGroupMap = await this.groupUserRepository.findOne({ userId: data.userId, groupId: data.groupId }) if (!userGroupMap || !data.groupId) { this.server.to(data.userId).emit('groupMessage', { code: RCode.FAIL, msg: '群消息发送错误', data: '' }) return } if ( data.messageType === 'file' || data.messageType === 'image' || data.messageType === 'video' ) { // 根据文件类型判断保存路径 const SAVE_PATH = data.messageType === 'image' ? IMAGE_SAVE_PATH : FILE_SAVE_PATH const saveName = data.messageType === 'image' ? `${Date.now()}$${data.userId}$${data.width}$${data.height}` : `${Date.now()}$${data.userId}$${formatBytes(data.size)}$${ data.fileName }` console.log(data.content) const stream = createWriteStream(join(SAVE_PATH, saveName)) stream.write(data.content) data.content = saveName } console.log(data.groupId) data.time = new Date().valueOf() // 使用服务端时间 await this.groupMessageRepository.save(data) this.server.to(data.groupId).emit('groupMessage', { code: RCode.OK, msg: '', data: { ...data, username: isUser.username // 此处返回发消息人姓名 } }) } else { this.server .to(data.userId) .emit('groupMessage', { code: RCode.FAIL, msg: '你没资格发消息' }) } } // 添加好友 @UseGuards(WsJwtGuard) @SubscribeMessage('addFriend') async addFriend( @ConnectedSocket() client: Socket, @MessageBody() data: UserFriendMap ): Promise<any> { const isUser = await this.userRepository.findOne({ userId: data.userId }) if (isUser) { if (data.friendId && data.userId) { if (data.userId === data.friendId) { this.server.to(data.userId).emit('addFriend', { code: RCode.FAIL, msg: '不能添加自己为好友', data: '' }) return } const relation1 = await this.friendRepository.findOne({ userId: data.userId, friendId: data.friendId }) const relation2 = await this.friendRepository.findOne({ userId: data.friendId, friendId: data.userId }) const roomId = data.userId > data.friendId ? data.userId + data.friendId : data.friendId + data.userId if (relation1 || relation2) { this.server.to(data.userId).emit('addFriend', { code: RCode.FAIL, msg: '已经有该好友', data: data }) return } let friend = (await this.userRepository.findOne({ userId: data.friendId })) as FriendDto const user = (await this.userRepository.findOne({ userId: data.userId })) as FriendDto if (!friend) { // 此处逻辑定制,如果为选择组织架构添加好友 // 好友不存在的情况下默认帮好友注册 if (data.friendUserName) { const res = await this.authService.register({ userId: data.friendId, username: data.friendUserName, avatar: '', role: 'user', tag: '', status: 'on', createTime: new Date().valueOf(), password: defaultPassword }) friend = res.data.user // 默认添加机器人为好友 await this.friendRepository.save({ userId: friend.userId, friendId: defaultRobotId }) } else { this.server.to(data.userId).emit('addFriend', { code: RCode.FAIL, msg: '该好友不存在', data: '' }) return } } // 双方都添加好友 并存入数据库 await this.friendRepository.save(data) const friendData = JSON.parse(JSON.stringify(data)) const friendId = friendData.friendId friendData.friendId = friendData.userId friendData.userId = friendId delete friendData._id await this.friendRepository.save(friendData) client.join(roomId) // 如果是删掉的好友重新加, 重新获取一遍私聊消息 let messages = await getRepository(FriendMessage) .createQueryBuilder('friendMessage') .orderBy('friendMessage.time', 'DESC') .where( 'friendMessage.userId = :userId AND friendMessage.friendId = :friendId', { userId: data.userId, friendId: data.friendId } ) .orWhere( 'friendMessage.userId = :friendId AND friendMessage.friendId = :userId', { userId: data.userId, friendId: data.friendId } ) .take(30) .getMany() messages = messages.reverse() if (messages.length) { // @ts-ignore friend.messages = messages // @ts-ignore user.messages = messages } // @ts-ignore; let onlineUserIdArr = Object.values(this.server.engine.clients).map( item => { // @ts-ignore; return item.request._query.userId } ) // 所有在线用户userId // 数组去重 onlineUserIdArr = Array.from(new Set(onlineUserIdArr)) // 好友是否在线 friend.online = onlineUserIdArr.includes(friend.userId) ? 1 : 0 this.server.to(data.userId).emit('addFriend', { code: RCode.OK, msg: `添加好友${friend.username}成功`, data: friend }) // 发起添加的人默认在线 user.online = 1 this.server.to(data.friendId).emit('addFriend', { code: RCode.OK, msg: `${user.username}添加你为好友`, data: user }) } } else { this.server .to(data.userId) .emit('addFriend', { code: RCode.FAIL, msg: '你没资格加好友' }) } } // 加入私聊的socket连接 @UseGuards(WsJwtGuard) @SubscribeMessage('joinFriendSocket') async joinFriend( @ConnectedSocket() client: Socket, @MessageBody() data: UserMap ): Promise<any> { if (data.friendId && data.userId) { const relation = await this.friendRepository.findOne({ userId: data.userId, friendId: data.friendId }) const roomId = data.userId > data.friendId ? data.userId + data.friendId : data.friendId + data.userId if (relation) { client.join(roomId) this.server.to(data.userId).emit('joinFriendSocket', { code: RCode.OK, msg: '进入私聊socket成功', data: relation }) } } } // 发送私聊消息 @UseGuards(WsJwtGuard) @SubscribeMessage('friendMessage') async friendMessage( @ConnectedSocket() client: Socket, @MessageBody() data: FriendMessageDto ): Promise<any> { const isUser = await this.userRepository.findOne({ userId: data.userId }) if (isUser) { if (data.userId && data.friendId) { const roomId = data.userId > data.friendId ? data.userId + data.friendId : data.friendId + data.userId // 根据文件类型判断保存路径 if ( data.messageType === 'file' || data.messageType === 'image' || data.messageType === 'video' ) { const SAVE_PATH = data.messageType === 'image' ? IMAGE_SAVE_PATH : FILE_SAVE_PATH const saveName = data.messageType === 'image' ? `${Date.now()}$${data.userId}$${data.width}$${data.height}` : `${Date.now()}$${data.userId}$${formatBytes(data.size)}$${ data.fileName }` console.log(data.content) const stream = createWriteStream(join(SAVE_PATH, saveName)) stream.write(data.content) data.content = saveName console.log(roomId) console.log(data.friendId) } data.time = new Date().valueOf() await this.friendMessageRepository.save(data) this.server .to(roomId) .emit('friendMessage', { code: RCode.OK, msg: '', data }) // 如果friendID 为机器人,则需要自动回复 // 获取自动回复内容 if (data.friendId === defaultRobotId) { this.autoReply(data, roomId) } } } else { this.server.to(data.userId).emit('friendMessage', { code: RCode.FAIL, msg: '你没资格发消息', data }) } } // 通过输入内容模糊匹配自动回复词条 async getReplyMessage(content: string) { const failMessage = '智能助手不知道你在说什么。' try { // 此处引用分词器进行中文分词 // nodejieba // https://github.com/yanyiwu/nodejieba const splitWords = nodejieba.cut(content).join(' ') console.log(splitWords) const res = await getElasticData(splitWords) console.log(res.data) const result = res.data.hits.hits if (result.length > 0) { return result[0]._source.title } return failMessage } catch (e) { return failMessage } } // 机器人自动回复 async autoReply(data, roomId) { // 获取自动回复内容 const message = await this.getReplyMessage(data.content) const reply = { time: new Date().valueOf(), content: message, userId: defaultRobotId, friendId: data.userId, messageType: 'text' } // 保存至好友消息表 await this.friendMessageRepository.save(reply) this.server .to(roomId) .emit('friendMessage', { code: RCode.OK, msg: '', data: reply }) } // 获取所有群和好友数据 @UseGuards(WsJwtGuard) @SubscribeMessage('chatData') async getAllData(@MessageBody() token: string): Promise<any> { const user = this.authService.verifyUser(token) if (user) { const isUser = await this.userRepository.findOne({ userId: user.userId }) let groupArr: GroupDto[] = [] let friendArr: FriendDto[] = [] const userGather: { [key: string]: User } = {} let userArr: FriendDto[] = [] // @ts-ignore; let onlineUserIdArr = Object.values(this.server.engine.clients).map( item => { // @ts-ignore; return item.request._query.userId } ) // 所有在线用户userId // 数组去重 onlineUserIdArr = Array.from(new Set(onlineUserIdArr)) // 找到用户所属的群 const groups: GroupDto[] = await getRepository(Group) .createQueryBuilder('group') .innerJoin( 'group_map', 'group_map', 'group_map.groupId = group.groupId' ) .select('group.groupName', 'groupName') .addSelect('group.groupId', 'groupId') .addSelect('group.notice', 'notice') .addSelect('group.userId', 'userId') .addSelect('group_map.createTime', 'createTime') // 获取用户进群时间 .where('group_map.userId = :id', { id: isUser.userId }) .getRawMany() // 找到用户所有好友 const friends: FriendDto[] = await getRepository(User) .createQueryBuilder('user') .select('user.userId', 'userId') .addSelect('user.username', 'username') .addSelect('user.avatar', 'avatar') .addSelect('user.role', 'role') .where((qb: any) => { const subQuery = qb .subQuery() .select('s.userId') .innerJoin('user_map', 'p', 'p.friendId = s.userId') .from(`user`, 's') .where('p.userId = :userId', { userId: isUser.userId }) .getQuery() // tslint:disable-next-line:prefer-template return 'user.userId IN ' + subQuery }) .getRawMany() // 获取所有群聊消息 const groupMessagePromise = groups.map(async item => { const createTime = item.createTime // 用户进群时间 const groupMessage = await getRepository(GroupMessage) .createQueryBuilder('group_message') .innerJoin('user', 'user', 'user.userId = group_message.userId') .select('group_message.*') .addSelect('user.username', 'username') .orderBy('group_message.time', 'DESC') .where('group_message.groupId = :id', { id: item.groupId }) .andWhere('group_message.time >= :createTime', { createTime: createTime - defaultGroupMessageTime // 新用户进群默认可以看群近24小时消息 }) .limit(10) .getRawMany() groupMessage.reverse() // 这里获取一下发消息的用户的用户信息 for (const message of groupMessage) { if (!userGather[message.userId]) { userGather[message.userId] = await this.userRepository.findOne({ userId: message.userId }) } } return groupMessage }) // 好友消息 const friendMessagePromise = friends.map(async item => { const messages = await getRepository(FriendMessage) .createQueryBuilder('friendMessage') .orderBy('friendMessage.time', 'DESC') .where( 'friendMessage.userId = :userId AND friendMessage.friendId = :friendId', { userId: user.userId, friendId: item.userId } ) .orWhere( 'friendMessage.userId = :friendId AND friendMessage.friendId = :userId', { userId: user.userId, friendId: item.userId } ) .take(10) .getMany() return messages.reverse() }) const groupsMessage: Array<GroupMessageDto[]> = await Promise.all( groupMessagePromise ) await Promise.all( groups.map(async (group, index) => { if (groupsMessage[index] && groupsMessage[index].length) { group.messages = groupsMessage[index] } group.members = [] // 获取群成员信息 const groupUserArr = await this.groupUserRepository.find({ groupId: group.groupId }) if (groupUserArr.length) { for (const u of groupUserArr) { const _user: FriendDto = await this.userRepository.findOne({ userId: u.userId }) if (_user) { // 设置群成员是否在线 onlineUserIdArr.includes(_user.userId) ? ((_user as FriendDto).online = 1) : ((_user as FriendDto).online = 0) // 检查是否为群主 _user.isManager = _user.userId === group.userId ? 1 : 0 group.members.push(_user) } } } return Promise.resolve(group) }) ) groupArr = groups const friendsMessage: Array<FriendMessageDto[]> = await Promise.all( friendMessagePromise ) friends.map((friend, index) => { if (friendsMessage[index] && friendsMessage[index].length) { friend.messages = friendsMessage[index] } // 设置好友在线状态 friend.online = onlineUserIdArr.includes(friend.userId) ? 1 : 0 }) friendArr = friends userArr = [...Object.values(userGather), ...friendArr] this.server.to(user.userId).emit('chatData', { code: RCode.OK, msg: '获取聊天数据成功', data: { groupData: groupArr, friendData: friendArr, userData: userArr } }) } } // 退群 @UseGuards(WsJwtGuard) @SubscribeMessage('exitGroup') async exitGroup( @ConnectedSocket() client: Socket, @MessageBody() groupMap: GroupMap ): Promise<any> { if (groupMap.groupId === defaultGroupId) { return this.server .to(groupMap.userId) .emit('exitGroup', { code: RCode.FAIL, msg: '默认群不可退' }) } const user = await this.userRepository.findOne({ userId: groupMap.userId }) const group = await this.groupRepository.findOne({ groupId: groupMap.groupId }) const map = await this.groupUserRepository.findOne({ userId: groupMap.userId, groupId: groupMap.groupId }) if (user && group && map) { await this.groupUserRepository.remove(map) return this.server .to(groupMap.groupId) .emit('exitGroup', { code: RCode.OK, msg: '退群成功', data: groupMap }) } this.server .to(groupMap.userId) .emit('exitGroup', { code: RCode.FAIL, msg: '退群失败' }) } // 删好友 @UseGuards(WsJwtGuard) @SubscribeMessage('exitFriend') async exitFriend( @ConnectedSocket() client: Socket, @MessageBody() userMap: UserMap ): Promise<any> { const user = await this.userRepository.findOne({ userId: userMap.userId }) const friend = await this.userRepository.findOne({ userId: userMap.friendId }) const map1 = await this.friendRepository.findOne({ userId: userMap.userId, friendId: userMap.friendId }) const map2 = await this.friendRepository.findOne({ userId: userMap.friendId, friendId: userMap.userId }) if (user && friend && map1 && map2) { await this.friendRepository.remove(map1) await this.friendRepository.remove(map2) return this.server.to(userMap.userId).emit('exitFriend', { code: RCode.OK, msg: '删好友成功', data: userMap }) } this.server .to(userMap.userId) .emit('exitFriend', { code: RCode.FAIL, msg: '删好友失败' }) } // 消息撤回 @UseGuards(WsJwtGuard) @SubscribeMessage('revokeMessage') async revokeMessage( @ConnectedSocket() client: Socket, @MessageBody() messageDto: GroupMessageDto & FriendMessageDto ): Promise<any> { // 先判断groupId是否有值,有值的话撤回的是群聊消息 if (messageDto.groupId) { const groupMessage = await this.groupMessageRepository.findOne( messageDto._id ) await this.groupMessageRepository.remove(groupMessage) return this.server.to(messageDto.groupId).emit('revokeMessage', { code: RCode.OK, msg: '已撤回了一条消息', data: messageDto }) } else { const friendMessage = await this.friendMessageRepository.findOne( messageDto._id ) const roomId = messageDto.userId > messageDto.friendId ? messageDto.userId + messageDto.friendId : messageDto.friendId + messageDto.userId console.log('消息撤回---' + messageDto._id) await this.friendMessageRepository.remove(friendMessage) return this.server.to(roomId).emit('revokeMessage', { code: RCode.OK, msg: '已撤回了一条消息', data: messageDto }) } } // 更新群信息(公告,群名) @UseGuards(WsJwtGuard) @SubscribeMessage('updateGroupInfo') async updateGroupNotice(@MessageBody() data: GroupDto): Promise<any> { console.log(data) const group = await this.groupRepository.findOne(data.groupId) group.groupName = data.groupName group.notice = data.notice const res = await this.groupService.update(group) this.server.to(data.groupId).emit('updateGroupInfo', res) return } // 更新用户信息(头像\用户名) @UseGuards(WsJwtGuard) @SubscribeMessage('updateUserInfo') async updateUserInfo( @ConnectedSocket() client: Socket, @MessageBody() userId ): Promise<any> { const user = await this.userRepository.findOne({ userId }) // 广播给所有用户我的信息更新了 client.broadcast.emit('updateUserInfo', { code: RCode.OK, msg: 'userOnline', data: user }) } // 邀请好友入群 @UseGuards(WsJwtGuard) @SubscribeMessage('inviteFriendsIntoGroup') async inviteFriendsIntoGroup( @MessageBody() data: FriendsIntoGroup ): Promise<any> { try { // 获取所有邀请好友 const isUser = await this.userRepository.findOne({ userId: data.userId }) const group = await this.groupRepository.findOne({ groupId: data.groupId }) const res = { group: group, friendIds: data.friendIds, userId: data.userId, invited: true // 标记为,此处跟单人加群区分 } if (isUser) { for (const friendId of data.friendIds) { if (group) { data.groupId = group.groupId await this.groupUserRepository.save({ groupId: data.groupId, userId: friendId }) // 广播所有被邀请者 (此处暂不判断该好友是否在线,统一广播,后期可优化) this.server.to(friendId).emit('joinGroup', { code: RCode.OK, msg: isUser.username + '邀请您加入群聊' + group.groupName, data: res }) } } console.log('inviteFriendsIntoGroup', res) this.server.to(group.groupId).emit('joinGroup', { code: RCode.OK, msg: '邀请' + data.friendIds.length + '位好友加入群聊', data: res }) } } catch (error) { this.server.to(data.userId).emit('joinGroup', { code: RCode.FAIL, msg: '邀请失败:' + error, data: null }) } } }
the_stack
import { AcceleratorTypesClient, AddressesClient, AutoscalersClient, BackendBucketsClient, BackendServicesClient, DisksClient, DiskTypesClient, ExternalVpnGatewaysClient, FirewallPoliciesClient, FirewallsClient, ForwardingRulesClient, GlobalAddressesClient, GlobalForwardingRulesClient, GlobalNetworkEndpointGroupsClient, GlobalOperationsClient, GlobalOrganizationOperationsClient, GlobalPublicDelegatedPrefixesClient, HealthChecksClient, ImageFamilyViewsClient, ImagesClient, InstanceGroupManagersClient, InstanceGroupsClient, InstancesClient, InstanceTemplatesClient, InterconnectAttachmentsClient, InterconnectLocationsClient, InterconnectsClient, LicenseCodesClient, LicensesClient, MachineTypesClient, NetworkEndpointGroupsClient, NetworksClient, NodeGroupsClient, NodeTemplatesClient, NodeTypesClient, PacketMirroringsClient, ProjectsClient, PublicAdvertisedPrefixesClient, PublicDelegatedPrefixesClient, RegionAutoscalersClient, RegionBackendServicesClient, RegionCommitmentsClient, RegionDisksClient, RegionDiskTypesClient, RegionHealthChecksClient, RegionHealthCheckServicesClient, RegionInstanceGroupManagersClient, RegionInstanceGroupsClient, RegionInstancesClient, RegionNetworkEndpointGroupsClient, RegionNotificationEndpointsClient, RegionOperationsClient, RegionsClient, RegionSslCertificatesClient, RegionTargetHttpProxiesClient, RegionTargetHttpsProxiesClient, RegionUrlMapsClient, ReservationsClient, ResourcePoliciesClient, RoutersClient, RoutesClient, SecurityPoliciesClient, ServiceAttachmentsClient, SnapshotsClient, SslCertificatesClient, SslPoliciesClient, SubnetworksClient, TargetGrpcProxiesClient, TargetHttpProxiesClient, TargetHttpsProxiesClient, TargetInstancesClient, TargetPoolsClient, TargetSslProxiesClient, TargetTcpProxiesClient, TargetVpnGatewaysClient, UrlMapsClient, VpnGatewaysClient, VpnTunnelsClient, ZoneOperationsClient, ZonesClient, } from '@google-cloud/compute'; // check that the client class type name can be used function doStuffWithAcceleratorTypesClient(client: AcceleratorTypesClient) { client.close(); } function doStuffWithAddressesClient(client: AddressesClient) { client.close(); } function doStuffWithAutoscalersClient(client: AutoscalersClient) { client.close(); } function doStuffWithBackendBucketsClient(client: BackendBucketsClient) { client.close(); } function doStuffWithBackendServicesClient(client: BackendServicesClient) { client.close(); } function doStuffWithDisksClient(client: DisksClient) { client.close(); } function doStuffWithDiskTypesClient(client: DiskTypesClient) { client.close(); } function doStuffWithExternalVpnGatewaysClient( client: ExternalVpnGatewaysClient ) { client.close(); } function doStuffWithFirewallPoliciesClient(client: FirewallPoliciesClient) { client.close(); } function doStuffWithFirewallsClient(client: FirewallsClient) { client.close(); } function doStuffWithForwardingRulesClient(client: ForwardingRulesClient) { client.close(); } function doStuffWithGlobalAddressesClient(client: GlobalAddressesClient) { client.close(); } function doStuffWithGlobalForwardingRulesClient( client: GlobalForwardingRulesClient ) { client.close(); } function doStuffWithGlobalNetworkEndpointGroupsClient( client: GlobalNetworkEndpointGroupsClient ) { client.close(); } function doStuffWithGlobalOperationsClient(client: GlobalOperationsClient) { client.close(); } function doStuffWithGlobalOrganizationOperationsClient( client: GlobalOrganizationOperationsClient ) { client.close(); } function doStuffWithGlobalPublicDelegatedPrefixesClient( client: GlobalPublicDelegatedPrefixesClient ) { client.close(); } function doStuffWithHealthChecksClient(client: HealthChecksClient) { client.close(); } function doStuffWithImageFamilyViewsClient(client: ImageFamilyViewsClient) { client.close(); } function doStuffWithImagesClient(client: ImagesClient) { client.close(); } function doStuffWithInstanceGroupManagersClient( client: InstanceGroupManagersClient ) { client.close(); } function doStuffWithInstanceGroupsClient(client: InstanceGroupsClient) { client.close(); } function doStuffWithInstancesClient(client: InstancesClient) { client.close(); } function doStuffWithInstanceTemplatesClient(client: InstanceTemplatesClient) { client.close(); } function doStuffWithInterconnectAttachmentsClient( client: InterconnectAttachmentsClient ) { client.close(); } function doStuffWithInterconnectLocationsClient( client: InterconnectLocationsClient ) { client.close(); } function doStuffWithInterconnectsClient(client: InterconnectsClient) { client.close(); } function doStuffWithLicenseCodesClient(client: LicenseCodesClient) { client.close(); } function doStuffWithLicensesClient(client: LicensesClient) { client.close(); } function doStuffWithMachineTypesClient(client: MachineTypesClient) { client.close(); } function doStuffWithNetworkEndpointGroupsClient( client: NetworkEndpointGroupsClient ) { client.close(); } function doStuffWithNetworksClient(client: NetworksClient) { client.close(); } function doStuffWithNodeGroupsClient(client: NodeGroupsClient) { client.close(); } function doStuffWithNodeTemplatesClient(client: NodeTemplatesClient) { client.close(); } function doStuffWithNodeTypesClient(client: NodeTypesClient) { client.close(); } function doStuffWithPacketMirroringsClient(client: PacketMirroringsClient) { client.close(); } function doStuffWithProjectsClient(client: ProjectsClient) { client.close(); } function doStuffWithPublicAdvertisedPrefixesClient( client: PublicAdvertisedPrefixesClient ) { client.close(); } function doStuffWithPublicDelegatedPrefixesClient( client: PublicDelegatedPrefixesClient ) { client.close(); } function doStuffWithRegionAutoscalersClient(client: RegionAutoscalersClient) { client.close(); } function doStuffWithRegionBackendServicesClient( client: RegionBackendServicesClient ) { client.close(); } function doStuffWithRegionCommitmentsClient(client: RegionCommitmentsClient) { client.close(); } function doStuffWithRegionDisksClient(client: RegionDisksClient) { client.close(); } function doStuffWithRegionDiskTypesClient(client: RegionDiskTypesClient) { client.close(); } function doStuffWithRegionHealthChecksClient(client: RegionHealthChecksClient) { client.close(); } function doStuffWithRegionHealthCheckServicesClient( client: RegionHealthCheckServicesClient ) { client.close(); } function doStuffWithRegionInstanceGroupManagersClient( client: RegionInstanceGroupManagersClient ) { client.close(); } function doStuffWithRegionInstanceGroupsClient( client: RegionInstanceGroupsClient ) { client.close(); } function doStuffWithRegionInstancesClient(client: RegionInstancesClient) { client.close(); } function doStuffWithRegionNetworkEndpointGroupsClient( client: RegionNetworkEndpointGroupsClient ) { client.close(); } function doStuffWithRegionNotificationEndpointsClient( client: RegionNotificationEndpointsClient ) { client.close(); } function doStuffWithRegionOperationsClient(client: RegionOperationsClient) { client.close(); } function doStuffWithRegionsClient(client: RegionsClient) { client.close(); } function doStuffWithRegionSslCertificatesClient( client: RegionSslCertificatesClient ) { client.close(); } function doStuffWithRegionTargetHttpProxiesClient( client: RegionTargetHttpProxiesClient ) { client.close(); } function doStuffWithRegionTargetHttpsProxiesClient( client: RegionTargetHttpsProxiesClient ) { client.close(); } function doStuffWithRegionUrlMapsClient(client: RegionUrlMapsClient) { client.close(); } function doStuffWithReservationsClient(client: ReservationsClient) { client.close(); } function doStuffWithResourcePoliciesClient(client: ResourcePoliciesClient) { client.close(); } function doStuffWithRoutersClient(client: RoutersClient) { client.close(); } function doStuffWithRoutesClient(client: RoutesClient) { client.close(); } function doStuffWithSecurityPoliciesClient(client: SecurityPoliciesClient) { client.close(); } function doStuffWithServiceAttachmentsClient(client: ServiceAttachmentsClient) { client.close(); } function doStuffWithSnapshotsClient(client: SnapshotsClient) { client.close(); } function doStuffWithSslCertificatesClient(client: SslCertificatesClient) { client.close(); } function doStuffWithSslPoliciesClient(client: SslPoliciesClient) { client.close(); } function doStuffWithSubnetworksClient(client: SubnetworksClient) { client.close(); } function doStuffWithTargetGrpcProxiesClient(client: TargetGrpcProxiesClient) { client.close(); } function doStuffWithTargetHttpProxiesClient(client: TargetHttpProxiesClient) { client.close(); } function doStuffWithTargetHttpsProxiesClient(client: TargetHttpsProxiesClient) { client.close(); } function doStuffWithTargetInstancesClient(client: TargetInstancesClient) { client.close(); } function doStuffWithTargetPoolsClient(client: TargetPoolsClient) { client.close(); } function doStuffWithTargetSslProxiesClient(client: TargetSslProxiesClient) { client.close(); } function doStuffWithTargetTcpProxiesClient(client: TargetTcpProxiesClient) { client.close(); } function doStuffWithTargetVpnGatewaysClient(client: TargetVpnGatewaysClient) { client.close(); } function doStuffWithUrlMapsClient(client: UrlMapsClient) { client.close(); } function doStuffWithVpnGatewaysClient(client: VpnGatewaysClient) { client.close(); } function doStuffWithVpnTunnelsClient(client: VpnTunnelsClient) { client.close(); } function doStuffWithZoneOperationsClient(client: ZoneOperationsClient) { client.close(); } function doStuffWithZonesClient(client: ZonesClient) { client.close(); } function main() { // check that the client instance can be created const acceleratorTypesClient = new AcceleratorTypesClient(); doStuffWithAcceleratorTypesClient(acceleratorTypesClient); // check that the client instance can be created const addressesClient = new AddressesClient(); doStuffWithAddressesClient(addressesClient); // check that the client instance can be created const autoscalersClient = new AutoscalersClient(); doStuffWithAutoscalersClient(autoscalersClient); // check that the client instance can be created const backendBucketsClient = new BackendBucketsClient(); doStuffWithBackendBucketsClient(backendBucketsClient); // check that the client instance can be created const backendServicesClient = new BackendServicesClient(); doStuffWithBackendServicesClient(backendServicesClient); // check that the client instance can be created const disksClient = new DisksClient(); doStuffWithDisksClient(disksClient); // check that the client instance can be created const diskTypesClient = new DiskTypesClient(); doStuffWithDiskTypesClient(diskTypesClient); // check that the client instance can be created const externalVpnGatewaysClient = new ExternalVpnGatewaysClient(); doStuffWithExternalVpnGatewaysClient(externalVpnGatewaysClient); // check that the client instance can be created const firewallPoliciesClient = new FirewallPoliciesClient(); doStuffWithFirewallPoliciesClient(firewallPoliciesClient); // check that the client instance can be created const firewallsClient = new FirewallsClient(); doStuffWithFirewallsClient(firewallsClient); // check that the client instance can be created const forwardingRulesClient = new ForwardingRulesClient(); doStuffWithForwardingRulesClient(forwardingRulesClient); // check that the client instance can be created const globalAddressesClient = new GlobalAddressesClient(); doStuffWithGlobalAddressesClient(globalAddressesClient); // check that the client instance can be created const globalForwardingRulesClient = new GlobalForwardingRulesClient(); doStuffWithGlobalForwardingRulesClient(globalForwardingRulesClient); // check that the client instance can be created const globalNetworkEndpointGroupsClient = new GlobalNetworkEndpointGroupsClient(); doStuffWithGlobalNetworkEndpointGroupsClient( globalNetworkEndpointGroupsClient ); // check that the client instance can be created const globalOperationsClient = new GlobalOperationsClient(); doStuffWithGlobalOperationsClient(globalOperationsClient); // check that the client instance can be created const globalOrganizationOperationsClient = new GlobalOrganizationOperationsClient(); doStuffWithGlobalOrganizationOperationsClient( globalOrganizationOperationsClient ); // check that the client instance can be created const globalPublicDelegatedPrefixesClient = new GlobalPublicDelegatedPrefixesClient(); doStuffWithGlobalPublicDelegatedPrefixesClient( globalPublicDelegatedPrefixesClient ); // check that the client instance can be created const healthChecksClient = new HealthChecksClient(); doStuffWithHealthChecksClient(healthChecksClient); // check that the client instance can be created const imageFamilyViewsClient = new ImageFamilyViewsClient(); doStuffWithImageFamilyViewsClient(imageFamilyViewsClient); // check that the client instance can be created const imagesClient = new ImagesClient(); doStuffWithImagesClient(imagesClient); // check that the client instance can be created const instanceGroupManagersClient = new InstanceGroupManagersClient(); doStuffWithInstanceGroupManagersClient(instanceGroupManagersClient); // check that the client instance can be created const instanceGroupsClient = new InstanceGroupsClient(); doStuffWithInstanceGroupsClient(instanceGroupsClient); // check that the client instance can be created const instancesClient = new InstancesClient(); doStuffWithInstancesClient(instancesClient); // check that the client instance can be created const instanceTemplatesClient = new InstanceTemplatesClient(); doStuffWithInstanceTemplatesClient(instanceTemplatesClient); // check that the client instance can be created const interconnectAttachmentsClient = new InterconnectAttachmentsClient(); doStuffWithInterconnectAttachmentsClient(interconnectAttachmentsClient); // check that the client instance can be created const interconnectLocationsClient = new InterconnectLocationsClient(); doStuffWithInterconnectLocationsClient(interconnectLocationsClient); // check that the client instance can be created const interconnectsClient = new InterconnectsClient(); doStuffWithInterconnectsClient(interconnectsClient); // check that the client instance can be created const licenseCodesClient = new LicenseCodesClient(); doStuffWithLicenseCodesClient(licenseCodesClient); // check that the client instance can be created const licensesClient = new LicensesClient(); doStuffWithLicensesClient(licensesClient); // check that the client instance can be created const machineTypesClient = new MachineTypesClient(); doStuffWithMachineTypesClient(machineTypesClient); // check that the client instance can be created const networkEndpointGroupsClient = new NetworkEndpointGroupsClient(); doStuffWithNetworkEndpointGroupsClient(networkEndpointGroupsClient); // check that the client instance can be created const networksClient = new NetworksClient(); doStuffWithNetworksClient(networksClient); // check that the client instance can be created const nodeGroupsClient = new NodeGroupsClient(); doStuffWithNodeGroupsClient(nodeGroupsClient); // check that the client instance can be created const nodeTemplatesClient = new NodeTemplatesClient(); doStuffWithNodeTemplatesClient(nodeTemplatesClient); // check that the client instance can be created const nodeTypesClient = new NodeTypesClient(); doStuffWithNodeTypesClient(nodeTypesClient); // check that the client instance can be created const packetMirroringsClient = new PacketMirroringsClient(); doStuffWithPacketMirroringsClient(packetMirroringsClient); // check that the client instance can be created const projectsClient = new ProjectsClient(); doStuffWithProjectsClient(projectsClient); // check that the client instance can be created const publicAdvertisedPrefixesClient = new PublicAdvertisedPrefixesClient(); doStuffWithPublicAdvertisedPrefixesClient(publicAdvertisedPrefixesClient); // check that the client instance can be created const publicDelegatedPrefixesClient = new PublicDelegatedPrefixesClient(); doStuffWithPublicDelegatedPrefixesClient(publicDelegatedPrefixesClient); // check that the client instance can be created const regionAutoscalersClient = new RegionAutoscalersClient(); doStuffWithRegionAutoscalersClient(regionAutoscalersClient); // check that the client instance can be created const regionBackendServicesClient = new RegionBackendServicesClient(); doStuffWithRegionBackendServicesClient(regionBackendServicesClient); // check that the client instance can be created const regionCommitmentsClient = new RegionCommitmentsClient(); doStuffWithRegionCommitmentsClient(regionCommitmentsClient); // check that the client instance can be created const regionDisksClient = new RegionDisksClient(); doStuffWithRegionDisksClient(regionDisksClient); // check that the client instance can be created const regionDiskTypesClient = new RegionDiskTypesClient(); doStuffWithRegionDiskTypesClient(regionDiskTypesClient); // check that the client instance can be created const regionHealthChecksClient = new RegionHealthChecksClient(); doStuffWithRegionHealthChecksClient(regionHealthChecksClient); // check that the client instance can be created const regionHealthCheckServicesClient = new RegionHealthCheckServicesClient(); doStuffWithRegionHealthCheckServicesClient(regionHealthCheckServicesClient); // check that the client instance can be created const regionInstanceGroupManagersClient = new RegionInstanceGroupManagersClient(); doStuffWithRegionInstanceGroupManagersClient( regionInstanceGroupManagersClient ); // check that the client instance can be created const regionInstanceGroupsClient = new RegionInstanceGroupsClient(); doStuffWithRegionInstanceGroupsClient(regionInstanceGroupsClient); // check that the client instance can be created const regionInstancesClient = new RegionInstancesClient(); doStuffWithRegionInstancesClient(regionInstancesClient); // check that the client instance can be created const regionNetworkEndpointGroupsClient = new RegionNetworkEndpointGroupsClient(); doStuffWithRegionNetworkEndpointGroupsClient( regionNetworkEndpointGroupsClient ); // check that the client instance can be created const regionNotificationEndpointsClient = new RegionNotificationEndpointsClient(); doStuffWithRegionNotificationEndpointsClient( regionNotificationEndpointsClient ); // check that the client instance can be created const regionOperationsClient = new RegionOperationsClient(); doStuffWithRegionOperationsClient(regionOperationsClient); // check that the client instance can be created const regionsClient = new RegionsClient(); doStuffWithRegionsClient(regionsClient); // check that the client instance can be created const regionSslCertificatesClient = new RegionSslCertificatesClient(); doStuffWithRegionSslCertificatesClient(regionSslCertificatesClient); // check that the client instance can be created const regionTargetHttpProxiesClient = new RegionTargetHttpProxiesClient(); doStuffWithRegionTargetHttpProxiesClient(regionTargetHttpProxiesClient); // check that the client instance can be created const regionTargetHttpsProxiesClient = new RegionTargetHttpsProxiesClient(); doStuffWithRegionTargetHttpsProxiesClient(regionTargetHttpsProxiesClient); // check that the client instance can be created const regionUrlMapsClient = new RegionUrlMapsClient(); doStuffWithRegionUrlMapsClient(regionUrlMapsClient); // check that the client instance can be created const reservationsClient = new ReservationsClient(); doStuffWithReservationsClient(reservationsClient); // check that the client instance can be created const resourcePoliciesClient = new ResourcePoliciesClient(); doStuffWithResourcePoliciesClient(resourcePoliciesClient); // check that the client instance can be created const routersClient = new RoutersClient(); doStuffWithRoutersClient(routersClient); // check that the client instance can be created const routesClient = new RoutesClient(); doStuffWithRoutesClient(routesClient); // check that the client instance can be created const securityPoliciesClient = new SecurityPoliciesClient(); doStuffWithSecurityPoliciesClient(securityPoliciesClient); // check that the client instance can be created const serviceAttachmentsClient = new ServiceAttachmentsClient(); doStuffWithServiceAttachmentsClient(serviceAttachmentsClient); // check that the client instance can be created const snapshotsClient = new SnapshotsClient(); doStuffWithSnapshotsClient(snapshotsClient); // check that the client instance can be created const sslCertificatesClient = new SslCertificatesClient(); doStuffWithSslCertificatesClient(sslCertificatesClient); // check that the client instance can be created const sslPoliciesClient = new SslPoliciesClient(); doStuffWithSslPoliciesClient(sslPoliciesClient); // check that the client instance can be created const subnetworksClient = new SubnetworksClient(); doStuffWithSubnetworksClient(subnetworksClient); // check that the client instance can be created const targetGrpcProxiesClient = new TargetGrpcProxiesClient(); doStuffWithTargetGrpcProxiesClient(targetGrpcProxiesClient); // check that the client instance can be created const targetHttpProxiesClient = new TargetHttpProxiesClient(); doStuffWithTargetHttpProxiesClient(targetHttpProxiesClient); // check that the client instance can be created const targetHttpsProxiesClient = new TargetHttpsProxiesClient(); doStuffWithTargetHttpsProxiesClient(targetHttpsProxiesClient); // check that the client instance can be created const targetInstancesClient = new TargetInstancesClient(); doStuffWithTargetInstancesClient(targetInstancesClient); // check that the client instance can be created const targetPoolsClient = new TargetPoolsClient(); doStuffWithTargetPoolsClient(targetPoolsClient); // check that the client instance can be created const targetSslProxiesClient = new TargetSslProxiesClient(); doStuffWithTargetSslProxiesClient(targetSslProxiesClient); // check that the client instance can be created const targetTcpProxiesClient = new TargetTcpProxiesClient(); doStuffWithTargetTcpProxiesClient(targetTcpProxiesClient); // check that the client instance can be created const targetVpnGatewaysClient = new TargetVpnGatewaysClient(); doStuffWithTargetVpnGatewaysClient(targetVpnGatewaysClient); // check that the client instance can be created const urlMapsClient = new UrlMapsClient(); doStuffWithUrlMapsClient(urlMapsClient); // check that the client instance can be created const vpnGatewaysClient = new VpnGatewaysClient(); doStuffWithVpnGatewaysClient(vpnGatewaysClient); // check that the client instance can be created const vpnTunnelsClient = new VpnTunnelsClient(); doStuffWithVpnTunnelsClient(vpnTunnelsClient); // check that the client instance can be created const zoneOperationsClient = new ZoneOperationsClient(); doStuffWithZoneOperationsClient(zoneOperationsClient); // check that the client instance can be created const zonesClient = new ZonesClient(); doStuffWithZonesClient(zonesClient); } main();
the_stack
// Copyright (c) 2009-2014 TJ Holowaychuk <tj@vision-media.ca> // Copyright (c) 2013-2014 Roman Shtylman <shtylman+expressjs@gmail.com> // Copyright (c) 2014-2015 Douglas Christopher Wilson <doug@somethingdoug.com> // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // 'Software'), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import ChildProcess from 'child_process' import _ from 'lodash' import request from 'request' import Rx from 'rx' import fs from 'fs' import jsyaml from 'js-yaml' class Kubectl { private type private binary private kubeconfig private namespace private endpoint private context constructor(type, conf) { this.type = type this.binary = conf.binary || 'kubectl' this.kubeconfig = conf.kubeconfig || '' this.namespace = conf.namespace || '' this.endpoint = conf.endpoint || '' this.context = conf.context || '' } private spawn(args, done) { const ops = [] if (this.kubeconfig) { ops.push('--kubeconfig=' + this.kubeconfig) } else { ops.push('-s') ops.push(this.endpoint) } if (this.namespace) { ops.push('--namespace=' + this.namespace) } if (this.context) { ops.push('--context=' + this.context) } const kube = ChildProcess.spawn(this.binary, ops.concat(args)), stdout = [], stderr = [] kube.stdout.on('data', (data) => { stdout.push(data.toString()) }) kube.stderr.on('data', (data) => { stderr.push(data.toString()) }) kube.on('close', (code) => { if (!stderr.length) return done(null, stdout.join('')) done(stderr.join('')) }) } private callbackFunction(primise, callback) { if (_.isFunction(callback)) { primise .then((data) => { callback(null, data) }) .catch((err) => { callback(err) }) } } public command(cmd, callback): Promise<any> { if (_.isString(cmd)) cmd = cmd.split(' ') const promise = new Promise((resolve, reject) => { this.spawn(cmd, (err, data) => { if (err) return reject(err || data) resolve(cmd.join(' ').indexOf('--output=json') > -1 ? JSON.parse(data) : data) }) }) this.callbackFunction(promise, callback) return promise } public list(selector, flags?, done?) { if (!this.type) throw new Error('not a function') if (typeof selector === 'object') { var args = '--selector=' for (var key in selector) args += key + '=' + selector[key] selector = args + '' } else { done = selector selector = '--output=json' } if (_.isFunction(flags)) { done = flags flags = null } flags = flags || [] const action = ['get', this.type, selector, '--output=json'].concat(flags) return this.command(action, done) } public get(name: string, flags?, done?: (err, data) => void) { if (!this.type) throw new Error('not a function') if (_.isFunction(flags)) { done = flags flags = null } flags = flags || [] const action = ['get', this.type, name, '--output=json'].concat(flags) return this.command(action, done) } public create(filepath: string, flags?, done?: (err, data) => void) { if (!this.type) throw new Error('not a function') if (_.isFunction(flags)) { done = flags flags = null } flags = flags || [] const action = ['create', '-f', filepath].concat(flags) return this.command(action, done) } public delete(id: string, flags, done?: (err, data) => void) { if (!this.type) throw new Error('not a function') if (_.isFunction(flags)) { done = flags flags = null } flags = flags || [] const action = ['delete', this.type, id].concat(flags) return this.command(action, done) } public update(filepath: string, flags?, done?: (err, data) => void) { if (!this.type) throw new Error('not a function') if (_.isFunction(flags)) { done = flags flags = null } flags = flags || [] const action = ['update', '-f', filepath].concat(flags) return this.command(action, done) } public apply(name: string, json: any, flags?, done?: (err, data) => void) { if (!this.type) throw new Error('not a function') if (_.isFunction(flags)) { done = flags flags = null } flags = flags || [] const action = ['update', this.type, name, '--patch=' + JSON.stringify(json)].concat(flags) return this.command(action, done) } public rollingUpdateByFile(name: string, filepath: string, flags?, done?: (err, data) => void) { if (this.type !== 'replicationcontrollers') throw new Error('not a function') if (_.isFunction(flags)) { done = flags flags = null } flags = flags || [] const action = ['rolling-update', name, '-f', filepath, '--update-period=0s'].concat(flags) return this.command(action, done) } public rollingUpdate(name: string, image: string, flags?, done?: (err, data) => void) { if (this.type !== 'replicationcontrollers') throw new Error('not a function') if (_.isFunction(flags)) { done = flags flags = null } flags = flags || [] const action = ['rolling-update', name, '--image=' + image, '--update-period=0s'].concat(flags) return this.command(action, done) } public scale(name: string, replicas: string, flags?, done?: (err, data) => void) { if (this.type !== 'replicationcontrollers' && this.type !== 'deployments') throw new Error('not a function') if (_.isFunction(flags)) { done = flags flags = null } flags = flags || [] const action = ['scale', '--replicas=' + replicas, 'replicationcontrollers', name].concat(flags) return this.command(action, done) } public logs(name: string, flags?, done?: (err, data) => void) { if (this.type !== 'pods') throw new Error('not a function') var action = new Array('logs') if (name.indexOf(' ') > -1) { var names = name.split(/ /) action.push(names[0]) action.push(names[1]) } else { action.push(name) } if (_.isFunction(flags)) { done = flags flags = null } flags = flags || [] return this.command(action.concat(flags), done) } public describe(name: string, flags?, done?: (err, data) => void) { if (!this.type) throw new Error('not a function') var action = ['describe', this.type] if (name === null) { action.push(name) } if (_.isFunction(flags)) { done = flags flags = null } flags = flags || [] return this.command(action.concat(flags), done) } public portForward(name: string, portString: string, done?: (err, data) => void) { if (this.type !== 'pods') throw new Error('not a function') var action = ['port-forward', name, portString] return this.command(action, done) } public useContext(context: string, done?: (err, data) => void) { var action = ['config', 'use-context', context] return this.command(action, done) } public viewContext(done?: (err, data) => void) { var action = ['config', '--output=json', 'view'] this.command(action, done) } } declare function require(name: string) export const kubectl = (conf): any => { return { // short names are just aliases to longer names pod: new Kubectl('pods', conf), po: new Kubectl('pods', conf), replicationcontroller: new Kubectl('replicationcontrollers', conf), rc: new Kubectl('replicationcontrollers', conf), service: new Kubectl('services', conf), svc: new Kubectl('services', conf), node: new Kubectl('nodes', conf), no: new Kubectl('nodes', conf), namespace: new Kubectl('namespaces', conf), ns: new Kubectl('namespaces', conf), deployment: new Kubectl('deployments', conf), daemonset: new Kubectl('daemonsets', conf), ds: new Kubectl('daemonsets', conf), secrets: new Kubectl('secrets', conf), endpoint: new Kubectl('endpoints', conf), ep: new Kubectl('endpoints', conf), ingress: new Kubectl('ingress', conf), ing: new Kubectl('ingress', conf), job: new Kubectl('job', conf), context: new Kubectl('context', conf), command: function (action, ...args) { args[0] = args[0].split(' ') return action.apply(this.pod, args) } } } declare var Buffer export class Request { private strictSSL private domain private auth constructor(conf: any) { if (conf.kubeconfig) { var kubeconfig = jsyaml.safeLoad(fs.readFileSync(conf.kubeconfig)) var context = conf.context || this.readContext(kubeconfig) var cluster = this.readCluster(kubeconfig, context) var user = this.readUser(kubeconfig, context) } this.auth = conf.auth || {} this.auth.caCert = this.auth.caCert || this.readCaCert(cluster) this.auth.clientKey = this.auth.clientKey || this.readClientKey(user) this.auth.clientCert = this.auth.clientCert || this.readClientCert(user) this.auth.token = this.auth.token || this.readUserToken(user) this.auth.username = this.auth.username || this.readUsername(user) this.auth.password = this.auth.password || this.readPassword(user) // only set to false if explictly false in the config this.strictSSL = conf.strictSSL !== false var endpoint = conf.endpoint || this.readEndpoint(cluster) this.domain = `${endpoint}${conf.version}/` } // Returns Context JSON from kubeconfig private readContext(kubeconfig) { if (!kubeconfig) return return kubeconfig.contexts.find((x) => x.name === kubeconfig['current-context']) } // Returns Cluster JSON from context at kubeconfig private readCluster(kubeconfig, context) { if (!kubeconfig || !context) return return kubeconfig.clusters.find((x) => x.name === context.context.cluster) } // Returns Cluster JSON from context at kubeconfig private readUser(kubeconfig, context) { if (!kubeconfig) return return kubeconfig.users.find((x) => x.name === context.context.user) } // Returns CaCert from kubeconfig private readCaCert(cluster) { if (!cluster) return var certificate_authority = cluster.cluster['certificate-authority'] if (certificate_authority) { return fs.readFileSync(certificate_authority).toString() } var certificate_authority_data = cluster.cluster['certificate-authority-data'] if (certificate_authority_data) { return Buffer.from(certificate_authority_data, 'base64').toString('ascii') } } // Returns CaCert from kubeconfig private readClientKey(user) { if (!user) return var client_key = user.user['client-key'] if (client_key) { return fs.readFileSync(client_key).toString() } var client_key_data = user.user['client-key-data'] if (client_key_data) { return Buffer.from(client_key_data, 'base64').toString('ascii') } } // Returns CaCert from kubeconfig private readClientCert(user) { if (!user) return var client_certificate = user.user['client-certificate'] if (client_certificate) { return fs.readFileSync(client_certificate).toString() } var client_certificate_data = user.user['client-certificate-data'] if (client_certificate_data) { return Buffer.from(client_certificate_data, 'base64').toString('ascii') } } // Returns User token from kubeconfig private readUserToken(user) { if (!user) return return user.user['token'] } // Returns User token from kubeconfig private readUsername(user) { if (!user) return return user.user['username'] } private readPassword(user) { if (!user) return return user.user['password'] } private readEndpoint(cluster) { if (!cluster) return return cluster.cluster['server'] } private callbackFunction(primise, callback) { if (_.isFunction(callback)) { primise .then((data) => { callback(null, data) }) .catch((err) => { callback(err) }) } } private getRequestOptions(path: string, opts?: any) { const options = opts || {} options.url = this.domain + path options.headers = { 'Content-Type': 'application/json' } options.strictSSL = this.strictSSL if (this.auth) { if (this.auth.caCert) { options.ca = this.auth.caCert } if (this.auth.username && this.auth.password) { const authstr = new Buffer(this.auth.username + ':' + this.auth.password).toString('base64') options.headers.Authorization = `Basic ${authstr}` } else if (this.auth.token) { options.headers.Authorization = `Bearer ${this.auth.token}` } else if (this.auth.clientCert && this.auth.clientKey) { options.cert = this.auth.clientCert options.key = this.auth.clientKey } } return options } public async get(url: string, done?): Promise<any> { const promise = new Promise((resolve, reject) => { request.get(this.getRequestOptions(url), (err, res, data) => { if (err || res.statusCode < 200 || res.statusCode >= 300) return reject(err || data) resolve(JSON.parse(data)) }) }) this.callbackFunction(promise, done) return promise } public async log(url: string, done?): Promise<any> { const promise = new Promise((resolve, reject) => { request.get(this.getRequestOptions(url), (err, res, data) => { if (err || res.statusCode < 200 || res.statusCode >= 300) return reject(err || data) resolve(data) }) }) this.callbackFunction(promise, done) return promise } public post(url, body, done?): Promise<any> { const promise = new Promise((resolve, reject) => { request.post(this.getRequestOptions(url, { json: body }), (err, res, data) => { if (err || res.statusCode < 200 || res.statusCode >= 300) return reject(err || data) resolve(data) }) }) this.callbackFunction(promise, done) return promise } public put(url, body, done?): Promise<any> { const promise = new Promise((resolve, reject) => { request.put(this.getRequestOptions(url, { json: body }), (err, res, data) => { if (err || res.statusCode < 200 || res.statusCode >= 300) return reject(err || data) resolve(data) }) }) this.callbackFunction(promise, done) return promise } public patch(url, body, _options?, done?): Promise<any> { if (typeof _options === 'function') { done = _options _options = undefined } const promise = new Promise((resolve, reject) => { const options = this.getRequestOptions(url, { json: body }) options.headers['Content-Type'] = 'application/json-patch+json' if (_options && _options.headers) { for (const key in _options.headers) { options.headers[key] = _options.headers[key] } } request.patch(options, (err, res, data) => { if (err || res.statusCode < 200 || res.statusCode >= 300) return reject(err || data) resolve(data) }) }) this.callbackFunction(promise, done) return promise } public delete(url, json?, done?): Promise<any> { if (_.isFunction(json)) { done = json json = undefined } const promise = new Promise((resolve, reject) => { request.del(this.getRequestOptions(url, json), (err, res, data) => { if (err || res.statusCode < 200 || res.statusCode >= 300) return reject(err || data) resolve(data) }) }) this.callbackFunction(promise, done) return promise } public watch(url, message?, exit?, timeout?) { if (_.isNumber(message)) { timeout = message message = undefined } var res const source = Rx.Observable.create((observer) => { var jsonStr = '' res = request .get(this.getRequestOptions(url, { timeout: timeout }), (e) => {}) .on('data', (data) => { if (res.response.headers['content-type'] === 'text/plain') { observer.onNext(data.toString()) } else { jsonStr += data.toString() if (!/\n$/.test(jsonStr)) return jsonStr = jsonStr.replace('\n$', '') try { jsonStr.split('\n').forEach((jsonStr) => { if (!jsonStr) return const json = JSON.parse(jsonStr) observer.onNext(json) }) jsonStr = '' } catch (err) { observer.onError(err) } } }) .on('error', (err) => { observer.onError(err) }) .on('close', () => { observer.onError() }) }) if (_.isFunction(message)) { source.subscribe( (data) => { message(data) }, (err) => { if (_.isFunction(exit)) exit(err) } ) return res } return source } } export type K8sRequest = Request export const api = (conf) => { return new Request(conf) }
the_stack
import { EventEmitter } from 'events' import { StringDecoder } from 'string_decoder' import assert from 'assert' import { Readable } from 'stream' // eslint-disable-next-line @typescript-eslint/no-var-requires const pkg = require('../package.json') import { NodeLibcurlNativeBinding, EasyNativeBinding, FileInfo, HttpPostField, } from './types' import { Easy } from './Easy' import { Multi } from './Multi' import { Share } from './Share' import { mergeChunks } from './mergeChunks' import { parseHeaders, HeaderInfo } from './parseHeaders' import { DataCallbackOptions, ProgressCallbackOptions, StringListOptions, BlobOptions, CurlOptionName, SpecificOptions, CurlOptionValueType, } from './generated/CurlOption' import { CurlInfoName } from './generated/CurlInfo' import { CurlChunk } from './enum/CurlChunk' import { CurlCode } from './enum/CurlCode' import { CurlFeature } from './enum/CurlFeature' import { CurlFnMatchFunc } from './enum/CurlFnMatchFunc' import { CurlFtpMethod } from './enum/CurlFtpMethod' import { CurlFtpSsl } from './enum/CurlFtpSsl' import { CurlGlobalInit } from './enum/CurlGlobalInit' import { CurlGssApi } from './enum/CurlGssApi' import { CurlHeader } from './enum/CurlHeader' import { CurlHttpVersion } from './enum/CurlHttpVersion' import { CurlInfoDebug } from './enum/CurlInfoDebug' import { CurlIpResolve } from './enum/CurlIpResolve' import { CurlNetrc } from './enum/CurlNetrc' import { CurlPause } from './enum/CurlPause' import { CurlProgressFunc } from './enum/CurlProgressFunc' import { CurlProtocol } from './enum/CurlProtocol' import { CurlProxy } from './enum/CurlProxy' import { CurlRtspRequest } from './enum/CurlRtspRequest' import { CurlSshAuth } from './enum/CurlSshAuth' import { CurlSslOpt } from './enum/CurlSslOpt' import { CurlSslVersion } from './enum/CurlSslVersion' import { CurlTimeCond } from './enum/CurlTimeCond' import { CurlUseSsl } from './enum/CurlUseSsl' import { CurlWriteFunc } from './enum/CurlWriteFunc' import { CurlReadFunc } from './enum/CurlReadFunc' import { CurlInfoNameSpecific, GetInfoReturn } from './types/EasyNativeBinding' // eslint-disable-next-line @typescript-eslint/no-var-requires const bindings: NodeLibcurlNativeBinding = require('../lib/binding/node_libcurl.node') const { Curl: _Curl, CurlVersionInfo } = bindings if ( !process.env.NODE_LIBCURL_DISABLE_GLOBAL_INIT_CALL || process.env.NODE_LIBCURL_DISABLE_GLOBAL_INIT_CALL !== 'true' ) { // We could just pass nothing here, CurlGlobalInitEnum.All is the default anyway. const globalInitResult = _Curl.globalInit(CurlGlobalInit.All) assert(globalInitResult === 0 || 'Libcurl global init failed.') } const decoder = new StringDecoder('utf8') // Handle used by curl instances created by the Curl wrapper. const multiHandle = new Multi() const curlInstanceMap = new WeakMap<EasyNativeBinding, Curl>() multiHandle.onMessage((error, handle, errorCode) => { multiHandle.removeHandle(handle) const curlInstance = curlInstanceMap.get(handle) assert( curlInstance, 'Could not retrieve curl instance from easy handle on onMessage callback', ) if (error) { curlInstance!.onError(error, errorCode) } else { curlInstance!.onEnd() } }) /** * Wrapper around {@link "Easy".Easy | `Easy`} class with a more *nodejs-friendly* interface. * * This uses an internal {@link "Multi".Multi | `Multi`} instance allowing for asynchronous * requests. * * @public */ class Curl extends EventEmitter { /** * Calls [`curl_global_init()`](http://curl.haxx.se/libcurl/c/curl_global_init.html). * * For **flags** see the the enum {@link CurlGlobalInit | `CurlGlobalInit`}. * * This is automatically called when the addon is loaded, to disable this, set the environment variable * `NODE_LIBCURL_DISABLE_GLOBAL_INIT_CALL=false` */ static globalInit = _Curl.globalInit /** * Calls [`curl_global_cleanup()`](http://curl.haxx.se/libcurl/c/curl_global_cleanup.html) * * This is automatically called when the process is exiting. */ static globalCleanup = _Curl.globalCleanup /** * Returns libcurl version string. * * The string shows which libraries libcurl was built with and their versions, example: * ``` * libcurl/7.69.1-DEV OpenSSL/1.1.1d zlib/1.2.11 WinIDN libssh2/1.9.0_DEV nghttp2/1.40.0 * ``` */ static getVersion = _Curl.getVersion /** * This is the default user agent that is going to be used on all `Curl` instances. * * You can overwrite this in a per instance basis, calling `curlHandle.setOpt('USERAGENT', 'my-user-agent/1.0')`, or * by directly changing this property so it affects all newly created `Curl` instances. * * To disable this behavior set this property to `null`. */ static defaultUserAgent = `node-libcurl/${pkg.version}` /** * Integer representing the current libcurl version. * * It was built the following way: * ``` * <8 bits major number> | <8 bits minor number> | <8 bits patch number>. * ``` * Version `7.69.1` is therefore returned as `0x074501` / `476417` */ static VERSION_NUM = _Curl.VERSION_NUM /** * This is a object with members resembling the `CURLINFO_*` libcurl constants. * * It can be used with {@link "Easy".Easy.getInfo | `Easy#getInfo`} or {@link getInfo | `Curl#getInfo`}. * * See the official documentation of [`curl_easy_getinfo()`](http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html) * for reference. * * `CURLINFO_EFFECTIVE_URL` becomes `Curl.info.EFFECTIVE_URL` */ static info = _Curl.info /** * This is a object with members resembling the `CURLOPT_*` libcurl constants. * * It can be used with {@link "Easy".Easy.setOpt | `Easy#setOpt`} or {@link setOpt | `Curl#setOpt`}. * * See the official documentation of [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) * for reference. * * `CURLOPT_URL` becomes `Curl.option.URL` */ static option = _Curl.option /** * Returns the number of handles currently open in the internal {@link "Multi".Multi | `Multi`} handle being used. */ static getCount = multiHandle.getCount /** * Whether this instance is running or not ({@link perform | `perform()`} was called). * * Make sure to not change their value, otherwise unexpected behavior would happen. * * This is marked as protected only with the TSDoc to not cause a breaking change. * * @protected */ isRunning = false /** * Internal Easy handle being used */ protected handle: EasyNativeBinding /** * Stores current response payload. * * This will not store anything in case {@link CurlFeature.NoDataStorage | `NoDataStorage`} flag is enabled */ protected chunks: Buffer[] = [] /** * Current response length. * * Will always be zero in case {@link CurlFeature.NoDataStorage | `NoDataStorage`} flag is enabled */ protected chunksLength = 0 /** * Stores current headers payload. * * This will not store anything in case {@link CurlFeature.NoDataStorage | `NoDataStorage`} flag is enabled */ protected headerChunks: Buffer[] = [] /** * Current headers length. * * Will always be zero in case {@link CurlFeature.NoDataStorage | `NoDataStorage`} flag is enabled */ protected headerChunksLength = 0 /** * Currently enabled features. * * See {@link enable | `enable`} and {@link disable | `disable`} */ protected features: CurlFeature = 0 // these are for stream handling // the streams themselves protected writeFunctionStream: Readable | null = null protected readFunctionStream: Readable | null = null // READFUNCTION / upload related protected streamReadFunctionCallbacksToClean: Array< [Readable, string, (...args: any[]) => void] > = [] // a state machine would be better here than all these flags 🤣 protected streamReadFunctionShouldEnd = false protected streamReadFunctionShouldPause = false protected streamReadFunctionPaused = false // WRITEFUNCTION / download related protected streamWriteFunctionHighWaterMark: number | undefined protected streamWriteFunctionShouldPause = false protected streamWriteFunctionPaused = false protected streamWriteFunctionFirstRun = true // common protected streamPauseNext = false protected streamContinueNext = false protected streamError: false | Error = false protected streamUserSuppliedProgressFunction: CurlOptionValueType['xferInfoFunction'] = null /** * @param cloneHandle {@link "Easy".Easy | `Easy`} handle that should be used instead of creating a new one. */ constructor(cloneHandle?: EasyNativeBinding) { super() const handle = cloneHandle || new Easy() this.handle = handle // callbacks called by libcurl handle.setOpt( Curl.option.WRITEFUNCTION, this.defaultWriteFunction.bind(this), ) handle.setOpt( Curl.option.HEADERFUNCTION, this.defaultHeaderFunction.bind(this), ) handle.setOpt(Curl.option.USERAGENT, Curl.defaultUserAgent) curlInstanceMap.set(handle, this) } /** * Callback called when an error is thrown on this handle. * * This is called from the internal callback we use with the {@link "Multi".Multi.onMessage | `onMessage`} * method of the global {@link "Multi".Multi | `Multi`} handle used by all `Curl` instances. * * @protected */ onError(error: Error, errorCode: CurlCode) { this.resetInternalState() this.emit('error', error, errorCode, this) } /** * Callback called when this handle has finished the request. * * This is called from the internal callback we use with the {@link "Multi".Multi.onMessage | `onMessage`} * method of the global {@link "Multi".Multi | `Multi`} handle used by all `Curl` instances. * * This should not be called in any other way. * * @protected */ onEnd() { const isStreamResponse = !!(this.features & CurlFeature.StreamResponse) const isDataStorageEnabled = !isStreamResponse && !(this.features & CurlFeature.NoDataStorage) const isDataParsingEnabled = !isStreamResponse && !(this.features & CurlFeature.NoDataParsing) && isDataStorageEnabled const dataRaw = isDataStorageEnabled ? mergeChunks(this.chunks, this.chunksLength) : Buffer.alloc(0) const data = isDataParsingEnabled ? decoder.write(dataRaw) : dataRaw const headers = this.getHeaders() const { code, data: status } = this.handle.getInfo(Curl.info.RESPONSE_CODE) // if this had the stream response flag we need to signal the end of the stream by pushing null to it. if (isStreamResponse) { // if the writeFunctionStream is still null here, this means the response had no body // This may happen because the writeFunctionStream is created in the writeFunction callback, which is not called // for requests that do not have a body if (!this.writeFunctionStream) { // we such cases we must call the on Stream event and immediately signal the end of the stream. const noopStream = new Readable({ read() { setImmediate(() => { this.push(null) }) }, }) // we are calling this with nextTick because it must run before the next event loop iteration (notice that the cleanup is called with setImmediate below). // We are not just calling it directly to avoid errors in the on Stream callbacks causing this function to throw process.nextTick(() => this.emit('stream', noopStream, status, headers, this), ) } else { this.writeFunctionStream.push(null) } } const wrapper = isStreamResponse ? setImmediate : (fn: (...args: any[]) => void) => fn() wrapper(() => { this.resetInternalState() // if is ignored because this should never happen under normal circumstances. /* istanbul ignore if */ if (code !== CurlCode.CURLE_OK) { const error = new Error('Could not get status code of request') this.emit('error', error, code, this) } else { this.emit('end', status, data, headers, this) } }) } /** * Enables a feature, must not be used while a request is running. * * Use {@link CurlFeature | `CurlFeature`} for predefined constants. */ enable(bitmask: CurlFeature) { if (this.isRunning) { throw new Error( 'You should not change the features while a request is running.', ) } this.features |= bitmask return this } /** * Disables a feature, must not be used while a request is running. * * Use {@link CurlFeature | `CurlFeature`} for predefined constants. */ disable(bitmask: CurlFeature) { if (this.isRunning) { throw new Error( 'You should not change the features while a request is running.', ) } this.features &= ~bitmask return this } /** * Sets an option the handle. * * This overloaded method has `never` as type for the arguments * because one of the other overloaded signatures must be used. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) * * @param optionIdOrName Option name or integer value. Use {@link Curl.option | `Curl.option`} for predefined constants. * @param optionValue The value of the option, value type depends on the option being set. */ setOpt(optionIdOrName: never, optionValue: never): this { // special case for WRITEFUNCTION and HEADERFUNCTION callbacks // since if they are set back to null, we must restore the default callback. let value = optionValue if ( (optionIdOrName === Curl.option.WRITEFUNCTION || optionIdOrName === 'WRITEFUNCTION') && !optionValue ) { value = this.defaultWriteFunction.bind(this) as never } else if ( (optionIdOrName === Curl.option.HEADERFUNCTION || optionIdOrName === 'HEADERFUNCTION') && !optionValue ) { value = this.defaultHeaderFunction.bind(this) as never } const code = this.handle.setOpt(optionIdOrName, value) if (code !== CurlCode.CURLE_OK) { throw new Error( code === CurlCode.CURLE_UNKNOWN_OPTION ? 'Unknown option given. First argument must be the option internal id or the option name. You can use the Curl.option constants.' : Easy.strError(code), ) } return this } /** * Retrieves some information about the last request made by a handle. * * This overloaded method has `never` as type for the argument * because one of the other overloaded signatures must be used. * * Official libcurl documentation: [`curl_easy_getinfo()`](http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html) * * @param infoNameOrId Info name or integer value. Use {@link Curl.info | `Curl.info`} for predefined constants. */ getInfo(infoNameOrId: never): any { const { code, data } = this.handle.getInfo(infoNameOrId) if (code !== CurlCode.CURLE_OK) { throw new Error(`getInfo failed. Error: ${Easy.strError(code)}`) } return data } /** * This will set an internal `READFUNCTION` callback that will read all the data from this stream. * * One usage for that is to upload data directly from streams. Example: * * ```typescript * const curl = new Curl() * curl.setOpt('URL', 'https://some-domain/upload') * curl.setOpt('UPLOAD', true) * // so we do not need to set the content length * curl.setOpt('HTTPHEADER', ['Transfer-Encoding: chunked']) * * const filePath = './test.zip' * const stream = fs.createReadStream(filePath) * curl.setUploadStream(stream) * * curl.setStreamProgressCallback(() => { * // this will use the default progress callback from libcurl * return CurlProgressFunc.Continue * }) * * curl.on('end', (statusCode, data) => { * console.log('\n'.repeat(5)) * // data length should be 0, as it was sent using the response stream * console.log( * `curl - end - status: ${statusCode} - data length: ${data.length}`, * ) * curl.close() * }) * curl.on('error', (error, errorCode) => { * console.log('\n'.repeat(5)) * console.error('curl - error: ', error, errorCode) * curl.close() * }) * curl.perform() * ``` * * Multiple calls with the same stream that was previously set has no effect. * * Setting this to `null` will remove the `READFUNCTION` callback and disable this behavior. * * @remarks * * This option is reset after each request, so if you want to upload the same data again using the same * `Curl` instance, you will need to provide a new stream. * * Make sure your libcurl version is greater than or equal 7.69.1. * Versions older than that one are not reliable for streams usage. */ setUploadStream(stream: Readable | null) { if (!stream) { if (this.readFunctionStream) { this.cleanupReadFunctionStreamEvents() this.readFunctionStream = null this.setOpt('READFUNCTION', null) } return this } if (this.readFunctionStream === stream) return this if ( typeof stream?.on !== 'function' || typeof stream?.read !== 'function' ) { throw new Error( 'The passed value to setUploadStream does not looks like a stream object', ) } this.readFunctionStream = stream const resumeIfPaused = () => { if (this.streamReadFunctionPaused) { this.streamReadFunctionPaused = false // let's unpause only on the next event loop iteration // this will avoid scenarios where the readable event was emitted // between libcurl pausing the transfer from the READFUNCTION // and the next real iteration. setImmediate(() => { // just to make sure we do not try to unpause // a connection that has already finished // this can happen if some error has been throw // in the meantime if (this.isRunning) { this.pause(CurlPause.Cont) } }) } } const attachEventListenerToStream = ( event: string, cb: (...args: any[]) => void, ) => { this.readFunctionStream!.on(event, cb) this.streamReadFunctionCallbacksToClean.push([ this.readFunctionStream!, event, cb, ]) } // TODO: Handle adding the event multiple times? // can only happen if the user calls the method with the same stream more than one time // and due to the if at the top, this is only possible if they use another stream in-between. attachEventListenerToStream('readable', () => { resumeIfPaused() }) // This needs the same logic than the destroy callback for the response stream // inside the default WRITEFUNCTION. // Which basically means we cannot throw an error inside the READFUNCTION itself // as this would cause the pause itself to throw an error // (pause calls the READFUNCTION before returning) // So we must create a fake "pause" just to trigger the progress function, and // then the error will be thrown. // This is why the following two callbacks are setting // this.streamReadFunctionShouldPause = true attachEventListenerToStream('close', () => { // If the stream was closed, but end was not called // it means the stream was forcefully destroyed, so // we must let libcurl fail! // streamError could already be set if destroy was called with an error // as it would call the error callback below, so we don't need to do anything. if (!this.streamReadFunctionShouldEnd && !this.streamError) { this.streamError = new Error( 'Curl upload stream was unexpectedly destroyed', ) this.streamReadFunctionShouldPause = true resumeIfPaused() } }) attachEventListenerToStream('error', (error: Error) => { this.streamError = error this.streamReadFunctionShouldPause = true resumeIfPaused() }) attachEventListenerToStream('end', () => { this.streamReadFunctionShouldEnd = true resumeIfPaused() }) this.setOpt('READFUNCTION', (buffer, size, nmemb) => { // Remember, we cannot throw this.streamError here. if (this.streamReadFunctionShouldPause) { this.streamReadFunctionShouldPause = false this.streamReadFunctionPaused = true return CurlReadFunc.Pause } const amountToRead = size * nmemb const data = stream.read(amountToRead) if (!data) { if (this.streamReadFunctionShouldEnd) { return 0 } else { this.streamReadFunctionPaused = true return CurlReadFunc.Pause } } const totalWritten = data.copy(buffer) // we could also return CurlReadFunc.Abort or CurlReadFunc.Pause here. return totalWritten }) return this } /** * Set the param to `null` to use the Node.js default value. * * @param highWaterMark This will passed directly to the `Readable` stream created to be returned as the response' * * @remarks * Only useful when the {@link CurlFeature.StreamResponse | `StreamResponse`} feature flag is enabled. */ setStreamResponseHighWaterMark(highWaterMark: number | null) { this.streamWriteFunctionHighWaterMark = highWaterMark || undefined return this } /** * This sets the callback to be used as the progress function when using any of the stream features. * * This is needed because when this `Curl` instance is enabled to use streams for upload/download, it needs * to set the libcurl progress function option to an internal function. * * If you are using any of the streams features, do not overwrite the progress callback to something else, * be it using {@link setOpt | `setOpt`} or {@link setProgressCallback | `setProgressCallback`}, as this would * cause undefined behavior. * * If are using this callback, there is no need to set the `NOPROGRESS` option to false (as you normally would). */ setStreamProgressCallback(cb: CurlOptionValueType['xferInfoFunction']) { this.streamUserSuppliedProgressFunction = cb return this } /** * The option `XFERINFOFUNCTION` was introduced in curl version `7.32.0`, * versions older than that should use `PROGRESSFUNCTION`. * If you don't want to mess with version numbers you can use this method, * instead of directly calling {@link Curl.setOpt | `Curl#setOpt`}. * * `NOPROGRESS` should be set to false to make this function actually get called. */ setProgressCallback( cb: | (( dltotal: number, dlnow: number, ultotal: number, ulnow: number, ) => number) | null, ) { if (Curl.VERSION_NUM >= 0x072000) { this.handle.setOpt(Curl.option.XFERINFOFUNCTION, cb) } else { this.handle.setOpt(Curl.option.PROGRESSFUNCTION, cb) } return this } /** * Add this instance to the processing queue. * This method should be called only one time per request, * otherwise it will throw an error. * * @remarks * * This basically calls the {@link "Multi".Multi.addHandle | `Multi#addHandle`} method. */ perform() { if (this.isRunning) { throw new Error('Handle already running!') } this.isRunning = true // set progress function to our internal one if using stream upload/download const isStreamEnabled = this.features & CurlFeature.StreamResponse || this.readFunctionStream if (isStreamEnabled) { this.setProgressCallback(this.streamModeProgressFunction.bind(this)) this.setOpt('NOPROGRESS', false) } multiHandle.addHandle(this.handle) return this } /** * Perform any connection upkeep checks. * * * Official libcurl documentation: [`curl_easy_upkeep()`](http://curl.haxx.se/libcurl/c/curl_easy_upkeep.html) */ upkeep() { const code = this.handle.upkeep() if (code !== CurlCode.CURLE_OK) { throw new Error(Easy.strError(code)) } return this } /** * Use this function to pause / unpause a connection. * * The bitmask argument is a set of bits that sets the new state of the connection. * * Use {@link CurlPause | `CurlPause`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_pause()`](http://curl.haxx.se/libcurl/c/curl_easy_pause.html) */ pause(bitmask: CurlPause) { const code = this.handle.pause(bitmask) if (code !== CurlCode.CURLE_OK) { throw new Error(Easy.strError(code)) } return this } /** * Reset this handle options to their defaults. * * This will put the handle in a clean state, as if it was just created. * * * Official libcurl documentation: [`curl_easy_reset()`](http://curl.haxx.se/libcurl/c/curl_easy_reset.html) */ reset() { this.removeAllListeners() this.handle.reset() // add callbacks back as reset will remove them this.handle.setOpt( Curl.option.WRITEFUNCTION, this.defaultWriteFunction.bind(this), ) this.handle.setOpt( Curl.option.HEADERFUNCTION, this.defaultHeaderFunction.bind(this), ) return this } /** * Duplicate this handle with all their options. * Keep in mind that, by default, this also means all event listeners. * * * Official libcurl documentation: [`curl_easy_duphandle()`](http://curl.haxx.se/libcurl/c/curl_easy_duphandle.html) * * @param shouldCopyEventListeners If you don't want to copy the event listeners, set this to `false`. */ dupHandle(shouldCopyEventListeners = true) { const duplicatedHandle = new Curl(this.handle.dupHandle()) const eventsToCopy = ['end', 'error', 'data', 'header'] duplicatedHandle.features = this.features if (shouldCopyEventListeners) { for (let i = 0; i < eventsToCopy.length; i += 1) { const listeners = this.listeners(eventsToCopy[i]) for (let j = 0; j < listeners.length; j += 1) { duplicatedHandle.on(eventsToCopy[i], listeners[j]) } } } return duplicatedHandle } /** * Close this handle. * * **NOTE:** After closing the handle, it must not be used anymore. Doing so will throw an error. * * * Official libcurl documentation: [`curl_easy_cleanup()`](http://curl.haxx.se/libcurl/c/curl_easy_cleanup.html) */ close() { curlInstanceMap.delete(this.handle) this.removeAllListeners() if (this.handle.isInsideMultiHandle) { multiHandle.removeHandle(this.handle) } this.handle.setOpt(Curl.option.WRITEFUNCTION, null) this.handle.setOpt(Curl.option.HEADERFUNCTION, null) this.handle.close() } /** * This is used to reset a few properties to their pre-request state. */ protected resetInternalState() { this.isRunning = false this.chunks = [] this.chunksLength = 0 this.headerChunks = [] this.headerChunksLength = 0 const wasStreamEnabled = this.writeFunctionStream || this.readFunctionStream if (wasStreamEnabled) { this.setProgressCallback(null) } // reset back the READFUNCTION if there was a stream we were reading from if (this.readFunctionStream) { this.setOpt('READFUNCTION', null) } // these are mostly streams related, as these options are not persisted between requests // the streams themselves this.writeFunctionStream = null this.readFunctionStream = null // READFUNCTION / upload related this.streamReadFunctionShouldEnd = false this.streamReadFunctionShouldPause = false this.streamReadFunctionPaused = false // WRITEFUNCTION / download related this.streamWriteFunctionShouldPause = false this.streamWriteFunctionPaused = false this.streamWriteFunctionFirstRun = true // common this.streamPauseNext = false this.streamContinueNext = false this.streamError = false this.streamUserSuppliedProgressFunction = null this.cleanupReadFunctionStreamEvents() } /** * When uploading a stream (by calling {@link setUploadStream | `setUploadStream`}) * some event listeners are attached to the stream instance. * This will remove them so our callbacks are not called anymore. */ protected cleanupReadFunctionStreamEvents() { this.streamReadFunctionCallbacksToClean.forEach(([stream, event, cb]) => { stream.off(event, cb) }) this.streamReadFunctionCallbacksToClean = [] } /** * Returns headers from the current stored chunks - if any */ protected getHeaders() { const isHeaderStorageEnabled = !( this.features & CurlFeature.NoHeaderStorage ) const isHeaderParsingEnabled = !(this.features & CurlFeature.NoHeaderParsing) && isHeaderStorageEnabled const headersRaw = isHeaderStorageEnabled ? mergeChunks(this.headerChunks, this.headerChunksLength) : Buffer.alloc(0) return isHeaderParsingEnabled ? parseHeaders(decoder.write(headersRaw)) : headersRaw } /** * The internal function passed to `PROGRESSFUNCTION` (`XFERINFOFUNCTION` on most recent libcurl versions) * when using any of the stream features. */ protected streamModeProgressFunction( dltotal: number, dlnow: number, ultotal: number, ulnow: number, ) { if (this.streamError) throw this.streamError const ret = this.streamUserSuppliedProgressFunction ? this.streamUserSuppliedProgressFunction.call( this.handle, dltotal, dlnow, ultotal, ulnow, ) : 0 return ret } /** * This is the default callback passed to {@link setOpt | `setOpt('WRITEFUNCTION', cb)`}. */ protected defaultWriteFunction(chunk: Buffer, size: number, nmemb: number) { // this is a stream based request, so we need a totally different handling if (this.features & CurlFeature.StreamResponse) { return this.defaultWriteFunctionStreamBased(chunk, size, nmemb) } if (!(this.features & CurlFeature.NoDataStorage)) { this.chunks.push(chunk) this.chunksLength += chunk.length } this.emit('data', chunk, this) return size * nmemb } /** * This is used by the default callback passed to {@link setOpt | `setOpt('WRITEFUNCTION', cb)`} * when the feature to stream response is enabled. */ protected defaultWriteFunctionStreamBased( chunk: Buffer, size: number, nmemb: number, ) { if (!this.writeFunctionStream) { // eslint-disable-next-line @typescript-eslint/no-this-alias const handle = this // create the response stream we are going to use this.writeFunctionStream = new Readable({ highWaterMark: this.streamWriteFunctionHighWaterMark, destroy(error, cb) { handle.streamError = error || new Error('Curl response stream was unexpectedly destroyed') // let the event loop run one more time before we do anything // if the handle is not running anymore it means that the // error we set above was caught, if it is still running, then it means that: // - the handle is paused // - the progress function was not called yet // If this is the case, then we just unpause the handle. This will cause the following: // - the WRITEFUNCTION callback will be called // - this will pause the handle again (because we cannot throw the error in here) // - the PROGRESSFUNCTION callback will be called, and then the error will be thrown. setImmediate(() => { if (handle.isRunning && handle.streamWriteFunctionPaused) { handle.streamWriteFunctionPaused = false handle.streamWriteFunctionShouldPause = true try { handle.pause(CurlPause.RecvCont) } catch (error) { cb(error) return } } cb(null) }) }, read(_size) { if ( handle.streamWriteFunctionFirstRun || handle.streamWriteFunctionPaused ) { if (handle.streamWriteFunctionFirstRun) { handle.streamWriteFunctionFirstRun = false } // we must allow Node.js to process the whole event queue // before we unpause setImmediate(() => { if (handle.isRunning) { handle.streamWriteFunctionPaused = false handle.pause(CurlPause.RecvCont) } }) } }, }) // as soon as we have the stream, we need to emit the "stream" event // but the "stream" event needs the statusCode and the headers, so this // is what we are retrieving here. const headers = this.getHeaders() const { code, data: status } = this.handle.getInfo( Curl.info.RESPONSE_CODE, ) if (code !== CurlCode.CURLE_OK) { const error = new Error('Could not get status code of request') this.emit('error', error, code, this) return 0 } // let's emit the event only in the next iteration of the event loop // We need to do this otherwise the event listener callbacks would run // before the pause below, and this is probably not what we want. setImmediate(() => this.emit('stream', this.writeFunctionStream, status, headers, this), ) this.streamWriteFunctionPaused = true return CurlWriteFunc.Pause } // pause this req if (this.streamWriteFunctionShouldPause) { this.streamWriteFunctionShouldPause = false this.streamWriteFunctionPaused = true return CurlWriteFunc.Pause } // write to the stream const ok = this.writeFunctionStream.push(chunk) // pause connection until there is more data if (!ok) { this.streamWriteFunctionPaused = true this.pause(CurlPause.Recv) } return size * nmemb } /** * This is the default callback passed to {@link setOpt | `setOpt('HEADERFUNCTION', cb)`}. */ protected defaultHeaderFunction(chunk: Buffer, size: number, nmemb: number) { if (!(this.features & CurlFeature.NoHeaderStorage)) { this.headerChunks.push(chunk) this.headerChunksLength += chunk.length } this.emit('header', chunk, this) return size * nmemb } /** * Returns an object with a representation of the current libcurl version and their features/protocols. * * This is basically [`curl_version_info()`](https://curl.haxx.se/libcurl/c/curl_version_info.html) */ static getVersionInfo = () => CurlVersionInfo /** * Returns a string that looks like the one returned by * ```bash * curl -V * ``` * Example: * ``` * Version: libcurl/7.69.1-DEV OpenSSL/1.1.1d zlib/1.2.11 WinIDN libssh2/1.9.0_DEV nghttp2/1.40.0 * Protocols: dict, file, ftp, ftps, gopher, http, https, imap, imaps, ldap, ldaps, pop3, pop3s, rtsp, scp, sftp, smb, smbs, smtp, smtps, telnet, tftp * Features: AsynchDNS, IDN, IPv6, Largefile, SSPI, Kerberos, SPNEGO, NTLM, SSL, libz, HTTP2, HTTPS-proxy * ``` */ static getVersionInfoString = () => { const version = Curl.getVersion() const protocols = CurlVersionInfo.protocols.join(', ') const features = CurlVersionInfo.features.join(', ') return [ `Version: ${version}`, `Protocols: ${protocols}`, `Features: ${features}`, ].join('\n') } /** * Useful if you want to check if the current libcurl version is greater or equal than another one. * @param x major * @param y minor * @param z patch */ static isVersionGreaterOrEqualThan = (x: number, y: number, z = 0) => { return _Curl.VERSION_NUM >= (x << 16) + (y << 8) + z } } interface Curl { on( event: 'data', listener: (this: Curl, chunk: Buffer, curlInstance: Curl) => void, ): this on( event: 'header', listener: (this: Curl, chunk: Buffer, curlInstance: Curl) => void, ): this on( event: 'error', listener: ( this: Curl, error: Error, errorCode: CurlCode, curlInstance: Curl, ) => void, ): this /** * This is emitted if the StreamResponse feature was enabled. */ on( event: 'stream', listener: ( this: Curl, stream: Readable, status: number, headers: Buffer | HeaderInfo[], curlInstance: Curl, ) => void, ): this /** * The `data` paramater passed to the listener callback will be one of the following: * - Empty `Buffer` if the feature {@link CurlFeature.NoDataStorage | `NoDataStorage`} flag was enabled * - Non-Empty `Buffer` if the feature {@link CurlFeature.NoDataParsing | `NoDataParsing`} flag was enabled * - Otherwise, it will be a string, with the result of decoding the received data as a UTF8 string. * If it's a JSON string for example, you still need to call JSON.parse on it. This library does no extra parsing * whatsoever. * * The `headers` parameter passed to the listener callback will be one of the following: * - Empty `Buffer` if the feature {@link CurlFeature.NoHeaderParsing | `NoHeaderStorage`} flag was enabled * - Non-Empty `Buffer` if the feature {@link CurlFeature.NoHeaderParsing | `NoHeaderParsing`} flag was enabled * - Otherwise, an array of parsed headers for each request * libcurl made (if there were 2 redirects before the last request, the array will have 3 elements, one for each request) */ on( event: 'end', listener: ( this: Curl, status: number, data: string | Buffer, headers: Buffer | HeaderInfo[], curlInstance: Curl, ) => void, ): this // eslint-disable-next-line @typescript-eslint/ban-types on(event: string, listener: Function): this // START AUTOMATICALLY GENERATED CODE - DO NOT EDIT /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt( option: DataCallbackOptions, value: | (( this: EasyNativeBinding, data: Buffer, size: number, nmemb: number, ) => number) | null, ): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt( option: ProgressCallbackOptions, value: | (( this: EasyNativeBinding, dltotal: number, dlnow: number, ultotal: number, ulnow: number, ) => number | CurlProgressFunc) | null, ): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: StringListOptions, value: string[] | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: BlobOptions, value: ArrayBuffer | Buffer | string | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt( option: 'CHUNK_BGN_FUNCTION', value: | (( this: EasyNativeBinding, fileInfo: FileInfo, remains: number, ) => CurlChunk) | null, ): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt( option: 'CHUNK_END_FUNCTION', value: ((this: EasyNativeBinding) => CurlChunk) | null, ): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt( option: 'DEBUGFUNCTION', value: | ((this: EasyNativeBinding, type: CurlInfoDebug, data: Buffer) => 0) | null, ): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt( option: 'FNMATCH_FUNCTION', value: | (( this: EasyNativeBinding, pattern: string, value: string, ) => CurlFnMatchFunc) | null, ): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt( option: 'SEEKFUNCTION', value: | ((this: EasyNativeBinding, offset: number, origin: number) => number) | null, ): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt( option: 'TRAILERFUNCTION', value: ((this: EasyNativeBinding) => string[] | false) | null, ): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'SHARE', value: Share | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'HTTPPOST', value: HttpPostField[] | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'FTP_SSL_CCC', value: CurlFtpSsl | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'FTP_FILEMETHOD', value: CurlFtpMethod | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'GSSAPI_DELEGATION', value: CurlGssApi | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'HEADEROPT', value: CurlHeader | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'HTTP_VERSION', value: CurlHttpVersion | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'IPRESOLVE', value: CurlIpResolve | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'NETRC', value: CurlNetrc | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'PROTOCOLS', value: CurlProtocol | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'PROXY_SSL_OPTIONS', value: CurlSslOpt | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'PROXYTYPE', value: CurlProxy | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'REDIR_PROTOCOLS', value: CurlProtocol | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'RTSP_REQUEST', value: CurlRtspRequest | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'SSH_AUTH_TYPES', value: CurlSshAuth | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'SSL_OPTIONS', value: CurlSslOpt | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'SSLVERSION', value: CurlSslVersion | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'TIMECONDITION', value: CurlTimeCond | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt(option: 'USE_SSL', value: CurlUseSsl | null): this /** * Use {@link "Curl".Curl.option|`Curl.option`} for predefined constants. * * * Official libcurl documentation: [`curl_easy_setopt()`](http://curl.haxx.se/libcurl/c/curl_easy_setopt.html) */ setOpt( option: Exclude<CurlOptionName, SpecificOptions>, value: string | number | boolean | null, ): this // END AUTOMATICALLY GENERATED CODE - DO NOT EDIT // overloaded getInfo definitions - changes made here must also be made in EasyNativeBinding.ts // TODO: do this automatically, like above. /** * Returns information about the finished connection. * * Official libcurl documentation: [`curl_easy_getinfo()`](http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html) * * @param info Info to retrieve. Use {@link "Curl".Curl.info | `Curl.info`} for predefined constants. */ getInfo(info: 'CERTINFO'): GetInfoReturn<string[]>['data'] /** * Returns information about the finished connection. * * Official libcurl documentation: [`curl_easy_getinfo()`](http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html) * * @param info Info to retrieve. Use {@link "Curl".Curl.info | `Curl.info`} for predefined constants. */ getInfo( info: Exclude<CurlInfoName, CurlInfoNameSpecific>, ): GetInfoReturn['data'] } export { Curl }
the_stack
import { describe, it } from "mocha"; import sinon from "sinon"; import { assert } from "chai"; import { getOutputOpts, parseInputOption, packedLEConcat, jsSHABase } from "../../src/common"; import { FixedLengthOptionsEncodingType, FixedLengthOptionsNoEncodingType, FormatNoTextType, packedValue, } from "../../src/custom_types"; describe("Test packedLEConcat", () => { it("For 2 0-byte Values", () => { assert.deepEqual(packedLEConcat({ value: [], binLen: 0 }, { value: [], binLen: 0 }), { value: [], binLen: 0 }); }); it("For 2 3-byte Values", () => { assert.deepEqual(packedLEConcat({ value: [0x00112233], binLen: 24 }, { value: [0x00aabbcc], binLen: 24 }), { value: [0xcc112233 | 0, 0x0000aabb], binLen: 48, }); }); it("For 2 4-byte Values", () => { assert.deepEqual(packedLEConcat({ value: [0x11223344], binLen: 32 }, { value: [0xaabbccdd], binLen: 32 }), { value: [0x11223344, 0xaabbccdd], binLen: 64, }); }); it("For 1 1-byte and 1 3-byte Value", () => { assert.deepEqual(packedLEConcat({ value: [0x00000011], binLen: 8 }, { value: [0x00aabbcc], binLen: 24 }), { value: [0xaabbcc11 | 0], binLen: 32, }); }); }); describe("Test parseInputOption", () => { it("For Fully Specified Value", () => { assert.deepEqual(parseInputOption("kmacKey", { value: "00112233", format: "HEX" }, 1), { value: [0x33221100], binLen: 32, }); }); it("For Empty but Optional Value", () => { assert.deepEqual(parseInputOption("kmacKey", undefined, 1, { value: [], binLen: 0 }), { value: [], binLen: 0 }); }); it("For Empty but Required Value", () => { assert.throws(() => { parseInputOption("kmacKey", undefined, 1); }, "kmacKey must include a value and format"); }); it("For Value Missing value Key", () => { assert.throws(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore - Deliberately bad value for test parseInputOption("kmacKey", { format: "HEX" }, 1); }, "kmacKey must include a value and format"); }); it("For Value Missing binLen Key", () => { assert.throws(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore - Deliberately bad value for test parseInputOption("kmacKey", { value: "TEST" }, 1); }, "kmacKey must include a value and format"); }); }); describe("Test getOutputOpts", () => { it("Empty Input", () => { assert.deepEqual(getOutputOpts(), { outputUpper: false, b64Pad: "=", outputLen: -1 }); }); it("b64Pad Specified", () => { assert.deepEqual(getOutputOpts({ b64Pad: "#" }), { outputUpper: false, b64Pad: "#", outputLen: -1 }); }); it("outputLen Specified", () => { assert.deepEqual(getOutputOpts({ outputLen: 16, shakeLen: 8 }), { outputUpper: false, b64Pad: "=", outputLen: 16 }); }); it("shakeLen Specified", () => { assert.deepEqual(getOutputOpts({ shakeLen: 8 }), { outputUpper: false, b64Pad: "=", outputLen: 8 }); }); it("Invalid shakeLen", () => { assert.throws(() => { getOutputOpts({ shakeLen: 1 }); }, "Output length must be a multiple of 8"); }); it("Invalid outputLen", () => { assert.throws(() => { getOutputOpts({ outputLen: 1 }); }, "Output length must be a multiple of 8"); }); it("Invalid b64Pad", () => { assert.throws(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore - Deliberate bad b64Pad value to test exceptions getOutputOpts({ b64Pad: 1 }); }, "Invalid b64Pad formatting option"); }); it("Invalid outputUpper", () => { assert.throws(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore - Deliberate bad outputUpper value to test exceptions getOutputOpts({ outputUpper: 1 }); }, "Invalid outputUpper formatting option"); }); }); describe("Test jsSHABase", () => { const stubbedStrConverter = sinon.stub(), stubbedRound = sinon.stub(), stubbedNewState = sinon.stub(), stubbedFinalize = sinon.stub(), stubbedStateClone = sinon.stub(), dummyVals = [ 0x11223344, 0xaabbccdd, 0xdeadbeef, 0xfacefeed, 0xbaddcafe, 0xdeadcafe, 0xdead2bad, 0xdeaddead, 0xcafed00d, 0xdecafbad, 0xfee1dead, 0xdeadfa11, ]; class jsSHAATest extends jsSHABase<number[], "SHA-TEST"> { intermediateState: number[]; variantBlockSize: number; bigEndianMod: -1 | 1; outputBinLen: number; isVariableLen: boolean; HMACSupported: boolean; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue; roundFunc: (block: number[], H: number[]) => number[]; finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: number[]) => number[]; stateCloneFunc: (state: number[]) => number[]; newStateFunc: (variant: "SHA-TEST") => number[]; getMAC: () => number[]; constructor(variant: "SHA-TEST", inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType); constructor(variant: "SHA-TEST", inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType); // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(variant: any, inputFormat: any, options?: any) { super(variant, inputFormat, options); this.bigEndianMod = -1; this.converterFunc = stubbedStrConverter; this.roundFunc = stubbedRound; this.stateCloneFunc = stubbedStateClone; this.newStateFunc = (stubbedNewState as unknown) as (variant: "SHA-TEST") => number[]; this.finalizeFunc = stubbedFinalize; // eslint-disable-next-line @typescript-eslint/unbound-method this.getMAC = this._getHMAC; this.intermediateState = [0, 0]; this.variantBlockSize = 64; this.outputBinLen = 64; this.isVariableLen = false; this.HMACSupported = true; } /* * Dirty hack function to expose the protected members of jsSHABase */ // eslint-disable-next-line @typescript-eslint/no-explicit-any getter(propName: string): any { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore - Override "any" ban as this is only used in testing return this[propName]; } /* * Dirty hack function to expose the protected members of jsSHABase */ // eslint-disable-next-line @typescript-eslint/no-explicit-any setter(propName: string, value: any): void { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore - Override "any" ban as this is only used in testing this[propName] = value; } } it("Test Constructor with Empty Options", () => { const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX"); assert.equal(stubbedJsSHA.getter("inputFormat"), "HEX"); assert.equal(stubbedJsSHA.getter("utfType"), "UTF8"); assert.equal(stubbedJsSHA.getter("shaVariant"), "SHA-TEST"); assert.equal(stubbedJsSHA.getter("numRounds"), 1); assert.equal(stubbedJsSHA.getter("remainderLen"), 0); assert.equal(stubbedJsSHA.getter("processedLen"), 0); assert.isFalse(stubbedJsSHA.getter("updateCalled")); assert.isFalse(stubbedJsSHA.getter("macKeySet")); assert.deepEqual(stubbedJsSHA.getter("remainder"), []); assert.deepEqual(stubbedJsSHA.getter("keyWithIPad"), []); assert.deepEqual(stubbedJsSHA.getter("keyWithOPad"), []); }); it("Test Constructor with Bad numRounds", () => { assert.throws(() => { new jsSHAATest("SHA-TEST", "HEX", { numRounds: 1.2 }); }, "numRounds must a integer >= 1"); assert.throws(() => { new jsSHAATest("SHA-TEST", "HEX", { numRounds: -1 }); }, "numRounds must a integer >= 1"); }); it("Test update", () => { /* * This is rather difficult to test so we want to check a few basic things: * 1. It passed the input to the string conversion function correctly * 2. It did *not* call the round function when the input was smaller than the block size * 3. Intermediate state was untouched but remainder variables are updated * 4. It *did* call the round function when the input was greater than or equal to than the block size * 5. Intermediate state and associated variables are set correctly */ const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX"), inputStr = "ABCD"; sinon.reset(); stubbedStrConverter .onFirstCall() .returns({ value: [dummyVals[0]], binLen: 32 }) .onSecondCall() .returns({ value: [dummyVals[0], dummyVals[0]], binLen: 64 }); stubbedRound.returns([dummyVals[1], dummyVals[2]]); stubbedJsSHA.update(inputStr); // Check #1 assert.isTrue(stubbedStrConverter.calledOnceWith(inputStr, [], 0)); // Check #2 assert.isFalse(stubbedRound.called); // Check #3 assert.deepEqual(stubbedJsSHA.getter("intermediateState"), [0, 0]); assert.deepEqual(stubbedJsSHA.getter("remainder"), [dummyVals[0]]); assert.equal(stubbedJsSHA.getter("remainderLen"), 32); assert.equal(stubbedJsSHA.getter("processedLen"), 0); assert.isTrue(stubbedJsSHA.getter("updateCalled")); stubbedJsSHA.update(inputStr); // Check #1 again to make sure state is being passed correctly assert.equal(stubbedStrConverter.callCount, 2); assert.isTrue(stubbedStrConverter.getCall(1).calledWithExactly(inputStr, [dummyVals[0]], 32)); // Check #4 assert.isTrue(stubbedRound.calledOnceWith([dummyVals[0], dummyVals[0]], [0, 0])); // Check #5 assert.deepEqual(stubbedJsSHA.getter("intermediateState"), [dummyVals[1], dummyVals[2]]); assert.deepEqual(stubbedJsSHA.getter("remainder"), []); assert.equal(stubbedJsSHA.getter("remainderLen"), 0); assert.equal(stubbedJsSHA.getter("processedLen"), 64); }); it("Test getHash Without Needed outputLen ", () => { const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX"); stubbedJsSHA.setter("isVariableLen", true); assert.throws(() => { stubbedJsSHA.getHash("HEX", {}); }, "Output length must be specified in options"); }); it("Test getHash", () => { /* * Check a few basic things: * 1. The output of getHash should equal the first outputBinLen bits of the output of finalizeFunc * 2. intermediateState and remainder should not be changed by calling getHash * 3. finalize should be called once with the correct inputs */ const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX"); sinon.reset(); stubbedFinalize.returns([dummyVals[0], dummyVals[1]]); stubbedStateClone.returns([dummyVals[2], dummyVals[3]]); stubbedJsSHA.setter("intermediateState", [dummyVals[4]]); const intermediateState = stubbedJsSHA.getter("intermediateState"); stubbedJsSHA.setter("remainder", [dummyVals[5]]); const remainder = stubbedJsSHA.getter("remainder"); stubbedJsSHA.setter("remainderLen", 32); stubbedJsSHA.setter("processedLen", 64); // Check #1 assert.equal(stubbedJsSHA.getHash("HEX"), dummyVals[0].toString(16) + dummyVals[1].toString(16)); // Check #2, note deliberate use of equal vs deepEqual assert.equal(intermediateState, stubbedJsSHA.getter("intermediateState")); assert.equal(remainder, stubbedJsSHA.getter("remainder")); // Check #3 assert.isTrue( stubbedFinalize.calledOnceWith( [dummyVals[5]], 32, 64, [dummyVals[2], dummyVals[3]], stubbedJsSHA.getter("outputBinLen") ) ); }); it("Test getHash for SHAKE", () => { /* * Check a few basic things: * 1. The output of getHash should equal the first outputLen bits of the output of finalizeFunc * 2. finalize should be called once with the correct inputs */ const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX"); stubbedJsSHA.setter("isVariableLen", true); sinon.reset(); stubbedFinalize.returns([dummyVals[0], dummyVals[1]]); stubbedStateClone.returns([dummyVals[2], dummyVals[3]]); stubbedJsSHA.setter("intermediateState", [dummyVals[4]]); stubbedJsSHA.setter("remainder", [dummyVals[5]]); stubbedJsSHA.setter("remainderLen", 32); stubbedJsSHA.setter("processedLen", 64); // Check #1 assert.equal(stubbedJsSHA.getHash("HEX", { outputLen: 32 }), dummyVals[0].toString(16)); // Check #2 assert.isTrue(stubbedFinalize.calledOnceWith([dummyVals[5]], 32, 64, [dummyVals[2], dummyVals[3]], 32)); }); it("Test getHash for numRounds=3", () => { /* * Check a few basic things: * 1. The output of getHash should equal the output of last finalizeFunc call * 2. finalizeFunc should be called numRound times */ const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX", { numRounds: 3 }); sinon.reset(); stubbedFinalize.returns([dummyVals[0], dummyVals[1]]).onCall(2).returns([dummyVals[2], dummyVals[3]]); // Check #1 assert.equal(stubbedJsSHA.getHash("HEX"), dummyVals[2].toString(16) + dummyVals[3].toString(16)); // Check #2 assert.equal(stubbedFinalize.callCount, 3); }); it("Test getHash for SHAKE numRounds=3", () => { /* * Check a few basic things: * 1. The output of getHash should equal the output of last finalizeFunc call * 2. finalizeFunc should be called numRound times * 3. The last numRound-1 calls of finalizeFunc should have the last 32-outputLen bits 0ed out */ const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX", { numRounds: 3 }); stubbedJsSHA.setter("isVariableLen", true); sinon.reset(); stubbedFinalize.returns([dummyVals[0], dummyVals[1]]).onCall(2).returns([dummyVals[2], dummyVals[3]]); // Check #1 assert.equal(stubbedJsSHA.getHash("HEX", { outputLen: 24 }), dummyVals[2].toString(16).substr(0, 6)); // Check #2 assert.equal(stubbedFinalize.callCount, 3); // Check #3 stubbedFinalize.getCall(1).calledWith([dummyVals[0], dummyVals[1] & 0x00ffffff], 24); stubbedFinalize.getCall(2).calledWith([dummyVals[0], dummyVals[1] & 0x00ffffff], 24); }); it("Test setHMACKey with Short Key", () => { /* * Check a few basic things: * 1. keyWithIPad is set correctly * 2. keyWithOPad is set correctly * 3. The round function was called and its return value stored as intermediateState * 4. macKeySet was set * 5. processedLen was updated */ const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX"); sinon.reset(); stubbedRound.returns([dummyVals[0], dummyVals[1]]); stubbedJsSHA.setHMACKey("ABCD", "TEXT"); // Check #1 assert.deepEqual( stubbedJsSHA.getter("keyWithIPad"), [0x41424344, 0].map((val) => { return val ^ 0x36363636; }) ); // Check #2 assert.deepEqual( stubbedJsSHA.getter("keyWithOPad"), [0x41424344, 0].map((val) => { return val ^ 0x5c5c5c5c; }) ); // Check #3 assert.isTrue( stubbedRound.calledOnceWithExactly( [0x41424344, 0].map((val) => { return val ^ 0x36363636; }), [0, 0] ) ); assert.deepEqual(stubbedJsSHA.getter("intermediateState"), [dummyVals[0], dummyVals[1]]); // Check #4 assert.isTrue(stubbedJsSHA.getter("macKeySet")); // Check #5 assert.equal(stubbedJsSHA.getter("processedLen"), stubbedJsSHA.getter("variantBlockSize")); }); it("Test setHMACKey with Long Key", () => { /* * Check a few basic things: * 1. Finalize was called with the correct keying material * 2. keyWithIPad is set correctly * 3. keyWithOPad is set correctly * 4. The round function was called with the input set as the output from finalize and its return value stored as intermediateState */ const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX"), inputStr = "ABCDEFGHABCD", inputStrPacked = [0x41424344, 0x45464748, 0x41424344]; sinon.reset(); stubbedFinalize.returns([dummyVals[0], dummyVals[1]]); stubbedRound.returns([dummyVals[2], dummyVals[3]]); stubbedNewState.returns([dummyVals[4], dummyVals[5]]); // Need to call setHMACKey with more than 64-bits of key material to test handling of "large" key sizes stubbedJsSHA.setHMACKey(inputStr, "TEXT"); // Check #1 assert.isTrue( stubbedFinalize.calledOnceWithExactly( inputStrPacked, 96, 0, [dummyVals[4], dummyVals[5]], stubbedJsSHA.getter("outputBinLen") ) ); // Check #2 assert.deepEqual( stubbedJsSHA.getter("keyWithIPad"), [dummyVals[0], dummyVals[1]].map((val) => { return val ^ 0x36363636; }) ); // Check #3 assert.deepEqual( stubbedJsSHA.getter("keyWithOPad"), [dummyVals[0], dummyVals[1]].map((val) => { return val ^ 0x5c5c5c5c; }) ); // Check #4 assert.isTrue( stubbedRound.calledOnceWithExactly( [dummyVals[0], dummyVals[1]].map((val) => { return val ^ 0x36363636; }), [0, 0] ) ); assert.deepEqual(stubbedJsSHA.getter("intermediateState"), [dummyVals[2], dummyVals[3]]); }); it("Test setHMACKey Error on Double Call", () => { const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX"); stubbedJsSHA.setter("macKeySet", true); sinon.reset(); assert.throws(() => { stubbedJsSHA.setHMACKey("ABCD", "TEXT"); }, "MAC key already set"); }); it("Test setHMACKey Error on numRounds > 1", () => { const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX", { numRounds: 2 }); sinon.reset(); assert.throws(() => { stubbedJsSHA.setHMACKey("ABCD", "TEXT"); }, "Cannot set numRounds with MAC"); }); it("Test setHMACKey Error on After update", () => { const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX"); stubbedJsSHA.setter("updateCalled", true); sinon.reset(); assert.throws(() => { stubbedJsSHA.setHMACKey("ABCD", "TEXT"); }, "Cannot set MAC key after calling update"); }); it("Test setHMACKey Error on Unsupported Variant", () => { const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX"); stubbedJsSHA.setter("HMACSupported", false); sinon.reset(); assert.throws(() => { stubbedJsSHA.setHMACKey("ABCD", "TEXT"); }, "Variant does not support HMAC"); }); it("Test HMAC Return", () => { /* * Check a few basic things: * 1. It returns the formatted output of the last finalizeFunc call * 2. finalizeFunc was called with a clone of the remainder and correct parameters * 3. roundFunc was called with keyWithOPad * 4. finalizeFunc was called with the output of the previous finalizeFunc's output and the roundFunc's state * 5. remainder, intermediateState, and remainderLen remain untouched * 6. A call to getHash actually returns the HMAC */ sinon.reset(); const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX"), intermediateState = [dummyVals[6], dummyVals[7]], remainder = [dummyVals[0]], keyWithOPad = [dummyVals[10], dummyVals[11]], newState = [dummyVals[8], dummyVals[9]], clonedState = [dummyVals[6], dummyVals[7]], getMACStub = sinon.stub().returns([[dummyVals[2]], dummyVals[3]]); stubbedFinalize .onCall(0) .returns([dummyVals[0], dummyVals[1]]) .onCall(1) .returns([[dummyVals[2]], dummyVals[3]]); stubbedRound.returns([dummyVals[4], dummyVals[5]]); stubbedStateClone.returns(clonedState); stubbedNewState.returns(newState); stubbedJsSHA.setter("macKeySet", true); stubbedJsSHA.setter("processedLen", 64); stubbedJsSHA.setter("keyWithOPad", keyWithOPad); stubbedJsSHA.setter("remainder", remainder); stubbedJsSHA.setter("remainderLen", 32); stubbedJsSHA.setter("intermediateState", intermediateState); // Check #1 assert.equal(stubbedJsSHA.getHMAC("HEX"), "deadbeeffacefeed"); // Check #2 stubbedFinalize .getCall(0) .calledWithExactly( remainder, 32, stubbedJsSHA.getter("outputBinLen"), clonedState, stubbedJsSHA.getter("outputBinLen") ); // Check #3 stubbedRound.calledOnceWithExactly(keyWithOPad, newState); // Check #4 stubbedFinalize .getCall(1) .calledWithExactly( [dummyVals[0], dummyVals[1]], stubbedJsSHA.getter("outputBinLen"), stubbedJsSHA.getter("variantBlockSize"), [dummyVals[4], dummyVals[5]], stubbedJsSHA.getter("outputBinLen") ); // Check #5 assert.equal(stubbedJsSHA.getter("remainder"), remainder); assert.equal(stubbedJsSHA.getter("remainderLen"), 32); assert.equal(stubbedJsSHA.getter("intermediateState"), intermediateState); // Check #6 stubbedJsSHA.setter("getMAC", getMACStub); stubbedJsSHA.getHash("HEX"); assert.equal(getMACStub.callCount, 1); }); it("Test getHMAC Error on Not Setting MAC Key", () => { const stubbedJsSHA = new jsSHAATest("SHA-TEST", "HEX"); sinon.reset(); assert.throws(() => { stubbedJsSHA.getHMAC("HEX"); }, "Cannot call getHMAC without first setting MAC key"); }); });
the_stack
import {VersionWorker, Plugin, PluginFactory, Operation} from './api'; import {VersionWorkerImpl} from './worker'; import {ScopedCache} from './cache'; import {NgSwAdapter, NgSwCache, NgSwEvents, NgSwFetch, Clock} from './facade'; import {LOG, LOGGER, Verbosity} from './logging'; import {Manifest, parseManifest} from './manifest'; let driverId: number = 0; /** * Possible states for the service worker. */ export enum DriverState { // Just starting up - this is the initial state. The worker is not servicing requests yet. // Crucially, it does not know if it is an active worker, or is being freshly installed or // updated. STARTUP, // The service worker has an active manifest and is currently serving traffic. READY, // The service worker is READY, but also has an updated manifest staged. When a fetch // is received and no current tabs are open, the worker may choose to activate the // pending manifest and discard the old one, in which case it will transition to READY. UPDATE_PENDING, // The worker has started up, but had no active manifest cached. In this case, it must // download from the network. INSTALLING, // Something happened that prevented the worker from reaching a good state. In the LAME // state the worker forwards all requests directly to the network, effectively self-disabling. // The worker will not recover from this state until it is terminated. LAME, } /** * Manages the lifecycle of the Angular service worker. * * `Driver` is a singleton within the worker. It attempts to instantiate a `VersionWorker`, * a class that serves fetch (and other) events according to the instructions defined in a * particular version of a manifest file. The `Driver` maintains an active `VersionWorker` * and routes events to it when possible. A state machine ensures the `Driver` always * responds to traffic correctly. * * A principle consideration for choosing a 'correct' manifest with which to serve traffic * is when to switch to a new (updated) version of the manifest. `Driver` is responsible * for periodically downloading fresh versions of the manifest from the server, staging * a new `VersionWorker` if the manifest has been updated, and deciding when to switch app * traffic from the old to the new manifest. A large part of `Driver`'s logic is devoted * to this update process. * * At a high level, updates follow this process: * * 1) When a new `Driver` is created (worker startup), it initializes into a READY state * and then checks for an updated manifest from the network. * * 2) If such a manifest is found, the `Driver` creates a new `VersionWorker` and attempts * to set it up successfully, updating files from the old `VersionWorker` currently * serving traffic. * * 3) If that update is successful, the driver queues the new manifest as staged and * enters an UPDATE_PENDING state. * * 4) On the next `fetch` event that meets all the criteria for an update, the `Driver` * activates the stage manifest, begins serving traffic with the new `VersionWorker`, * and instructs the old `VersionWorker to clear up. */ export class Driver { // The worker always starts in STARTUP. private state: DriverState = DriverState.STARTUP; // A hash of the pending manifest, if the worker is in an UPDATE_PENDING state. private pendingUpdateHash: string = null; // Tracks which `Driver` instance this is, useful for testing only. private id: number; // A `Promise` that resolves when the worker reaches a state other than READY. The worker // blocks on this when handling fetch events. private init: Promise<any>; // The currently active `VersionWorkerImpl`, which handles events for the active manifest. // This is only valid if the worker is in the READY or UPDATE_PENDING states. private active: VersionWorkerImpl; // A `CacheStorage` API wrapper with the service worker prefix. This is used to delete all // caches associated with the worker when upgrading between worker versions or recovering // from a critical error. private scopedCache: ScopedCache; // The next available id for observable streams used to communicate with application tabs. private streamId: number = 0; // A map of stream ids to `MessagePort`s that communicate with application tabs. private streams: {[key: number]: MessagePort} = {}; // The worker's lifecycle log, which is appended to when lifecycle events happen. This // is not ever cleared, but should not grow very large. private lifecycleLog: string[] = []; // A `Promise` that resolves when the worker enters the READY state. Used only in tests. ready: Promise<any>; // A resolve function that resolves the `ready` promise. Used only for testing. readyResolve: Function; // A `Promise` that resolves when the worker enters the UPDATE_PENDING state. Used only // in tests. updatePending: Promise<any>; // A resolve function that resolves the `ready` promise. Used only for testing. updatePendingResolve: Function; // Stream IDs that are actively listening for update lifecycle events. private updateListeners: number[] = []; constructor( private manifestUrl: string, private plugins: PluginFactory<any>[], private scope: ServiceWorkerGlobalScope, private adapter: NgSwAdapter, private cache: NgSwCache, private events: NgSwEvents, public fetcher: NgSwFetch, public clock: Clock) { this.id = driverId++; // Set up Promises for testing. this.ready = new Promise(resolve => this.readyResolve = resolve) this.updatePending = new Promise(resolve => this.updatePendingResolve = resolve); // All SW caching should go through this cache. this.scopedCache = new ScopedCache(this.cache, 'ngsw:'); // Subscribe to all the service worker lifecycle events: events.install = (event: InstallEvent) => { this.lifecycle('install event'); event.waitUntil(Promise.resolve() // On installation, wipe all the caches to avoid any inconsistent states // with what the previous script version saved. .then(() => this.reset()) // Get rid of the old service worker asap. .then(() => this.scope.skipWaiting()) ); }; events.activate = (event: ActivateEvent) => { this.lifecycle('activate event'); // Kick off the startup process right away, so the worker doesn't wait for fetch // events before getting a manifest and installing the app. if (!this.init) { this.startup(); } // Take over all active pages. At this point the worker is still in STARTUP, so // all requests will fall back on the network. event.waitUntil(this.scope.clients.claim()); }; events.fetch = (event: FetchEvent) => { const req = event.request; // Handle the log event no matter what state the worker is in. if (req.url.endsWith('/ngsw.log')) { event.respondWith(this .status() .then(status => this.adapter.newResponse(JSON.stringify(status, null, 2))) ); return; } // Skip fetch events when in LAME state - no need to wait for init for this. // Since the worker doesn't call event.respondWith(), the browser will go to // the network for this request. if (this.state === DriverState.LAME) { return; } // If this is the first request and the worker is in STARTUP, kick off the startup // process. This is a normal step for subsequent startups of the worker (during the // first one, the activate event usually kicks off the startup process). if (this.state === DriverState.STARTUP && !this.init) { this.startup(); } // Should not happen, but just in case, throw an error. if (!this.init) { throw new Error(`init Promise not present in state ${DriverState[this.state]}`); } event.respondWith(this // For every request, first wait on initialization. After this.init resolves, the // worker should no longer be in STARTUP. Choose the strategy to handle the // request based on the worker's state. .init .then(() => { switch (this.state) { case DriverState.READY: // The worker is ready and this.active is set to a VersionWorker. return this.active.fetch(req); case DriverState.UPDATE_PENDING: // The worker is ready but has a pending update. Decide whether to activate // the pending manifest before servicing the request. return this .maybeUpdate(event.clientId) // After maybeUpdate(), the worker is either still in UPDATE_PENDING (the // worker couldn't update because other tabs were open, etc) or in READY // and this.active is now the new VersionWorker for the updated manifest. // Either way, serve the request with the active worker. .then(() => this.active.fetch(req)); case DriverState.INSTALLING: case DriverState.LAME: // Whether the worker is still INSTALLING or has freshly transitioned to a // LAME state, serve the request with the network. return this.fetcher.request(req, true); default: // Shouldn't happen, but just be safe and serve the request from the network. return this.fetcher.request(req, true); } }) ); }; events.message = (event: MessageEvent) => { // Skip all events in the LAME state. if (this.state === DriverState.LAME) { return; } // Start up if needed (see fetch above). if (this.state === DriverState.STARTUP && !this.init) { this.startup(); } if (!this.init) { throw new Error(`init Promise not present in state ${DriverState[this.state]}`); } // Some sanity checks against the incoming message - is it intended for the worker? if (event.ports.length !== 1 || !event.data || !event.data.hasOwnProperty('$ngsw')) { return; } // Wait for initialization. this.init.then(() => { // Did the worker reach a good state? if (this.state !== DriverState.READY && this.state !== DriverState.UPDATE_PENDING) { // No - drop the message, it can't be handled until the worker is in a good state. return; } // The message includes a MessagePort for sending responses. Set this up as a stream. const respond: MessagePort = event.ports[0]; const id = this.streamId++; this.streams[id] = respond; // Send the id as the first response. This can be used by the client to notify of an // "unsubscription" to this request. respond.postMessage({'$ngsw': true, 'id': id}); // Handle the actual payload. this.handleMessage(event.data, id); }); } events.push = (event: PushEvent) => { // Skip all PUSH messages in the LAME state. Technically this isn't valid per the spec, // but better to ignore them than throw random errors. if (this.state === DriverState.LAME) { return; } // Start up if needed (see fetch above). if (this.state === DriverState.STARTUP && !this.init) { this.startup(); } if (!this.init) { throw new Error(`init Promise not present in state ${DriverState[this.state]}`); } Promise // Wait for both initialization and the data sent with the push message. .all([ this.init, event.data.text(), ]) // Result of this.init is unimportant as long as it's resolved. .then(results => results[1]) .then(data => { // Make sure the worker ended up in a good state after initialization. if (this.state !== DriverState.READY && this.state !== DriverState.UPDATE_PENDING) { // If not, drop the push message. Again, not valid per the spec, but safer than attempting // to handle and throwing errors. return; } // Handle the message with the active VersionWorker. this.active.push(data); }); }; } /** * Write a message to the lifecycle log. */ private lifecycle(msg: string): void { this.lifecycleLog.push(msg); } /** * Attempt to reset the service worker to a pristine state, as if one had never been installed * before. * * This involves removing all of the caches that fall under the `ScopedCache` used by the * worker. */ private reset(): Promise<any> { return this .scopedCache // List all the keys in the cache. .keys() .then(keys => Promise // Wait for them all to be removed. .all(keys.map(key => this.scopedCache.remove(key))) // Log it for debugging. .then(() => this.lifecycle(`reset removed ${keys.length} ngsw: caches`))); } /** * Start up the worker. * * this.init is set up as a Promise that resolves when the worker exits the STARTUP state. * In the background, it also kicks off a check for a new version of the manifest. * * In the usual update flow, this means that the worker will first transition to READY, * and then to UPDATE_PENDING when the updated manifest is set up and ready to be served. */ private startup() { this.init = this.initialize(); this.init.then(() => this.checkForUpdate()); } /** * Possibly switch to a pending manifest if it's safe to do so. * * Safety is determined by whether there are other application tabs open, since they may * be depending on the worker to serve lazily-loaded js from the previous version of the * app, or it may be using a shared IndexedDB across all the tabs that can't be updated * yet, etc. */ private maybeUpdate(clientId: any): Promise<any> { return this .scope .clients .matchAll() .then(clients => { // Currently, the only criteria is that this must be a fresh tab (no current // clients). if (clients.length !== 0) { return null; } return this.doUpdate(); }); } /** * Switch to the staged worker (if any). * * After updating, the worker will be in state READY, always. If a staged manifest * was present and validated, it will be set as active. * * If `expectVersion` is set but the staged manifest does not match the expected * version, the update is skipped and the result resolves to false. */ private doUpdate(expectVersion?: string): Promise<boolean> { return this .fetchManifestFromCache('staged') .then(manifest => { // If no staged manifest exists in the cache, just transition to READY now. if (!manifest) { this.transition(DriverState.READY); return false; } // If a particular version is expected if (!!expectVersion && manifest._hash !== expectVersion) { return false; } return this // Open the new manifest. This implicitly validates that the manifest was // downloaded correctly and is ready to serve, and can resolve with null if // this validation fails. .openManifest(manifest) .then(worker => this // Regardless of whether the new manifest validated correctly, clear the staged // manifest. This ensures that if the validation failed, the worker will try again. .clearStaged() // If the worker is present, set the manifest as active, ensuring it will be used // in the future. .then(() => worker ? this.setManifest(manifest, 'active') : null) .then(() => { if (worker) { // Set this.active to the new worker. const oldActive = this.active; this.active = worker as VersionWorkerImpl; // At this point, the old worker can clean up its caches as they're no longer // needed. this .cleanup(oldActive) .then(() => this.lifecycle(`cleaned up old version ${oldActive.manifest._hash}`)); // Notify update listeners that an update has occurred. this.updateListeners.forEach(id => { this.sendToStream(id, { type: 'activation', version: manifest._hash, }); }); this.lifecycle(`updated to manifest ${manifest._hash}`); } // Regardless of whether the manifest successfully validated, it is no longer // a pending update, so transition to READY. this.transition(DriverState.READY); return true; }) as Promise<boolean> ); }); } /** * Clear the currently active manifest (if any). */ private clearActive(): Promise<any> { // Fail if the worker is in a state which expects an active manifest to be present. if (this.state === DriverState.READY || this.state === DriverState.UPDATE_PENDING) { return Promise.reject("Cannot clear the active manifest when it's being used."); } return this.scopedCache.invalidate('active', this.manifestUrl); } /** * Clear the currently staged manifest (if any). */ private clearStaged(): Promise<any> { return this.scopedCache.invalidate('staged', this.manifestUrl); } /** * Check the network for a new version of the manifest, and stage it if possible. * * This will request a new copy of the manifest from the network and compare it with * both the active manifest and any staged manifest if present. * * If the manifest is newer than the active or the staged manifest, it will be loaded * and the setup process run for all installed plugins. If it passes that process, it * will be set as the staged manifest, and the worker state will be set to UPDATE_PENDING. * * checkForUpdate() returns a boolean indicating whether a staged update is pending, * regardless of whether this particular call caused the update to become staged. */ private checkForUpdate(): Promise<boolean> { // If the driver isn't in a good serving state, there is no reasonable course of action // if an update would be found, so don't check. if (this.state !== DriverState.READY && this.state !== DriverState.UPDATE_PENDING) { this.lifecycle(`skipping update check, in state ${DriverState[this.state]}`); return Promise.resolve(false); } // If the worker is in the UPDATE_PENDING state, then no need to check, there is an update. if (this.state === DriverState.UPDATE_PENDING) { return Promise.resolve(true); } return Promise // Fetch active and staged manifests and a fresh copy of the manifest from the network. // Technically, the staged manifest should be null, but it is checked here for thoroughness. .all([ this.fetchManifestFromCache('active'), this.fetchManifestFromCache('staged'), this.fetchManifestFromNetwork(), ]) .then((manifests: Manifest[]) => { const [active, staged, network] = manifests; // If the request for a manifest from the network was unsuccessful, there's no // way to tell if an update is available, so skip. if (!network) { // Even if the network request failed, there could still be a pending manifest. // This technically shouldn't happen since the worker should have been placed in // the UPDATE_PENDING state by initialize(), but this is here for safety. if (!!staged) { // If there is a staged manifest, transition to UPDATE_PENDING. this.pendingUpdateHash = staged._hash; this.transition(DriverState.UPDATE_PENDING); return true; } else { return false; } } // If the network manifest is currently the active manifest, no update is available. if (!!active && active._hash === network._hash) { return false; } // If the network manifest is already staged, just go to UPDATE_PENDING. Theoretically // this shouldn't happen since initialize() should have already transitioned to // UPDATE_PENDING, but as above, this is here for safety. if (!!staged && staged._hash === network._hash) { this.lifecycle(`network manifest ${network._hash} is already staged`); this.pendingUpdateHash = staged._hash; this.transition(DriverState.UPDATE_PENDING); return true; } // A Promise which may do extra work before the update. let start = Promise.resolve(); // If there is a staged manifest, then before setting up the update, remove it. if (!!staged) { this.lifecycle(`staged manifest ${staged._hash} is old, removing`); start = this.clearStaged(); } return start // Create a VersionWorker from the network manifest, setting up all registered plugins. // this.active is passed as if there is a currently active worker, the updated // VersionWorker will possibly update from it, saving bytes for files which have not // changed between manifest versions. This update process is plugin-specific. .then(() => this.setupManifest(network, this.active)) // Once the new VersionWorker has been set up properly, mark the manifest as staged. // This sets up the worker to update to it on a future fetch event, when maybeUpdate() // decides to update. .then(() => this.setManifest(network, 'staged')) .then(() => { // Finally, transition to UPDATE_PENDING to indicate updates should be checked. this.pendingUpdateHash = network._hash; this.transition(DriverState.UPDATE_PENDING); this.lifecycle(`staged update to ${network._hash}`); return true; }); }); } /** * Transitions the worker out of the STARTUP state, by either serving the active * manifest or installing from the network if one is not present. * * Initialization can fail, which will result in the worker ending up in a LAME * state where it effectively disables itself until the next startup. * * This function returns a Promise which, when resolved, guarantees the worker is * no longer in a STARTUP state. */ private initialize(): Promise<any> { // Fail if the worker is initialized twice. if (!!this.init) { throw new Error("double initialization!"); } // Initialization is only valid in the STARTUP state. if (this.state !== DriverState.STARTUP) { return Promise.reject(new Error("driver: initialize() called when not in STARTUP state")); } return Promise // Fetch both active and staged manifests. .all([ this.fetchManifestFromCache('active'), this.fetchManifestFromCache('staged'), ]) .then(manifests => { const [active, staged] = manifests; if (!active) { // If there's no active manifest, then a network installation is required. this.transition(DriverState.INSTALLING); // Installing from the network is asynchronous, but initialization doesn't block on // it. Therefore the Promise returned from doInstallFromNetwork() is ignored. this.doInstallFromNetwork(); return null; } return this // Turn the active manifest into a VersionWorker, which will implicitly validate that // all files are cached correctly. If this fails, openManifest() can resolve with a // null worker. .openManifest(active) .then(worker => { if (!worker) { // The active manifest is somehow invalid. Nothing to do but enter a LAME state // and remove it, and hope the next time the worker is initialized, a fresh copy // will be installed from the network without issues. this.transition(DriverState.LAME); return this.clearActive(); } this.lifecycle(`manifest ${active._hash} activated`); this.active = worker as VersionWorkerImpl; // If a staged manifest exist, go to UPDATE_PENDING instead of READY. if (!!staged) { if (staged._hash === active._hash) { this.lifecycle(`staged manifest ${staged._hash} is already active, cleaning it up`); this.transition(DriverState.READY); return this.clearStaged(); } else { this.lifecycle(`staged manifest ${staged._hash} present at initialization`); this.pendingUpdateHash = staged._hash; this.transition(DriverState.UPDATE_PENDING); return null; } } this.transition(DriverState.READY); }); }); } /** * Fetch and install a manifest from the network. * * If successful, the manifest will become active and the worker will finish in state * READY. If any errors are encountered, the worker will transition to a LAME state. */ private doInstallFromNetwork(): Promise<any> { return this // First get a new copy of the manifest from the network. .fetchManifestFromNetwork() .then(manifest => { if (!manifest) { // If it wasn't successful, there's no graceful way to recover, so go to a // LAME state. this.lifecycle('no network manifest found to install from'); this.transition(DriverState.LAME); return null; } return this // Set up a new VersionWorker using this manifest, which could fail if all of the // resources listed don't download correctly. .setupManifest(manifest, null) .then(worker => { if (!worker) { this.lifecycle('network manifest setup failed'); this.transition(DriverState.LAME); return null; } this // Setup was successful, and the VersionWorker is ready to serve traffic. Set the // new manifest as active. .setManifest(manifest, 'active') .then(() => { // Set this.active and transition to READY. this.active = worker as VersionWorkerImpl; this.lifecycle(`installed version ${manifest._hash} from network`); this.transition(DriverState.READY); }); }); }); } /** * Fetch a cached copy of the manifest. */ private fetchManifestFromCache(cache: string): Promise<Manifest> { return this .scopedCache .load(cache, this.manifestUrl) .then(resp => this.manifestFromResponse(resp)); } /** * Fetch a copy of the manifest from the network. * * Resolves with null on a failure. */ private fetchManifestFromNetwork(): Promise<Manifest> { return this .fetcher .refresh(this.manifestUrl) .then(resp => this.manifestFromResponse(resp)) .catch(() => null); } /** * Parse the given `Response` and return a `Manifest` object. */ private manifestFromResponse(resp: Response): Promise<Manifest> { if (!resp || resp.status !== 200) { return null; } return resp.text().then(body => parseManifest(body)); } /** * Store the given `Manifest` in the given cache. */ private setManifest(manifest: Manifest, cache: string): Promise<void> { return this.scopedCache.store(cache, this.manifestUrl, this.adapter.newResponse(manifest._json)); } /** * Construct a `VersionWorker` for the given manifest. * * This worker will have all of the plugins specified during the bootstrap process installed, * but not yet initialized (setup()). */ private workerFromManifest(manifest: Manifest): VersionWorkerImpl { const plugins: Plugin<any>[] = []; const worker = new VersionWorkerImpl(this, this.scope, manifest, this.adapter, new ScopedCache(this.scopedCache, `manifest:${manifest._hash}:`), this.clock, this.fetcher, plugins); plugins.push(...this.plugins.map(factory => factory(worker))); return worker; } /** * Instantiates a `VersionWorker` from a manifest and runs it through its setup process. * * Optionally, the worker can be directed to update from an existing `VersionWorker` * instead of performing a fresh setup. This can save time if resources have not changed * between the old and new manifests. */ private setupManifest(manifest: Manifest, existing: VersionWorker = null): Promise<VersionWorker> { const worker = this.workerFromManifest(manifest); return worker .setup(existing as VersionWorkerImpl) .then(() => worker); } /** * Instantiates a `VersionWorker` from a manifest that was previously set up according * by `setupManifest`. * * The worker will be validated (its caches checked against the manifest to assure all * resources listed are cached properly). If it passes validation, the returned Promise * will resolve with the worker instance, if not it resolves with `null`. */ private openManifest(manifest: Manifest): Promise<VersionWorker> { const worker = this.workerFromManifest(manifest); return worker // Run validation to make sure all resources have been previously set up properly. .validate() .then(valid => { if (!valid) { // The worker wasn't valid - something was missing from the caches. this.lifecycle(`cached version ${manifest._hash} not valid`); // Attempt to recover by cleaning up the worker. This should allow it to be // freshly installed the next time the `Driver` starts. return this .cleanup(worker) .then(() => null); } return worker; }); } /** * Run a `VersionWorker` through its cleanup process, resolving when it completes. */ private cleanup(worker: VersionWorkerImpl): Promise<any> { return worker .cleanup() .reduce<Promise<Response>>( (prev, curr) => prev.then(resp => curr()), Promise.resolve(null) ); } /** * Fetch the status of the `Driver`, including current state and lifecycle messages. */ private status(): Promise<any> { return Promise.resolve({ state: DriverState[this.state], lifecycleLog: this.lifecycleLog, }); } /** * Transition into a new state. * * `transition` logs the transition, and also handles resolving several promises useful * for testing the more asynchronous parts of the `Driver` which aren't exposed via the * more public API. */ private transition(state: DriverState): void { this.lifecycle(`transition from ${DriverState[this.state]} to ${DriverState[state]}`); this.state = state; // If the `DRIVER` entered the READY state, resolve the ready Promise. if (state === DriverState.READY && this.readyResolve !== null) { const resolve = this.readyResolve; this.readyResolve = null; resolve(); } // If the driver entered the UPDATE_PENDING state, resolve the update pending Promise, // and reset the ready Promise. if (state === DriverState.UPDATE_PENDING && this.updatePendingResolve !== null) { this.ready = new Promise(resolve => this.readyResolve = resolve) const resolve = this.updatePendingResolve; this.updatePendingResolve = null; resolve(); } // If the driver entered the UPDATE_PENDING state, notify all update subscribers // about the pending update. if (state === DriverState.UPDATE_PENDING && this.pendingUpdateHash !== null) { this.updateListeners.forEach(id => this.sendToStream(id, { type: 'pending', version: this.pendingUpdateHash, })); } else if (state !== DriverState.UPDATE_PENDING) { // Reset the pending update hash if not transitioning to UPDATE_PENDING. this.pendingUpdateHash = null; } } /** * Process a `postMessage` received by the worker. */ private handleMessage(message: Object, id: number): void { // If the `Driver` is not in a known good state, nothing to do but exit. if (this.state !== DriverState.READY && this.state !== DriverState.UPDATE_PENDING) { this.lifecycle(`can't handle message in state ${DriverState[this.state]}`) return; } // The message has a 'cmd' key which determines the action the `Driver` will take. // Some commands are handled directly by the `Driver`, the rest are passed on to the // active `VersionWorker` to be handled by a plugin. switch (message['cmd']) { // A ping is a request for the service worker to assert it is up and running by // completing the "Observable" stream. case 'ping': this.lifecycle(`responding to ping on ${id}`) this.closeStream(id); break; // An update message is a request for the service worker to keep the application // apprised of any pending update events, such as a new manifest becoming pending. case 'update': this.updateListeners.push(id); // Since this is a new subscriber, check if there's a pending update now and // deliver an initial event if so. if (this.state === DriverState.UPDATE_PENDING && this.pendingUpdateHash !== null) { this.sendToStream(id, { type: 'pending', version: this.pendingUpdateHash, }); } break; // Check for a pending update, fetching a new manifest from the network if necessary, // and return the result as a boolean value beore completing. case 'checkUpdate': this.checkForUpdate().then(value => { this.sendToStream(id, value); this.closeStream(id); }); break; case 'activateUpdate': this.doUpdate(message['version'] || undefined).then(success => { this.sendToStream(id, success); this.closeStream(id); }); break; // 'cancel' is a special command that the other side has unsubscribed from the stream. // Plugins may choose to take action as a result. case 'cancel': // Attempt to look up the stream the client is requesting to cancel. const idToCancel = message['id']; if (!this.streams.hasOwnProperty(id)) { // Not found - nothing to do but exit. return; } // Notify the active `VersionWorker` that the client has unsubscribed. this.active.messageClosed(id); // This listener may have been a subscriber to 'update' events. this.maybeRemoveUpdateListener(id); // Finally, remove the stream. delete this.streams[id]; break; // A request to stream the service worker debugging log. Only one of these is valid // at a time. case 'log': LOGGER.messages = (message: string) => { this.sendToStream(id, message); }; break; // If the command is unknown, delegate to the active `VersionWorker` to handle it. default: this.active.message(message, id); } } /** * Remove the given stream id from the set of subscribers to update events, if present. */ private maybeRemoveUpdateListener(id: number): void { const idx = this.updateListeners.indexOf(id); if (idx !== -1) { this.updateListeners.splice(idx, 1); } } /** * Post a message to the stream with the given id. */ sendToStream(id: number, message: Object): void { if (!this.streams.hasOwnProperty(id)) { return; } this.streams[id].postMessage(message); } /** * Complete the stream with the given id. * * Per the protocol between the service worker and client tabs, a completion is modeled as * a null message. */ closeStream(id: number): void { if (!this.streams.hasOwnProperty(id)) { return; } this.streams[id].postMessage(null); delete this.streams[id]; } }
the_stack
/// <reference path="../../node_modules/monaco-editor/monaco.d.ts" /> import * as React from 'react' import * as ReactDOM from 'react-dom' import { osMac } from '../utils' import { SelectionState } from 'draft-js' import { EditorMessage, EditorMessageType, EditorKeys } from '../utils/EditorMessages' import { CodeCellUpdate, DiagnosticSeverity } from '../evaluation' import './MonacoCellEditor.scss' export interface MonacoCellEditorProps { blockProps: { codeCellFocused: (currentKey: string) => void, codeCellBlurred: (currentKey: string) => void, subscribeToEditor: (callback: (message: EditorMessage) => void) => void, selectNext: (currentKey: string) => boolean, selectPrevious: (currentKey: string) => boolean, updateTextContentOfBlock: (blockKey: string, textContent: string) => void, setSelection: (anchorKey: string, offset: number) => void, setModelId: (modelId: string) => void, updateCodeCell(buffer: string): Promise<CodeCellUpdate | null>, evaluate: () => void } block: { key: string text: string } } interface MonacoCellEditorState { created: boolean } enum ViewEventType { ViewLinesDeleted = 8, ViewLinesInserted = 9 } export class MonacoCellEditor extends React.Component<MonacoCellEditorProps, MonacoCellEditorState> { private windowResizeHandler: any; private editor?: monaco.editor.ICodeEditor; private lastUpdateResponse: CodeCellUpdate | null = null private markedTextIds: string[] = [] constructor(props: MonacoCellEditorProps) { super(props) this.state = { created: true } } componentDidMount() { const monacoContainer = ReactDOM.findDOMNode(this) this.editor = this.buildEditor(monacoContainer) this.props.blockProps.setModelId(this.editor.getModel().id) this.props.blockProps.subscribeToEditor((message: EditorMessage) => { this.onEditorMessage(message) }) setTimeout(() => { if (this.state.created) { this.setState({ created: false }) } this.updateLayout() this.moveSelection(false, false) }, 0) } componentWillUnmount() { this.props.blockProps.codeCellBlurred(this.getKey()) window.removeEventListener("resize", this.windowResizeHandler) this.editor!.dispose() } getKey() { return this.props.block.key } render() { return ( <div onClick={(e) => this.focus(e)}> </div> ) } buildEditor(elem: Element) { const targetElem = document.createElement("div") const editor = monaco.editor.create(targetElem, { value: this.props.block.text, language: "csharp", scrollBeyondLastLine: false, roundedSelection: false, overviewRulerLanes: 0, // 0 = hide overview ruler wordWrap: "on", formatOnType: true, lineNumbers: "on", lineDecorationsWidth: 8, contextmenu: false, cursorBlinking: 'phase', minimap: { enabled: false }, scrollbar: { // must explicitly hide scrollbars so they don't interfere with mouse events horizontal: 'hidden', vertical: 'hidden', handleMouseWheel: false, useShadows: false, } }) editor.onDidChangeModelContent((e) => { this.syncContent() }) editor.onKeyDown(e => this.onKeyDown(e)) editor.onDidBlurEditor(() => { this.props.blockProps.codeCellBlurred(this.getKey()); this.dismissParameterHintsWindow() }) editor.onDidFocusEditor(() => { this.props.blockProps.codeCellFocused(this.getKey()); }) const internalViewEventsHandler = { handleEvents: (e: any) => this.handleInternalViewEvents(e) }; let untypedEditor: any = editor untypedEditor._view.eventDispatcher.addEventHandler(internalViewEventsHandler) this.windowResizeHandler = () => this.updateLayout() window.addEventListener("resize", this.windowResizeHandler) setTimeout(() => { this.updateLayout() this.focus() }, 0) elem.appendChild(targetElem) return editor } syncContent() { let buffer = this.getContent() this.props.blockProps.updateTextContentOfBlock(this.getKey(), buffer) this.updateCodeCellStatus(buffer) // No need to await this } async updateCodeCellStatus(buffer: string) { this.lastUpdateResponse = await this.props.blockProps.updateCodeCell(buffer) this.clearMarkedText() if (!this.lastUpdateResponse) return for (const diagnostic of this.lastUpdateResponse.diagnostics) { if (diagnostic.severity !== DiagnosticSeverity.Error) continue this.markText({ options: { inlineClassName: 'xi-diagnostic', hoverMessage: diagnostic.message }, range: diagnostic.range }) } } markText(decoration: monaco.editor.IModelDeltaDecoration) { let newIds = this.editor!.getModel().deltaDecorations([], [decoration]) this.markedTextIds.push(...newIds) } // TODO: Use this on cell reset, once we have that clearMarkedText() { this.editor!.getModel().deltaDecorations(this.markedTextIds, []) this.markedTextIds = [] } onEditorMessage(message: EditorMessage) { // ignore events not related to this instance if (message.target !== this.getKey()) return if (message.type === EditorMessageType.setSelection) { const isBackwards = message.data.isBackwards const isUpArrow = message.data.keyCode == EditorKeys.UP || message.data.keyCode == EditorKeys.BACKSPACE const startColumn = !isBackwards this.moveSelection(!isBackwards, startColumn) this.focus() } if (message.type == EditorMessageType.setCursor) { this.editor!.setPosition(message.data) this.focus() } } onKeyDown(e: monaco.IKeyboardEvent) { if (this.isCompletionWindowVisible()) return if (e.keyCode == monaco.KeyCode.Enter) { if (this.onEnter(e)) e.preventDefault() e.stopPropagation() return } let handled = false if ((e.keyCode == monaco.KeyCode.UpArrow && !this.isParameterHintsWindowVisible()) || e.keyCode == monaco.KeyCode.LeftArrow) handled = this.handleEditorBoundaries(-1, e.keyCode == monaco.KeyCode.UpArrow) else if ((e.keyCode == monaco.KeyCode.DownArrow && !this.isParameterHintsWindowVisible()) || e.keyCode == monaco.KeyCode.RightArrow) handled = this.handleEditorBoundaries(1, e.keyCode == monaco.KeyCode.DownArrow) else if (e.keyCode == monaco.KeyCode.Backspace && !this.isParameterHintsWindowVisible()) handled = this.handleEditorBoundaries(-1, false); if (handled) { e.preventDefault() e.stopPropagation() } } onEnter(e: monaco.IKeyboardEvent): boolean { const isMod = osMac ? e.metaKey : e.ctrlKey // Shift+Mod+Enter: new markdown cell (do we need this now?) if (e.shiftKey && isMod) { // TODO return true } // Mod+Enter: evaluate if (isMod) { this.props.blockProps.evaluate() return true } // Shift+Enter: regular newline+indent if (e.shiftKey) return false if (this.lastUpdateResponse && this.lastUpdateResponse.isSubmissionComplete && !this.isSomethingSelected() && this.isCursorAtEnd()) { let content = this.getContent() if (!content || !content.trim()) return false this.props.blockProps.evaluate() return true } return false } isSomethingSelected() { let sel = this.editor!.getSelection() return !sel.getStartPosition().equals(sel.getEndPosition()) } isCursorAtEnd() { let pos = this.editor!.getPosition() let model = this.editor!.getModel() return pos.lineNumber == model.getLineCount() && pos.column == model.getLineMaxColumn(pos.lineNumber) } // TODO: It would be better if we had API access to SuggestController, and if // SuggestController had API to check widget visibility. In the future // we could add this functionality to monaco. // (or if our keybindings had access to 'suggestWidgetVisible' context key) isCompletionWindowVisible() { return this.isMonacoWidgetVisible("suggest-widget") } isParameterHintsWindowVisible() { return this.isMonacoWidgetVisible("parameter-hints-widget") } dismissParameterHintsWindow() { if (this.isParameterHintsWindowVisible()) this.editor!.setPosition({ lineNumber: 1, column: 1 }) } isMonacoWidgetVisible(widgetClassName: string) { let node = this.editor!.getDomNode() if (node == null) return false let widgets = node.getElementsByClassName(widgetClassName) for (var i = 0; i < widgets.length; i++) if (widgets[i].classList.contains("visible")) return true return false } focus(e?: any) { this.editor!.focus() this.props.blockProps.setSelection(this.getKey(), 0) if (e) e.stopPropagation() } blur(e?: any) { if (this.editor!.isFocused()) { (document.activeElement as any).blur() } } updateLayout() { let clientWidth = this.getClientWidth() let fontSize = this.editor!.getConfiguration().fontInfo.fontSize || 0 this.editor!.layout({ // NOTE: Something weird happens in layout, and padding+border are added // on top of the total width by monaco. So we subtract those here. // Keep in sync with editor.css. Currently 0.5em left/right padding // and 1px border means (1em + 2px) to subtract. width: clientWidth - (fontSize + 2), height: (this.editor as any)._view._context.viewLayout._linesLayout.getLinesTotalHeight() }) } handleInternalViewEvents(events: any[]) { for (let i = 0, len = events.length; i < len; i++) { let type: number = events[i].type; // This is the best way for us to find out about lines being added and // removed, if you take wrapping into account. if (type == ViewEventType.ViewLinesInserted || type == ViewEventType.ViewLinesDeleted) this.updateLayout() } } handleEditorBoundaries(dir: 1 | -1, useLineBoundary: boolean) { let handled = false let pos = this.editor!.getPosition() let isBeginning = (pos.lineNumber === 1 && dir === -1) if (!useLineBoundary) isBeginning = isBeginning && pos.column === 1 let isEnd = (pos.lineNumber === this.getEditorLines() && dir === 1) if (!useLineBoundary) isEnd = isEnd && this.getLineColumns(pos.lineNumber) + 1 === pos.column this.blur() if (isBeginning) { handled = this.props.blockProps.selectPrevious(this.getKey()) } else if (isEnd) { handled = this.props.blockProps.selectNext(this.getKey()) } if (!handled) this.focus() return handled } /** * Move selection to start or end of the code block */ moveSelection(firstLine: boolean, firstColumn: boolean) { firstColumn = firstColumn === true let lineIndex = 1 if (!firstLine) lineIndex = this.getEditorLines() const targetColumn = firstColumn ? 1 : (this.editor!.getModel() as any)._lines[lineIndex - 1].text.length + 1 const selection = new monaco.Selection(lineIndex, targetColumn, lineIndex, targetColumn); this.editor!.setSelection(selection) } getClientWidth() { return ReactDOM.findDOMNode(this).clientWidth } getEditorLines() { const model = this.editor!.getModel(); return model ? model.getLineCount() : 0; } getLineColumns(lineIndex: number) { return this.editor!.getModel().getLineContent(lineIndex).length } getContent() { return this.editor!.getModel().getValue() } }
the_stack
/* * --------------------------------------------------------- * Copyright(C) Microsoft Corporation. All rights reserved. * --------------------------------------------------------- * * --------------------------------------------------------- * Generated file, DO NOT EDIT * --------------------------------------------------------- */ // Licensed under the MIT license. See LICENSE file in the project root for full license information. import * as restm from 'typed-rest-client/RestClient'; import vsom = require('./VsoClient'); import basem = require('./ClientApiBases'); import VsoBaseInterfaces = require('./interfaces/common/VsoBaseInterfaces'); import WorkItemTrackingProcessDefinitionsInterfaces = require("./interfaces/WorkItemTrackingProcessDefinitionsInterfaces"); export interface IWorkItemTrackingProcessDefinitionsApi extends basem.ClientApiBase { createBehavior(behavior: WorkItemTrackingProcessDefinitionsInterfaces.BehaviorCreateModel, processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>; deleteBehavior(processId: string, behaviorId: string): Promise<void>; getBehavior(processId: string, behaviorId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>; getBehaviors(processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel[]>; replaceBehavior(behaviorData: WorkItemTrackingProcessDefinitionsInterfaces.BehaviorReplaceModel, processId: string, behaviorId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>; addControlToGroup(control: WorkItemTrackingProcessDefinitionsInterfaces.Control, processId: string, witRefName: string, groupId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control>; editControl(control: WorkItemTrackingProcessDefinitionsInterfaces.Control, processId: string, witRefName: string, groupId: string, controlId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control>; removeControlFromGroup(processId: string, witRefName: string, groupId: string, controlId: string): Promise<void>; setControlInGroup(control: WorkItemTrackingProcessDefinitionsInterfaces.Control, processId: string, witRefName: string, groupId: string, controlId: string, removeFromGroupId?: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control>; createField(field: WorkItemTrackingProcessDefinitionsInterfaces.FieldModel, processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel>; updateField(field: WorkItemTrackingProcessDefinitionsInterfaces.FieldUpdate, processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel>; addGroup(group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>; editGroup(group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>; removeGroup(processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string): Promise<void>; setGroupInPage(group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string, removeFromPageId: string, removeFromSectionId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>; setGroupInSection(group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string, removeFromSectionId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>; getFormLayout(processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.FormLayout>; getListsMetadata(): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListMetadataModel[]>; createList(picklist: WorkItemTrackingProcessDefinitionsInterfaces.PickListModel): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>; deleteList(listId: string): Promise<void>; getList(listId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>; updateList(picklist: WorkItemTrackingProcessDefinitionsInterfaces.PickListModel, listId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>; addPage(page: WorkItemTrackingProcessDefinitionsInterfaces.Page, processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Page>; editPage(page: WorkItemTrackingProcessDefinitionsInterfaces.Page, processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Page>; removePage(processId: string, witRefName: string, pageId: string): Promise<void>; createStateDefinition(stateModel: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateInputModel, processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; deleteStateDefinition(processId: string, witRefName: string, stateId: string): Promise<void>; getStateDefinition(processId: string, witRefName: string, stateId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; getStateDefinitions(processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel[]>; hideStateDefinition(hideStateModel: WorkItemTrackingProcessDefinitionsInterfaces.HideStateModel, processId: string, witRefName: string, stateId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; updateStateDefinition(stateModel: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateInputModel, processId: string, witRefName: string, stateId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; addBehaviorToWorkItemType(behavior: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior, processId: string, witRefNameForBehaviors: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>; getBehaviorForWorkItemType(processId: string, witRefNameForBehaviors: string, behaviorRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>; getBehaviorsForWorkItemType(processId: string, witRefNameForBehaviors: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior[]>; removeBehaviorFromWorkItemType(processId: string, witRefNameForBehaviors: string, behaviorRefName: string): Promise<void>; updateBehaviorToWorkItemType(behavior: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior, processId: string, witRefNameForBehaviors: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>; createWorkItemType(workItemType: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel, processId: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>; deleteWorkItemType(processId: string, witRefName: string): Promise<void>; getWorkItemType(processId: string, witRefName: string, expand?: WorkItemTrackingProcessDefinitionsInterfaces.GetWorkItemTypeExpand): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>; getWorkItemTypes(processId: string, expand?: WorkItemTrackingProcessDefinitionsInterfaces.GetWorkItemTypeExpand): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel[]>; updateWorkItemType(workItemTypeUpdate: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeUpdateModel, processId: string, witRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>; addFieldToWorkItemType(field: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2, processId: string, witRefNameForFields: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>; getWorkItemTypeField(processId: string, witRefNameForFields: string, fieldRefName: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>; getWorkItemTypeFields(processId: string, witRefNameForFields: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2[]>; removeFieldFromWorkItemType(processId: string, witRefNameForFields: string, fieldRefName: string): Promise<void>; updateWorkItemTypeField(field: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2, processId: string, witRefNameForFields: string): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>; } export class WorkItemTrackingProcessDefinitionsApi extends basem.ClientApiBase implements IWorkItemTrackingProcessDefinitionsApi { constructor(baseUrl: string, handlers: VsoBaseInterfaces.IRequestHandler[], options?: VsoBaseInterfaces.IRequestOptions) { super(baseUrl, handlers, 'node-WorkItemTracking-api', options); } public static readonly RESOURCE_AREA_ID = "5264459e-e5e0-4bd8-b118-0985e68a4ec5"; /** * Creates a single behavior in the given process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.BehaviorCreateModel} behavior * @param {string} processId - The ID of the process */ public async createBehavior( behavior: WorkItemTrackingProcessDefinitionsInterfaces.BehaviorCreateModel, processId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>(async (resolve, reject) => { let routeValues: any = { processId: processId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "47a651f4-fb70-43bf-b96b-7c0ba947142b", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>; res = await this.rest.create<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>(url, behavior, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Removes a behavior in the process. * * @param {string} processId - The ID of the process * @param {string} behaviorId - The ID of the behavior */ public async deleteBehavior( processId: string, behaviorId: string ): Promise<void> { return new Promise<void>(async (resolve, reject) => { let routeValues: any = { processId: processId, behaviorId: behaviorId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "47a651f4-fb70-43bf-b96b-7c0ba947142b", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<void>; res = await this.rest.del<void>(url, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Returns a single behavior in the process. * * @param {string} processId - The ID of the process * @param {string} behaviorId - The ID of the behavior */ public async getBehavior( processId: string, behaviorId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>(async (resolve, reject) => { let routeValues: any = { processId: processId, behaviorId: behaviorId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "47a651f4-fb70-43bf-b96b-7c0ba947142b", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>; res = await this.rest.get<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>(url, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Returns a list of all behaviors in the process. * * @param {string} processId - The ID of the process */ public async getBehaviors( processId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel[]> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel[]>(async (resolve, reject) => { let routeValues: any = { processId: processId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "47a651f4-fb70-43bf-b96b-7c0ba947142b", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel[]>; res = await this.rest.get<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel[]>(url, options); let ret = this.formatResponse(res.result, null, true); resolve(ret); } catch (err) { reject(err); } }); } /** * Replaces a behavior in the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.BehaviorReplaceModel} behaviorData * @param {string} processId - The ID of the process * @param {string} behaviorId - The ID of the behavior */ public async replaceBehavior( behaviorData: WorkItemTrackingProcessDefinitionsInterfaces.BehaviorReplaceModel, processId: string, behaviorId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>(async (resolve, reject) => { let routeValues: any = { processId: processId, behaviorId: behaviorId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "47a651f4-fb70-43bf-b96b-7c0ba947142b", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>; res = await this.rest.replace<WorkItemTrackingProcessDefinitionsInterfaces.BehaviorModel>(url, behaviorData, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Creates a control in a group * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Control} control - The control * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} groupId - The ID of the group to add the control to */ public async addControlToGroup( control: WorkItemTrackingProcessDefinitionsInterfaces.Control, processId: string, witRefName: string, groupId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, groupId: groupId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "e2e3166a-627a-4e9b-85b2-d6a097bbd731", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.Control>; res = await this.rest.create<WorkItemTrackingProcessDefinitionsInterfaces.Control>(url, control, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Updates a control on the work item form * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Control} control - The updated control * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} groupId - The ID of the group * @param {string} controlId - The ID of the control */ public async editControl( control: WorkItemTrackingProcessDefinitionsInterfaces.Control, processId: string, witRefName: string, groupId: string, controlId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, groupId: groupId, controlId: controlId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "e2e3166a-627a-4e9b-85b2-d6a097bbd731", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.Control>; res = await this.rest.update<WorkItemTrackingProcessDefinitionsInterfaces.Control>(url, control, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Removes a control from the work item form * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} groupId - The ID of the group * @param {string} controlId - The ID of the control to remove */ public async removeControlFromGroup( processId: string, witRefName: string, groupId: string, controlId: string ): Promise<void> { return new Promise<void>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, groupId: groupId, controlId: controlId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "e2e3166a-627a-4e9b-85b2-d6a097bbd731", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<void>; res = await this.rest.del<void>(url, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Moves a control to a new group * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Control} control - The control * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} groupId - The ID of the group to move the control to * @param {string} controlId - The id of the control * @param {string} removeFromGroupId - The group to remove the control from */ public async setControlInGroup( control: WorkItemTrackingProcessDefinitionsInterfaces.Control, processId: string, witRefName: string, groupId: string, controlId: string, removeFromGroupId?: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.Control>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, groupId: groupId, controlId: controlId }; let queryValues: any = { removeFromGroupId: removeFromGroupId, }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "e2e3166a-627a-4e9b-85b2-d6a097bbd731", routeValues, queryValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.Control>; res = await this.rest.replace<WorkItemTrackingProcessDefinitionsInterfaces.Control>(url, control, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Creates a single field in the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.FieldModel} field * @param {string} processId - The ID of the process */ public async createField( field: WorkItemTrackingProcessDefinitionsInterfaces.FieldModel, processId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel>(async (resolve, reject) => { let routeValues: any = { processId: processId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "f36c66c7-911d-4163-8938-d3c5d0d7f5aa", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel>; res = await this.rest.create<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel>(url, field, options); let ret = this.formatResponse(res.result, WorkItemTrackingProcessDefinitionsInterfaces.TypeInfo.FieldModel, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Updates a given field in the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.FieldUpdate} field * @param {string} processId - The ID of the process */ public async updateField( field: WorkItemTrackingProcessDefinitionsInterfaces.FieldUpdate, processId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel>(async (resolve, reject) => { let routeValues: any = { processId: processId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "f36c66c7-911d-4163-8938-d3c5d0d7f5aa", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel>; res = await this.rest.update<WorkItemTrackingProcessDefinitionsInterfaces.FieldModel>(url, field, options); let ret = this.formatResponse(res.result, WorkItemTrackingProcessDefinitionsInterfaces.TypeInfo.FieldModel, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Adds a group to the work item form * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Group} group - The group * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} pageId - The ID of the page to add the group to * @param {string} sectionId - The ID of the section to add the group to */ public async addGroup( group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, pageId: pageId, sectionId: sectionId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "2617828b-e850-4375-a92a-04855704d4c3", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.Group>; res = await this.rest.create<WorkItemTrackingProcessDefinitionsInterfaces.Group>(url, group, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Updates a group in the work item form * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Group} group - The updated group * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} pageId - The ID of the page the group is in * @param {string} sectionId - The ID of the section the group is in * @param {string} groupId - The ID of the group */ public async editGroup( group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, pageId: pageId, sectionId: sectionId, groupId: groupId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "2617828b-e850-4375-a92a-04855704d4c3", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.Group>; res = await this.rest.update<WorkItemTrackingProcessDefinitionsInterfaces.Group>(url, group, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Removes a group from the work item form * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} pageId - The ID of the page the group is in * @param {string} sectionId - The ID of the section to the group is in * @param {string} groupId - The ID of the group */ public async removeGroup( processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string ): Promise<void> { return new Promise<void>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, pageId: pageId, sectionId: sectionId, groupId: groupId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "2617828b-e850-4375-a92a-04855704d4c3", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<void>; res = await this.rest.del<void>(url, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Moves a group to a different page and section * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Group} group - The updated group * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} pageId - The ID of the page the group is in * @param {string} sectionId - The ID of the section the group is in * @param {string} groupId - The ID of the group * @param {string} removeFromPageId - ID of the page to remove the group from * @param {string} removeFromSectionId - ID of the section to remove the group from */ public async setGroupInPage( group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string, removeFromPageId: string, removeFromSectionId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group> { if (removeFromPageId == null) { throw new TypeError('removeFromPageId can not be null or undefined'); } if (removeFromSectionId == null) { throw new TypeError('removeFromSectionId can not be null or undefined'); } return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, pageId: pageId, sectionId: sectionId, groupId: groupId }; let queryValues: any = { removeFromPageId: removeFromPageId, removeFromSectionId: removeFromSectionId, }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "2617828b-e850-4375-a92a-04855704d4c3", routeValues, queryValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.Group>; res = await this.rest.replace<WorkItemTrackingProcessDefinitionsInterfaces.Group>(url, group, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Moves a group to a different section * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Group} group - The updated group * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} pageId - The ID of the page the group is in * @param {string} sectionId - The ID of the section the group is in * @param {string} groupId - The ID of the group * @param {string} removeFromSectionId - ID of the section to remove the group from */ public async setGroupInSection( group: WorkItemTrackingProcessDefinitionsInterfaces.Group, processId: string, witRefName: string, pageId: string, sectionId: string, groupId: string, removeFromSectionId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group> { if (removeFromSectionId == null) { throw new TypeError('removeFromSectionId can not be null or undefined'); } return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.Group>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, pageId: pageId, sectionId: sectionId, groupId: groupId }; let queryValues: any = { removeFromSectionId: removeFromSectionId, }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "2617828b-e850-4375-a92a-04855704d4c3", routeValues, queryValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.Group>; res = await this.rest.replace<WorkItemTrackingProcessDefinitionsInterfaces.Group>(url, group, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Gets the form layout * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ public async getFormLayout( processId: string, witRefName: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.FormLayout> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.FormLayout>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "3eacc80a-ddca-4404-857a-6331aac99063", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.FormLayout>; res = await this.rest.get<WorkItemTrackingProcessDefinitionsInterfaces.FormLayout>(url, options); let ret = this.formatResponse(res.result, WorkItemTrackingProcessDefinitionsInterfaces.TypeInfo.FormLayout, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Returns meta data of the picklist. * */ public async getListsMetadata( ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListMetadataModel[]> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListMetadataModel[]>(async (resolve, reject) => { let routeValues: any = { }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "b45cc931-98e3-44a1-b1cd-2e8e9c6dc1c6", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.PickListMetadataModel[]>; res = await this.rest.get<WorkItemTrackingProcessDefinitionsInterfaces.PickListMetadataModel[]>(url, options); let ret = this.formatResponse(res.result, null, true); resolve(ret); } catch (err) { reject(err); } }); } /** * Creates a picklist. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.PickListModel} picklist */ public async createList( picklist: WorkItemTrackingProcessDefinitionsInterfaces.PickListModel ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>(async (resolve, reject) => { let routeValues: any = { }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "0b6179e2-23ce-46b2-b094-2ffa5ee70286", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>; res = await this.rest.create<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>(url, picklist, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Removes a picklist. * * @param {string} listId - The ID of the list */ public async deleteList( listId: string ): Promise<void> { return new Promise<void>(async (resolve, reject) => { let routeValues: any = { listId: listId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "0b6179e2-23ce-46b2-b094-2ffa5ee70286", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<void>; res = await this.rest.del<void>(url, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Returns a picklist. * * @param {string} listId - The ID of the list */ public async getList( listId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>(async (resolve, reject) => { let routeValues: any = { listId: listId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "0b6179e2-23ce-46b2-b094-2ffa5ee70286", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>; res = await this.rest.get<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>(url, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Updates a list. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.PickListModel} picklist * @param {string} listId - The ID of the list */ public async updateList( picklist: WorkItemTrackingProcessDefinitionsInterfaces.PickListModel, listId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>(async (resolve, reject) => { let routeValues: any = { listId: listId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "0b6179e2-23ce-46b2-b094-2ffa5ee70286", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>; res = await this.rest.replace<WorkItemTrackingProcessDefinitionsInterfaces.PickListModel>(url, picklist, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Adds a page to the work item form * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Page} page - The page * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ public async addPage( page: WorkItemTrackingProcessDefinitionsInterfaces.Page, processId: string, witRefName: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Page> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.Page>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "1b4ac126-59b2-4f37-b4df-0a48ba807edb", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.Page>; res = await this.rest.create<WorkItemTrackingProcessDefinitionsInterfaces.Page>(url, page, options); let ret = this.formatResponse(res.result, WorkItemTrackingProcessDefinitionsInterfaces.TypeInfo.Page, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Updates a page on the work item form * * @param {WorkItemTrackingProcessDefinitionsInterfaces.Page} page - The page * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ public async editPage( page: WorkItemTrackingProcessDefinitionsInterfaces.Page, processId: string, witRefName: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.Page> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.Page>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "1b4ac126-59b2-4f37-b4df-0a48ba807edb", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.Page>; res = await this.rest.update<WorkItemTrackingProcessDefinitionsInterfaces.Page>(url, page, options); let ret = this.formatResponse(res.result, WorkItemTrackingProcessDefinitionsInterfaces.TypeInfo.Page, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Removes a page from the work item form * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} pageId - The ID of the page */ public async removePage( processId: string, witRefName: string, pageId: string ): Promise<void> { return new Promise<void>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, pageId: pageId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "1b4ac126-59b2-4f37-b4df-0a48ba807edb", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<void>; res = await this.rest.del<void>(url, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Creates a state definition in the work item type of the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateInputModel} stateModel * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ public async createStateDefinition( stateModel: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateInputModel, processId: string, witRefName: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "4303625d-08f4-4461-b14b-32c65bba5599", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; res = await this.rest.create<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>(url, stateModel, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Removes a state definition in the work item type of the process. * * @param {string} processId - ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} stateId - ID of the state */ public async deleteStateDefinition( processId: string, witRefName: string, stateId: string ): Promise<void> { return new Promise<void>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, stateId: stateId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "4303625d-08f4-4461-b14b-32c65bba5599", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<void>; res = await this.rest.del<void>(url, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Returns a state definition in the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} stateId - The ID of the state */ public async getStateDefinition( processId: string, witRefName: string, stateId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, stateId: stateId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "4303625d-08f4-4461-b14b-32c65bba5599", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; res = await this.rest.get<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>(url, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Returns a list of all state definitions in the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ public async getStateDefinitions( processId: string, witRefName: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel[]> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel[]>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "4303625d-08f4-4461-b14b-32c65bba5599", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel[]>; res = await this.rest.get<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel[]>(url, options); let ret = this.formatResponse(res.result, null, true); resolve(ret); } catch (err) { reject(err); } }); } /** * Hides a state definition in the work item type of the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.HideStateModel} hideStateModel * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} stateId - The ID of the state */ public async hideStateDefinition( hideStateModel: WorkItemTrackingProcessDefinitionsInterfaces.HideStateModel, processId: string, witRefName: string, stateId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, stateId: stateId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "4303625d-08f4-4461-b14b-32c65bba5599", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; res = await this.rest.replace<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>(url, hideStateModel, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Updates a given state definition in the work item type of the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateInputModel} stateModel * @param {string} processId - ID of the process * @param {string} witRefName - The reference name of the work item type * @param {string} stateId - ID of the state */ public async updateStateDefinition( stateModel: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateInputModel, processId: string, witRefName: string, stateId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName, stateId: stateId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "4303625d-08f4-4461-b14b-32c65bba5599", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>; res = await this.rest.update<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemStateResultModel>(url, stateModel, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Adds a behavior to the work item type of the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior} behavior * @param {string} processId - The ID of the process * @param {string} witRefNameForBehaviors - Work item type reference name for the behavior */ public async addBehaviorToWorkItemType( behavior: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior, processId: string, witRefNameForBehaviors: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefNameForBehaviors: witRefNameForBehaviors }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "921dfb88-ef57-4c69-94e5-dd7da2d7031d", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>; res = await this.rest.create<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>(url, behavior, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Returns a behavior for the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefNameForBehaviors - Work item type reference name for the behavior * @param {string} behaviorRefName - The reference name of the behavior */ public async getBehaviorForWorkItemType( processId: string, witRefNameForBehaviors: string, behaviorRefName: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefNameForBehaviors: witRefNameForBehaviors, behaviorRefName: behaviorRefName }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "921dfb88-ef57-4c69-94e5-dd7da2d7031d", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>; res = await this.rest.get<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>(url, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Returns a list of all behaviors for the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefNameForBehaviors - Work item type reference name for the behavior */ public async getBehaviorsForWorkItemType( processId: string, witRefNameForBehaviors: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior[]> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior[]>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefNameForBehaviors: witRefNameForBehaviors }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "921dfb88-ef57-4c69-94e5-dd7da2d7031d", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior[]>; res = await this.rest.get<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior[]>(url, options); let ret = this.formatResponse(res.result, null, true); resolve(ret); } catch (err) { reject(err); } }); } /** * Removes a behavior for the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefNameForBehaviors - Work item type reference name for the behavior * @param {string} behaviorRefName - The reference name of the behavior */ public async removeBehaviorFromWorkItemType( processId: string, witRefNameForBehaviors: string, behaviorRefName: string ): Promise<void> { return new Promise<void>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefNameForBehaviors: witRefNameForBehaviors, behaviorRefName: behaviorRefName }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "921dfb88-ef57-4c69-94e5-dd7da2d7031d", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<void>; res = await this.rest.del<void>(url, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Updates default work item type for the behavior of the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior} behavior * @param {string} processId - The ID of the process * @param {string} witRefNameForBehaviors - Work item type reference name for the behavior */ public async updateBehaviorToWorkItemType( behavior: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior, processId: string, witRefNameForBehaviors: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefNameForBehaviors: witRefNameForBehaviors }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "921dfb88-ef57-4c69-94e5-dd7da2d7031d", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>; res = await this.rest.update<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeBehavior>(url, behavior, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Creates a work item type in the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel} workItemType * @param {string} processId - The ID of the process */ public async createWorkItemType( workItemType: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel, processId: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>(async (resolve, reject) => { let routeValues: any = { processId: processId }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "1ce0acad-4638-49c3-969c-04aa65ba6bea", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>; res = await this.rest.create<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>(url, workItemType, options); let ret = this.formatResponse(res.result, WorkItemTrackingProcessDefinitionsInterfaces.TypeInfo.WorkItemTypeModel, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Removes a work itewm type in the process. * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ public async deleteWorkItemType( processId: string, witRefName: string ): Promise<void> { return new Promise<void>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "1ce0acad-4638-49c3-969c-04aa65ba6bea", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<void>; res = await this.rest.del<void>(url, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Returns a work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type * @param {WorkItemTrackingProcessDefinitionsInterfaces.GetWorkItemTypeExpand} expand */ public async getWorkItemType( processId: string, witRefName: string, expand?: WorkItemTrackingProcessDefinitionsInterfaces.GetWorkItemTypeExpand ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName }; let queryValues: any = { '$expand': expand, }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "1ce0acad-4638-49c3-969c-04aa65ba6bea", routeValues, queryValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>; res = await this.rest.get<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>(url, options); let ret = this.formatResponse(res.result, WorkItemTrackingProcessDefinitionsInterfaces.TypeInfo.WorkItemTypeModel, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Returns a list of all work item types in the process. * * @param {string} processId - The ID of the process * @param {WorkItemTrackingProcessDefinitionsInterfaces.GetWorkItemTypeExpand} expand */ public async getWorkItemTypes( processId: string, expand?: WorkItemTrackingProcessDefinitionsInterfaces.GetWorkItemTypeExpand ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel[]> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel[]>(async (resolve, reject) => { let routeValues: any = { processId: processId }; let queryValues: any = { '$expand': expand, }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "1ce0acad-4638-49c3-969c-04aa65ba6bea", routeValues, queryValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel[]>; res = await this.rest.get<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel[]>(url, options); let ret = this.formatResponse(res.result, WorkItemTrackingProcessDefinitionsInterfaces.TypeInfo.WorkItemTypeModel, true); resolve(ret); } catch (err) { reject(err); } }); } /** * Updates a work item type of the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeUpdateModel} workItemTypeUpdate * @param {string} processId - The ID of the process * @param {string} witRefName - The reference name of the work item type */ public async updateWorkItemType( workItemTypeUpdate: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeUpdateModel, processId: string, witRefName: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefName: witRefName }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "1ce0acad-4638-49c3-969c-04aa65ba6bea", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>; res = await this.rest.update<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeModel>(url, workItemTypeUpdate, options); let ret = this.formatResponse(res.result, WorkItemTrackingProcessDefinitionsInterfaces.TypeInfo.WorkItemTypeModel, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Adds a field to the work item type in the process. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2} field * @param {string} processId - The ID of the process * @param {string} witRefNameForFields - Work item type reference name for the field */ public async addFieldToWorkItemType( field: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2, processId: string, witRefNameForFields: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefNameForFields: witRefNameForFields }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "976713b4-a62e-499e-94dc-eeb869ea9126", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>; res = await this.rest.create<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>(url, field, options); let ret = this.formatResponse(res.result, WorkItemTrackingProcessDefinitionsInterfaces.TypeInfo.WorkItemTypeFieldModel2, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Returns a single field in the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefNameForFields - Work item type reference name for fields * @param {string} fieldRefName - The reference name of the field */ public async getWorkItemTypeField( processId: string, witRefNameForFields: string, fieldRefName: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefNameForFields: witRefNameForFields, fieldRefName: fieldRefName }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "976713b4-a62e-499e-94dc-eeb869ea9126", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>; res = await this.rest.get<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>(url, options); let ret = this.formatResponse(res.result, WorkItemTrackingProcessDefinitionsInterfaces.TypeInfo.WorkItemTypeFieldModel2, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Returns a list of all fields in the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefNameForFields - Work item type reference name for fields */ public async getWorkItemTypeFields( processId: string, witRefNameForFields: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2[]> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2[]>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefNameForFields: witRefNameForFields }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "976713b4-a62e-499e-94dc-eeb869ea9126", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2[]>; res = await this.rest.get<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2[]>(url, options); let ret = this.formatResponse(res.result, WorkItemTrackingProcessDefinitionsInterfaces.TypeInfo.WorkItemTypeFieldModel2, true); resolve(ret); } catch (err) { reject(err); } }); } /** * Removes a field in the work item type of the process. * * @param {string} processId - The ID of the process * @param {string} witRefNameForFields - Work item type reference name for fields * @param {string} fieldRefName - The reference name of the field */ public async removeFieldFromWorkItemType( processId: string, witRefNameForFields: string, fieldRefName: string ): Promise<void> { return new Promise<void>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefNameForFields: witRefNameForFields, fieldRefName: fieldRefName }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "976713b4-a62e-499e-94dc-eeb869ea9126", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<void>; res = await this.rest.del<void>(url, options); let ret = this.formatResponse(res.result, null, false); resolve(ret); } catch (err) { reject(err); } }); } /** * Updates a single field in the scope of the given process and work item type. * * @param {WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2} field - The model with which to update the field * @param {string} processId - The ID of the process * @param {string} witRefNameForFields - Work item type reference name for fields */ public async updateWorkItemTypeField( field: WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2, processId: string, witRefNameForFields: string ): Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2> { return new Promise<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>(async (resolve, reject) => { let routeValues: any = { processId: processId, witRefNameForFields: witRefNameForFields }; try { let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData( "6.1-preview.1", "processDefinitions", "976713b4-a62e-499e-94dc-eeb869ea9126", routeValues); let url: string = verData.requestUrl!; let options: restm.IRequestOptions = this.createRequestOptions('application/json', verData.apiVersion); let res: restm.IRestResponse<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>; res = await this.rest.update<WorkItemTrackingProcessDefinitionsInterfaces.WorkItemTypeFieldModel2>(url, field, options); let ret = this.formatResponse(res.result, WorkItemTrackingProcessDefinitionsInterfaces.TypeInfo.WorkItemTypeFieldModel2, false); resolve(ret); } catch (err) { reject(err); } }); } }
the_stack
import { Component } from '@angular/core'; import { HMSAnalytics, HAEventType, HAParamType, LogLevelType, ReportPolicyType } from '@hmscore/ionic-native-hms-analytics/ngx'; @Component({ selector: 'app-home', templateUrl: 'analytics.page.html', styleUrls: ['analytics.page.scss'], }) export class HomePage { boolSetAnalyticsEnabled: string = ''; userId: string = ''; name: string = ''; value: string = ''; deleteName: string = ''; profile: string = ''; milliSecondsForActivitySessions: number; milliSecondsForSessionDuration: number; selectedLevel: string = ''; startPageName: string = ''; startPageClassOverride: string = ''; endPageName: string = ''; reportPolicyType: string = ''; restrictionIsEnabled: string = ''; constructor(private hmsAnalytics: HMSAnalytics) {} /** * Specifies whether to enable event collection. * If the function is disabled, no data is recorded. */ setAnalyticsEnabled() { if (this.boolSetAnalyticsEnabled === '') { alert("Please choose required field"); } else { let enabled = (this.boolSetAnalyticsEnabled === "true"); this.hmsAnalytics.setAnalyticsEnabled(enabled) .then(() => { alert("setAnalyticsEnabled :: Success"); }) .catch((error) => alert("setAnalyticsEnabled :: Error! " + JSON.stringify(error,null,1))); } } /** * Set a user ID. * @important: When the setUserId API is called, if the old userId is not empty and is different from the new userId, a new session is generated. * If you do not want to use setUserId to identify a user (for example, when a user signs out), set userId to **null**. */ setUserId() { if (this.userId === '') { alert("Please fill out requred field"); } else { this.hmsAnalytics.setUserId(this.userId) .then(() => { alert("setUserId :: Success"); }) .catch((error) => alert("setUserId :: Error! " + JSON.stringify(error,null,1))); } } /** * User attribute values remain unchanged throughout the app's lifecycle and session. * A maximum of 25 user attribute names are supported. * If an attribute name is duplicate with an existing one, the attribute names needs to be changed. */ setUserProfile() { if (this.name === '' || this.value === '') { alert("Please fill out requred field"); } else { this.hmsAnalytics.setUserProfile(this.name, this.value) .then(() => { alert("setUserProfile :: Success"); }) .catch((error) => alert("setUserProfile :: Error! " + JSON.stringify(error,null,1))); } } /** * User attribute name */ deleteUserProfile() { if (this.deleteName === '') { alert("Please fill out requred field"); } else { this.hmsAnalytics.deleteUserProfile(this.deleteName) .then(() => { alert("deleteUserProfile :: Success"); }) .catch((error) => alert("deleteUserProfile :: Error! " + JSON.stringify(error,null,1))); } } /** * Sets the push token, which is obtained using the Push Kit. * @note This method is only to support on Android Platform. */ setPushToken() { const pushToken = "AFcSAHhhnxdrMCYBxth2QOG9IgY2VydAM61DTThqNux3KBC_hgzQQTadfgtDv"; this.hmsAnalytics.setPushToken(pushToken) .then(() => { alert("setPushToken :: Success"); }) .catch((error) => alert("setPushToken :: Error! " + JSON.stringify(error,null,1))); } /** * Sets the minimum interval for starting a new session. */ setMinActivitySessions() { if (this.milliSecondsForActivitySessions === undefined) { alert("Please fill out requred field"); } else { this.hmsAnalytics.setMinActivitySessions(this.milliSecondsForActivitySessions) .then(() => { alert("setMinActivitySessions :: Success"); }) .catch((error) => alert("setMinActivitySessions :: Error! " + JSON.stringify(error,null,1))); } } /** * Sets the session timeout interval. */ setSessionDuration() { if (this.milliSecondsForSessionDuration === undefined) { alert("Please fill out requred field"); } else { this.hmsAnalytics.setSessionDuration(this.milliSecondsForSessionDuration) .then(() => { alert("setSessionDuration :: Success"); }) .catch((error) => alert("setSessionDuration :: Error! " + JSON.stringify(error,null,1))); } } /** * Report custom events. */ onEvent() { let name = 'event_name'; let params = { "putInt": 123, "putDouble": 12.056565665612346789, "putLong": 2121455345345343, "putString": "string", "putBoolean1": true, "putBoolean2": false, "items": [{ "itemsPutInt0": 1523, "itemsPutDouble0": 12.0565600002346789, "itemsPutLong0": 2333333345345343, "itemsPutString0": "string0", "itemsPutBoolean0": true },{ "itemsPutInt1": 321, "itemsPutDouble1": 12.056565665612222222, "itemsPutLong1": 1111451115345343, "itemsPutString1": "string1", "itemsPutBoolean1": false }] }; this.hmsAnalytics.onEvent(name, params) .then(() => { alert("onEvent :: Success"); }) .catch((error) => alert("onEvent :: Error! " + JSON.stringify(error,null,1))); } /** * Report predefined events. */ onPredefinedEvent() { let name = HAEventType.SUBMITSCORE; let params = {}; params[HAParamType.SCORE] = 12; params[HAParamType.CATEGORY] = "SPORT"; this.hmsAnalytics.onEvent(name, params) .then(() => { alert("onPredefinedEvent :: Success"); }) .catch((error) => alert("onPredefinedEvent :: Error! " + JSON.stringify(error,null,1))); } /** * Delete all collected data in the local cache, including the cached data that fails to be sent. */ clearCachedData() { this.hmsAnalytics.clearCachedData() .then(() => { alert("clearCachedData :: Success"); }) .catch((error) => alert("clearCachedData :: Error! " + JSON.stringify(error,null,1))); } /** * Obtains the app instance ID from AppGallery Connect. */ getAAID() { this.hmsAnalytics.getAAID() .then((aaid) => { alert("getAAID :: Success -> aaid: " + JSON.stringify(aaid,null,1)); }) .catch((error) => alert("getAAID :: Error! " + JSON.stringify(error,null,1))); } /** * Enables AB Testing. Predefined or custom user attributes are supported. */ getUserProfiles() { if (this.profile === '') { alert("Please fill out requred field"); } else { let predefined = (this.profile === "true"); this.hmsAnalytics.getUserProfiles(predefined) .then((userProfiles) => { alert("getUserProfiles :: Success -> userProfiles: " + JSON.stringify(userProfiles,null,1)); }) .catch((error) => alert("getUserProfiles :: Error! " + JSON.stringify(error,null,1))); } } /** * Defines a custom page entry event. * @note This method is only to support on Android Platform. */ pageStart() { if (this.startPageName === '' || this.startPageClassOverride === '') { alert("Please fill out requred field"); } else { this.hmsAnalytics.pageStart(this.startPageName, this.startPageClassOverride) .then(() => { alert("pageStart :: Success"); }) .catch((error) => alert("pageStart :: Error! " + JSON.stringify(error,null,1))); } } /** * Defines a custom page exit event. * @note This method is only to support on Android Platform. */ pageEnd() { if (this.endPageName === '') { alert("Please fill out requred field"); } else { this.hmsAnalytics.pageEnd(this.endPageName) .then(() => { alert("pageEnd :: Success"); }) .catch((error) => alert("pageEnd :: Error! " + JSON.stringify(error,null,1))); } } /** * Enables the debug log function and sets the minimum log level. * @note This method is only to support on Android Platform. */ enableLog() { if (this.selectedLevel === '') { alert("Please choose required field"); } else { let logLevelType; switch(this.selectedLevel) { case "INFO": logLevelType = LogLevelType.INFO; break; case "WARN": logLevelType = LogLevelType.WARN; break; case "ERROR": logLevelType = LogLevelType.ERROR; break; case "DEBUG": default: logLevelType = LogLevelType.DEBUG; } this.hmsAnalytics.enableLog(logLevelType) .then(() => { alert("enableLog :: Success"); }) .catch((error) => alert("enableLog :: Error! " + JSON.stringify(error,null,1))); } } /** * Sets data reporting policies. */ setReportPolicies() { const reportPolicies = { onScheduledTimePolicy: 300, onAppLaunchPolicy: true, onMoveBackgroundPolicy: true, onCacheThresholdPolicy: 350, }; this.hmsAnalytics.setReportPolicies(reportPolicies) .then(() => { alert("setReportPolicies :: Success"); }) .catch((error) => alert("setReportPolicies :: Error! " + JSON.stringify(error,null,1))); } /** * Obtains the threshold for event reporting. */ getReportPolicyThreshold() { if (this.reportPolicyType === '') { alert("Please choose required field"); } else { let reportPolicyType; switch(this.reportPolicyType) { case "ON_SCHEDULED_TIME_POLICY": reportPolicyType = ReportPolicyType.ON_SCHEDULED_TIME_POLICY; break; case "ON_APP_LAUNCH_POLICY": reportPolicyType = ReportPolicyType.ON_APP_LAUNCH_POLICY; break; case "ON_MOVE_BACKGROUND_POLICY": reportPolicyType = ReportPolicyType.ON_MOVE_BACKGROUND_POLICY; break; case "ON_CACHE_THRESHOLD_POLICY": reportPolicyType = ReportPolicyType.ON_CACHE_THRESHOLD_POLICY; break; default: reportPolicyType = ReportPolicyType.ON_SCHEDULED_TIME_POLICY; } this.hmsAnalytics.getReportPolicyThreshold(reportPolicyType) .then((result) => { alert("getReportPolicyThreshold :: Success "+reportPolicyType+" ->Threshold:" + JSON.stringify(result,null,1)); }) .catch((error) => alert("getReportPolicyThreshold :: Error! " + JSON.stringify(error,null,1))); } } /** * Specifies whether to enable restriction of HUAWEI Analytics. */ setRestrictionEnabled() { if (this.restrictionIsEnabled === '') { alert("Please fill out requred field"); } else { let isEnabled = (this.restrictionIsEnabled === "true"); this.hmsAnalytics.setRestrictionEnabled(isEnabled) .then(() => { alert("setRestrictionEnabled :: Success"); }) .catch((error) => alert("setRestrictionEnabled :: Error! " + JSON.stringify(error,null,1))); } } /** * Obtains the restriction status of HUAWEI Analytics. */ isRestrictionEnabled() { this.hmsAnalytics.isRestrictionEnabled() .then((result) => { alert("isRestrictionEnabled :: Success -> isRestrictionEnabled: " + JSON.stringify(result,null,1)); }) .catch((error) => alert("isRestrictionEnabled :: Error! " + JSON.stringify(error,null,1))); } /** * Adds default event parameters. * These parameters will be added to all events except the automatically collected events. */ addDefaultEventParams() { let params = {}; params["DefaultEventKey0"] = false; params["DefaultEventKey1"] = 1; params["DefaultEventKey2"] = "two"; this.hmsAnalytics.addDefaultEventParams(params) .then(() => { alert("addDefaultEventParams :: Success"); }) .catch((error) => alert("addDefaultEventParams :: Error! " + JSON.stringify(error,null,1))); } /** * HAParamType types for provides the IDs of all predefined parameters, * including the IDs of predefined parameters and user attributes. */ HAParamType() { alert(JSON.stringify(HAParamType,null,1)); } /** * HAEventType types for provides the IDs of all predefined events. */ HAEventType() { alert(JSON.stringify(HAEventType,null,1)); } }
the_stack
import {Flamechart} from '../lib/flamechart' import {RectangleBatch, RectangleBatchRenderer} from './rectangle-batch-renderer' import {Vec2, Rect, AffineTransform} from '../lib/math' import {Color} from '../lib/color' import {KeyedSet} from '../lib/utils' import {RowAtlas} from './row-atlas' import {Graphics} from './graphics' import {FlamechartColorPassRenderer} from './flamechart-color-pass-renderer' import {renderInto} from './utils' const MAX_BATCH_SIZE = 10000 interface RangeTreeNode { getBounds(): Rect getRectCount(): number getChildren(): RangeTreeNode[] forEachLeafNodeWithinBounds(configSpaceBounds: Rect, cb: (leaf: RangeTreeLeafNode) => void): void } class RangeTreeLeafNode implements RangeTreeNode { private children: RangeTreeNode[] = [] constructor( private batch: RectangleBatch, private bounds: Rect, private numPrecedingRectanglesInRow: number, ) {} getBatch() { return this.batch } getBounds() { return this.bounds } getRectCount() { return this.batch.getRectCount() } getChildren() { return this.children } getParity() { return this.numPrecedingRectanglesInRow % 2 } forEachLeafNodeWithinBounds(configSpaceBounds: Rect, cb: (leaf: RangeTreeLeafNode) => void) { if (!this.bounds.hasIntersectionWith(configSpaceBounds)) return cb(this) } } class RangeTreeInteriorNode implements RangeTreeNode { private rectCount: number = 0 private bounds: Rect constructor(private children: RangeTreeNode[]) { if (children.length === 0) { throw new Error('Empty interior node') } let minLeft = Infinity let maxRight = -Infinity let minTop = Infinity let maxBottom = -Infinity for (let child of children) { this.rectCount += child.getRectCount() const bounds = child.getBounds() minLeft = Math.min(minLeft, bounds.left()) maxRight = Math.max(maxRight, bounds.right()) minTop = Math.min(minTop, bounds.top()) maxBottom = Math.max(maxBottom, bounds.bottom()) } this.bounds = new Rect( new Vec2(minLeft, minTop), new Vec2(maxRight - minLeft, maxBottom - minTop), ) } getBounds() { return this.bounds } getRectCount() { return this.rectCount } getChildren() { return this.children } forEachLeafNodeWithinBounds(configSpaceBounds: Rect, cb: (leaf: RangeTreeLeafNode) => void) { if (!this.bounds.hasIntersectionWith(configSpaceBounds)) return for (let child of this.children) { child.forEachLeafNodeWithinBounds(configSpaceBounds, cb) } } } export interface FlamechartRendererProps { configSpaceSrcRect: Rect physicalSpaceDstRect: Rect renderOutlines: boolean } interface FlamechartRowAtlasKeyInfo { stackDepth: number zoomLevel: number index: number } export class FlamechartRowAtlasKey { readonly stackDepth: number readonly zoomLevel: number readonly index: number get key() { return `${this.stackDepth}_${this.index}_${this.zoomLevel}` } private constructor(options: FlamechartRowAtlasKeyInfo) { this.stackDepth = options.stackDepth this.zoomLevel = options.zoomLevel this.index = options.index } static getOrInsert(set: KeyedSet<FlamechartRowAtlasKey>, info: FlamechartRowAtlasKeyInfo) { return set.getOrInsert(new FlamechartRowAtlasKey(info)) } } export interface FlamechartRendererOptions { inverted: boolean } export class FlamechartRenderer { private layers: RangeTreeNode[] = [] constructor( private gl: Graphics.Context, private rowAtlas: RowAtlas<FlamechartRowAtlasKey>, private flamechart: Flamechart, private rectangleBatchRenderer: RectangleBatchRenderer, private colorPassRenderer: FlamechartColorPassRenderer, private options: FlamechartRendererOptions = {inverted: false}, ) { const nLayers = flamechart.getLayers().length for (let stackDepth = 0; stackDepth < nLayers; stackDepth++) { const leafNodes: RangeTreeLeafNode[] = [] const y = options.inverted ? nLayers - 1 - stackDepth : stackDepth let minLeft = Infinity let maxRight = -Infinity let batch = new RectangleBatch(this.gl) let rectCount = 0 const layer = flamechart.getLayers()[stackDepth] for (let i = 0; i < layer.length; i++) { const frame = layer[i] if (batch.getRectCount() >= MAX_BATCH_SIZE) { leafNodes.push( new RangeTreeLeafNode( batch, new Rect(new Vec2(minLeft, y), new Vec2(maxRight - minLeft, 1)), rectCount, ), ) minLeft = Infinity maxRight = -Infinity batch = new RectangleBatch(this.gl) } const configSpaceBounds = new Rect( new Vec2(frame.start, y), new Vec2(frame.end - frame.start, 1), ) minLeft = Math.min(minLeft, configSpaceBounds.left()) maxRight = Math.max(maxRight, configSpaceBounds.right()) // We'll use the red channel to indicate the index to allow // us to separate adjacent rectangles within a row from one another, // the green channel to indicate the row, // and the blue channel to indicate the color bucket to render. // We add one to each so we have zero reserved for the background color. const color = new Color( (1 + (i % 255)) / 256, (1 + (stackDepth % 255)) / 256, (1 + this.flamechart.getColorBucketForFrame(frame.node.frame)) / 256, ) batch.addRect(configSpaceBounds, color) rectCount++ } if (batch.getRectCount() > 0) { leafNodes.push( new RangeTreeLeafNode( batch, new Rect(new Vec2(minLeft, y), new Vec2(maxRight - minLeft, 1)), rectCount, ), ) } // TODO(jlfwong): Making this into a binary tree // range than a tree of always-height-two might make this run faster this.layers.push(new RangeTreeInteriorNode(leafNodes)) } } private rectInfoTexture: Graphics.Texture | null = null getRectInfoTexture(width: number, height: number): Graphics.Texture { if (this.rectInfoTexture) { const texture = this.rectInfoTexture if (texture.width != width || texture.height != height) { texture.resize(width, height) } } else { this.rectInfoTexture = this.gl.createTexture( Graphics.TextureFormat.NEAREST_CLAMP, width, height, ) } return this.rectInfoTexture } private rectInfoRenderTarget: Graphics.RenderTarget | null = null getRectInfoRenderTarget(width: number, height: number): Graphics.RenderTarget { const texture = this.getRectInfoTexture(width, height) if (this.rectInfoRenderTarget) { if (this.rectInfoRenderTarget.texture != texture) { this.rectInfoRenderTarget.texture.free() this.rectInfoRenderTarget.setColor(texture) } } if (!this.rectInfoRenderTarget) { this.rectInfoRenderTarget = this.gl.createRenderTarget(texture) } return this.rectInfoRenderTarget } free() { if (this.rectInfoRenderTarget) { this.rectInfoRenderTarget.free() } if (this.rectInfoTexture) { this.rectInfoTexture.free() } } private atlasKeys = new KeyedSet<FlamechartRowAtlasKey>() configSpaceBoundsForKey(key: FlamechartRowAtlasKey): Rect { const {stackDepth, zoomLevel, index} = key const configSpaceContentWidth = this.flamechart.getTotalWeight() const width = configSpaceContentWidth / Math.pow(2, zoomLevel) const nLayers = this.flamechart.getLayers().length const y = this.options.inverted ? nLayers - 1 - stackDepth : stackDepth return new Rect(new Vec2(width * index, y), new Vec2(width, 1)) } render(props: FlamechartRendererProps) { const {configSpaceSrcRect, physicalSpaceDstRect} = props const atlasKeysToRender: FlamechartRowAtlasKey[] = [] // We want to render the lowest resolution we can while still guaranteeing that the // atlas line is higher resolution than its corresponding destination rectangle on // the screen. const configToPhysical = AffineTransform.betweenRects(configSpaceSrcRect, physicalSpaceDstRect) if (configSpaceSrcRect.isEmpty()) { // Prevent an infinite loop return } let zoomLevel = 0 while (true) { const key = FlamechartRowAtlasKey.getOrInsert(this.atlasKeys, { stackDepth: 0, zoomLevel, index: 0, }) const configSpaceBounds = this.configSpaceBoundsForKey(key) const physicalBounds = configToPhysical.transformRect(configSpaceBounds) if (physicalBounds.width() < this.rowAtlas.getResolution()) { break } zoomLevel++ } const top = Math.max(0, Math.floor(configSpaceSrcRect.top())) const bottom = Math.min(this.layers.length, Math.ceil(configSpaceSrcRect.bottom())) const configSpaceContentWidth = this.flamechart.getTotalWeight() const numAtlasEntriesPerLayer = Math.pow(2, zoomLevel) const left = Math.floor( (numAtlasEntriesPerLayer * configSpaceSrcRect.left()) / configSpaceContentWidth, ) const right = Math.ceil( (numAtlasEntriesPerLayer * configSpaceSrcRect.right()) / configSpaceContentWidth, ) const nLayers = this.flamechart.getLayers().length for (let y = top; y < bottom; y++) { for (let index = left; index <= right; index++) { const stackDepth = this.options.inverted ? nLayers - 1 - y : y const key = FlamechartRowAtlasKey.getOrInsert(this.atlasKeys, { stackDepth, zoomLevel, index, }) const configSpaceBounds = this.configSpaceBoundsForKey(key) if (!configSpaceBounds.hasIntersectionWith(configSpaceSrcRect)) continue atlasKeysToRender.push(key) } } // TODO(jlfwong): When I switched the GL backend from regl to the port from // evanw/sky, rendering uncached even for massive documents seemed fast // enough. It's possible that the row cache is now unnecessary, but I'll // leave it around for now since it's not causing issues. const cacheCapacity = this.rowAtlas.getCapacity() const keysToRenderCached = atlasKeysToRender.slice(0, cacheCapacity) const keysToRenderUncached = atlasKeysToRender.slice(cacheCapacity) // Fill the cache this.rowAtlas.writeToAtlasIfNeeded(keysToRenderCached, (textureDstRect, key) => { const configSpaceBounds = this.configSpaceBoundsForKey(key) this.layers[key.stackDepth].forEachLeafNodeWithinBounds(configSpaceBounds, leaf => { this.rectangleBatchRenderer.render({ batch: leaf.getBatch(), configSpaceSrcRect: configSpaceBounds, physicalSpaceDstRect: textureDstRect, }) }) }) const renderTarget = this.getRectInfoRenderTarget( physicalSpaceDstRect.width(), physicalSpaceDstRect.height(), ) renderInto(this.gl, renderTarget, () => { this.gl.clear(new Graphics.Color(0, 0, 0, 0)) const viewportRect = new Rect( Vec2.zero, new Vec2(this.gl.viewport.width, this.gl.viewport.height), ) const configToViewport = AffineTransform.betweenRects(configSpaceSrcRect, viewportRect) // Render from the cache for (let key of keysToRenderCached) { const configSpaceSrcRect = this.configSpaceBoundsForKey(key) this.rowAtlas.renderViaAtlas(key, configToViewport.transformRect(configSpaceSrcRect)) } // Render entries that didn't make it into the cache for (let key of keysToRenderUncached) { const configSpaceBounds = this.configSpaceBoundsForKey(key) const physicalBounds = configToViewport.transformRect(configSpaceBounds) this.layers[key.stackDepth].forEachLeafNodeWithinBounds(configSpaceBounds, leaf => { this.rectangleBatchRenderer.render({ batch: leaf.getBatch(), configSpaceSrcRect: configSpaceBounds, physicalSpaceDstRect: physicalBounds, }) }) } }) const rectInfoTexture = this.getRectInfoTexture( physicalSpaceDstRect.width(), physicalSpaceDstRect.height(), ) this.colorPassRenderer.render({ rectInfoTexture, srcRect: new Rect(Vec2.zero, new Vec2(rectInfoTexture.width, rectInfoTexture.height)), dstRect: physicalSpaceDstRect, renderOutlines: props.renderOutlines, }) } }
the_stack
type StateType = string; import { reduce as reduce_to_639 } from 'reduce-to-639-1'; import { JssmGenericState, JssmGenericConfig, JssmTransition, JssmTransitionList, // JssmTransitionRule, JssmMachineInternalState, JssmParseTree, JssmStateDeclaration, JssmStateDeclarationRule, JssmCompileSe, JssmCompileSeStart, JssmCompileRule, JssmArrow, JssmArrowDirection, JssmArrowKind, JssmLayout, FslDirection, FslTheme } from './jssm_types'; import { seq, weighted_rand_select, weighted_sample_select, histograph, weighted_histo_key, array_box_if_string } from './jssm_util'; import { parse } from './jssm-dot'; // TODO FIXME WHARGARBL this could be post-typed import { version } from './version'; // replaced from package.js in build // TODO FIXME currently broken /* eslint-disable complexity */ function arrow_direction(arrow: JssmArrow): JssmArrowDirection { switch ( String(arrow) ) { case '->' : case '→' : case '=>' : case '⇒' : case '~>' : case '↛' : return 'right'; case '<-' : case '←' : case '<=' : case '⇐' : case '<~' : case '↚' : return 'left'; case '<->' : case '↔' : case '<-=>' : case '←⇒' : case '←=>' : case '<-⇒' : case '<-~>' : case '←↛' : case '←~>' : case '<-↛' : case '<=>' : case '⇔' : case '<=->' : case '⇐→' : case '⇐->' : case '<=→' : case '<=~>' : case '⇐↛' : case '⇐~>' : case '<=↛' : case '<~>' : case '↮' : case '<~->' : case '↚→' : case '↚->' : case '<~→' : case '<~=>' : case '↚⇒' : case '↚=>' : case '<~⇒' : return 'both'; default: throw new Error(`arrow_direction: unknown arrow type ${arrow}`); } } /* eslint-enable complexity */ /* eslint-disable complexity */ function arrow_left_kind(arrow: JssmArrow): JssmArrowKind { switch ( String(arrow) ) { case '->' : case '→' : case '=>' : case '⇒' : case '~>' : case '↛' : return 'none'; case '<-': case '←' : case '<->': case '↔' : case '<-=>': case '←⇒' : case '<-~>': case '←↛' : return 'legal'; case '<=': case '⇐' : case '<=>': case '⇔' : case '<=->': case '⇐→' : case '<=~>': case '⇐↛' : return 'main'; case '<~': case '↚' : case '<~>': case '↮' : case '<~->': case '↚→' : case '<~=>': case '↚⇒' : return 'forced'; default: throw new Error(`arrow_direction: unknown arrow type ${arrow}`); } } /* eslint-enable complexity */ /* eslint-disable complexity */ function arrow_right_kind(arrow: JssmArrow): JssmArrowKind { switch ( String(arrow) ) { case '<-' : case '←' : case '<=' : case '⇐' : case '<~' : case '↚' : return 'none'; case '->' : case '→' : case '<->': case '↔' : case '<=->': case '⇐→' : case '<~->': case '↚→' : return 'legal'; case '=>' : case '⇒' : case '<=>': case '⇔' : case '<-=>': case '←⇒' : case '<~=>': case '↚⇒' : return 'main'; case '~>' : case '↛' : case '<~>': case '↮' : case '<-~>': case '←↛' : case '<=~>': case '⇐↛' : return 'forced'; default: throw new Error(`arrow_direction: unknown arrow type ${arrow}`); } } /* eslint-enable complexity */ function makeTransition<mDT>( this_se : JssmCompileSe, from : string, to : string, isRight : boolean, _wasList? : Array<string>, _wasIndex? : number ) : JssmTransition<mDT> { const kind : JssmArrowKind = isRight? arrow_right_kind(this_se.kind) : arrow_left_kind(this_se.kind), edge : JssmTransition<mDT> = { from, to, kind, forced_only : kind === 'forced', main_path : kind === 'main' }; // if ((wasList !== undefined) && (wasIndex === undefined)) { throw new TypeError("Must have an index if transition was in a list"); } // if ((wasIndex !== undefined) && (wasList === undefined)) { throw new TypeError("Must be in a list if transition has an index"); } /* if (typeof edge.to === 'object') { if (edge.to.key === 'cycle') { if (wasList === undefined) { throw "Must have a waslist if a to is type cycle"; } const nextIndex = wrapBy(wasIndex, edge.to.value, wasList.length); edge.to = wasList[nextIndex]; } } */ const action : string = isRight? 'r_action' : 'l_action', probability : string = isRight? 'r_probability' : 'l_probability'; if (this_se[action]) { edge.action = this_se[action]; } if (this_se[probability]) { edge.probability = this_se[probability]; } return edge; } function wrap_parse(input: string, options?: Object) { return parse(input, options || {}); } function compile_rule_transition_step<mDT>( acc : Array< JssmTransition<mDT> >, from : string, to : string, this_se : JssmCompileSe, next_se : JssmCompileSe ) : Array< JssmTransition<mDT> > { // todo flow describe the parser representation of a transition step extension const edges : Array< JssmTransition<mDT> > = []; const uFrom : Array< string > = (Array.isArray(from)? from : [from]), uTo : Array< string > = (Array.isArray(to)? to : [to] ); uFrom.map( (f: string) => { uTo.map( (t: string) => { const right: JssmTransition<mDT> = makeTransition(this_se, f, t, true); if (right.kind !== 'none') { edges.push(right); } const left: JssmTransition<mDT> = makeTransition(this_se, t, f, false); if (left.kind !== 'none') { edges.push(left); } }); }); const new_acc: Array< JssmTransition<mDT> > = acc.concat(edges); if (next_se) { return compile_rule_transition_step(new_acc, to, next_se.to, next_se, next_se.se); } else { return new_acc; } } function compile_rule_handle_transition(rule: JssmCompileSeStart<StateType>): any { // TODO FIXME no any // todo flow describe the parser representation of a transition return compile_rule_transition_step([], rule.from, rule.se.to, rule.se, rule.se.se); } function compile_rule_handler(rule: JssmCompileSeStart<StateType>): JssmCompileRule { // todo flow describe the output of the parser if (rule.key === 'transition') { return { agg_as: 'transition', val: compile_rule_handle_transition(rule) }; } if (rule.key === 'machine_language') { return { agg_as: 'machine_language', val: reduce_to_639(rule.value) }; } if (rule.key === 'state_declaration') { if (!rule.name) { throw new Error('State declarations must have a name'); } return { agg_as: 'state_declaration', val: { state: rule.name, declarations: rule.value } }; } if (['arrange_declaration', 'arrange_start_declaration', 'arrange_end_declaration'].includes(rule.key)) { return { agg_as: rule.key, val: [rule.value] }; } const tautologies : Array<string> = [ 'graph_layout', 'start_states', 'end_states', 'machine_name', 'machine_version', 'machine_comment', 'machine_author', 'machine_contributor', 'machine_definition', 'machine_reference', 'machine_license', 'fsl_version', 'state_config', 'theme', 'flow', 'dot_preamble' ]; if (tautologies.includes(rule.key)) { return { agg_as: rule.key, val: rule.value }; } throw new Error(`compile_rule_handler: Unknown rule: ${JSON.stringify(rule)}`); } function compile<mDT>(tree: JssmParseTree): JssmGenericConfig<mDT> { // todo flow describe the output of the parser const results : { graph_layout : Array< JssmLayout >, transition : Array< JssmTransition<mDT> >, start_states : Array< string >, end_states : Array< string >, state_config : Array< any >, // TODO COMEBACK no any state_declaration : Array< string >, fsl_version : Array< string >, machine_author : Array< string >, machine_comment : Array< string >, machine_contributor : Array< string >, machine_definition : Array< string >, machine_language : Array< string >, machine_license : Array< string >, machine_name : Array< string >, machine_reference : Array< string >, theme : Array< string >, flow : Array< string >, dot_preamble : Array< string >, arrange_declaration : Array< Array< string > >, // TODO COMEBACK CHECKME arrange_start_declaration : Array< Array< string > >, // TODO COMEBACK CHECKME arrange_end_declaration : Array< Array< string > >, // TODO COMEBACK CHECKME machine_version : Array< string > // TODO COMEBACK semver } = { graph_layout : [], transition : [], start_states : [], end_states : [], state_config : [], state_declaration : [], fsl_version : [], machine_author : [], machine_comment : [], machine_contributor : [], machine_definition : [], machine_language : [], machine_license : [], machine_name : [], machine_reference : [], theme : [], flow : [], dot_preamble : [], arrange_declaration : [], arrange_start_declaration : [], arrange_end_declaration : [], machine_version : [] }; tree.map( (tr : JssmCompileSeStart<StateType>) => { const rule : JssmCompileRule = compile_rule_handler(tr), agg_as : string = rule.agg_as, val : any = rule.val; // TODO FIXME no any results[agg_as] = results[agg_as].concat(val); }); const assembled_transitions : Array< JssmTransition<mDT> > = [].concat(... results['transition']); const result_cfg : JssmGenericConfig<mDT> = { start_states : results.start_states.length? results.start_states : [assembled_transitions[0].from], transitions : assembled_transitions }; const oneOnlyKeys : Array<string> = [ 'graph_layout', 'machine_name', 'machine_version', 'machine_comment', 'fsl_version', 'machine_license', 'machine_definition', 'machine_language', 'theme', 'flow', 'dot_preamble' ]; oneOnlyKeys.map( (oneOnlyKey : string) => { if (results[oneOnlyKey].length > 1) { throw new Error( `May only have one ${oneOnlyKey} statement maximum: ${JSON.stringify(results[oneOnlyKey])}` ); } else { if (results[oneOnlyKey].length) { result_cfg[oneOnlyKey] = results[oneOnlyKey][0]; } } }); ['arrange_declaration', 'arrange_start_declaration', 'arrange_end_declaration', 'machine_author', 'machine_contributor', 'machine_reference', 'state_declaration'].map( (multiKey : string) => { if (results[multiKey].length) { result_cfg[multiKey] = results[multiKey]; } } ); return result_cfg; } function make<mDT>(plan: string): JssmGenericConfig<mDT> { return compile(wrap_parse(plan)); } function transfer_state_properties(state_decl: JssmStateDeclaration): JssmStateDeclaration { state_decl.declarations.map( (d: JssmStateDeclarationRule) => { switch (d.key) { case 'shape' : state_decl.shape = d.value; break; case 'color' : state_decl.color = d.value; break; case 'corners' : state_decl.corners = d.value; break; case 'linestyle' : state_decl.linestyle = d.value; break; case 'text-color' : state_decl.textColor = d.value; break; case 'background-color' : state_decl.backgroundColor = d.value; break; case 'border-color' : state_decl.borderColor = d.value; break; default: throw new Error(`Unknown state property: '${JSON.stringify(d)}'`); } }); return state_decl; } class Machine<mDT> { _state : StateType; _states : Map<StateType, JssmGenericState>; _edges : Array<JssmTransition<mDT>>; _edge_map : Map<StateType, Map<StateType, number>>; _named_transitions : Map<StateType, number>; _actions : Map<StateType, Map<StateType, number>>; _reverse_actions : Map<StateType, Map<StateType, number>>; _reverse_action_targets : Map<StateType, Map<StateType, number>>; _machine_author? : Array<string>; _machine_comment? : string; _machine_contributor? : Array<string>; _machine_definition? : string; _machine_language? : string; _machine_license? : string; _machine_name? : string; _machine_version? : string; _fsl_version? : string; _raw_state_declaration? : Array<Object>; _state_declarations : Map<StateType, JssmStateDeclaration>; _graph_layout : JssmLayout; _dot_preamble : string; _arrange_declaration : Array<Array<StateType>>; _arrange_start_declaration : Array<Array<StateType>>; _arrange_end_declaration : Array<Array<StateType>>; _theme : FslTheme; _flow : FslDirection; // whargarbl this badly needs to be broken up, monolith master constructor({ start_states, complete = [], transitions, machine_author, machine_comment, machine_contributor, machine_definition, machine_language, machine_license, machine_name, machine_version, state_declaration, fsl_version, dot_preamble = undefined, arrange_declaration = [], arrange_start_declaration = [], arrange_end_declaration = [], theme = 'default', flow = 'down', graph_layout = 'dot' } : JssmGenericConfig<mDT>) { this._state = start_states[0]; this._states = new Map(); this._state_declarations = new Map(); this._edges = []; this._edge_map = new Map(); this._named_transitions = new Map(); this._actions = new Map(); this._reverse_actions = new Map(); this._reverse_action_targets = new Map(); // todo this._machine_author = array_box_if_string(machine_author); this._machine_comment = machine_comment; this._machine_contributor = array_box_if_string(machine_contributor); this._machine_definition = machine_definition; this._machine_language = machine_language; this._machine_license = machine_license; this._machine_name = machine_name; this._machine_version = machine_version; this._raw_state_declaration = state_declaration || []; this._fsl_version = fsl_version; this._arrange_declaration = arrange_declaration; this._arrange_start_declaration = arrange_start_declaration; this._arrange_end_declaration = arrange_end_declaration; this._dot_preamble = dot_preamble; this._theme = theme; this._flow = flow; this._graph_layout = graph_layout; if (state_declaration) { state_declaration.map( (state_decl: JssmStateDeclaration) => { if (this._state_declarations.has(state_decl.state)) { // no repeats throw new Error(`Added the same state declaration twice: ${JSON.stringify(state_decl.state)}`); } this._state_declarations.set( state_decl.state, transfer_state_properties(state_decl) ); } ); } transitions.map( (tr:JssmTransition<mDT>) => { if (tr.from === undefined) { throw new Error(`transition must define 'from': ${JSON.stringify(tr)}`); } if (tr.to === undefined) { throw new Error(`transition must define 'to': ${ JSON.stringify(tr)}`); } // get the cursors. what a mess const cursor_from: JssmGenericState = this._states.get(tr.from) || { name: tr.from, from: [], to: [], complete: complete.includes(tr.from) }; if (!(this._states.has(tr.from))) { this._new_state(cursor_from); } const cursor_to: JssmGenericState = this._states.get(tr.to) || {name: tr.to, from: [], to: [], complete: complete.includes(tr.to) }; if (!(this._states.has(tr.to))) { this._new_state(cursor_to); } // guard against existing connections being re-added if (cursor_from.to.includes(tr.to)) { throw new Error(`already has ${JSON.stringify(tr.from)} to ${JSON.stringify(tr.to)}`); } else { cursor_from.to.push(tr.to); cursor_to.from.push(tr.from); } // add the edge; note its id this._edges.push(tr); const thisEdgeId: number = this._edges.length - 1; // guard against repeating a transition name if (tr.name) { if (this._named_transitions.has(tr.name)) { throw new Error(`named transition "${JSON.stringify(tr.name)}" already created`); } else { this._named_transitions.set(tr.name, thisEdgeId); } } // set up the mapping, so that edges can be looked up by endpoint pairs const from_mapping: Map<StateType, number> = this._edge_map.get(tr.from) || new Map(); if (!(this._edge_map.has(tr.from))) { this._edge_map.set(tr.from, from_mapping); } // const to_mapping = from_mapping.get(tr.to); from_mapping.set(tr.to, thisEdgeId); // already checked that this mapping doesn't exist, above // set up the action mapping, so that actions can be looked up by origin if (tr.action) { // forward mapping first by action name let actionMap: Map<StateType, number> = this._actions.get(tr.action); // TODO FIXME ?Map equiv if (!(actionMap)) { actionMap = new Map(); this._actions.set(tr.action, actionMap); } if (actionMap.has(tr.from)) { throw new Error(`action ${JSON.stringify(tr.action)} already attached to origin ${JSON.stringify(tr.from)}`); } else { actionMap.set(tr.from, thisEdgeId); } // reverse mapping first by state origin name let rActionMap: Map<StateType, number> = this._reverse_actions.get(tr.from); // TODO FIXME ?Map equiv if (!(rActionMap)) { rActionMap = new Map(); this._reverse_actions.set(tr.from, rActionMap); } // no need to test for reverse mapping pre-presence; // forward mapping already covers collisions rActionMap.set(tr.action, thisEdgeId); // reverse mapping first by state target name if (!(this._reverse_action_targets.has(tr.to))) { this._reverse_action_targets.set(tr.to, new Map()); } /* todo comeback fundamental problem is roActionMap needs to be a multimap const roActionMap = this._reverse_action_targets.get(tr.to); // wasteful - already did has - refactor if (roActionMap) { if (roActionMap.has(tr.action)) { throw new Error(`ro-action ${tr.to} already attached to action ${tr.action}`); } else { roActionMap.set(tr.action, thisEdgeId); } } else { throw new Error('should be impossible - flow doesn\'t know .set precedes .get yet again. severe error?'); } */ } }); } _new_state(state_config: JssmGenericState): StateType { if (this._states.has(state_config.name)) { throw new Error(`state ${JSON.stringify(state_config.name)} already exists`); } this._states.set(state_config.name, state_config); return state_config.name; } state(): StateType { return this._state; } /* whargarbl todo major when we reimplement this, reintroduce this change to the is_final call is_changing(): boolean { return true; // todo whargarbl } */ state_is_final(whichState: StateType): boolean { return ( (this.state_is_terminal(whichState)) && (this.state_is_complete(whichState)) ); } is_final(): boolean { // return ((!this.is_changing()) && this.state_is_final(this.state())); return this.state_is_final(this.state()); } graph_layout(): string { return this._graph_layout; } dot_preamble(): string { return this._dot_preamble; } machine_author(): Array<string> { return this._machine_author; } machine_comment(): string { return this._machine_comment; } machine_contributor(): Array<string> { return this._machine_contributor; } machine_definition(): string { return this._machine_definition; } machine_language(): string { return this._machine_language; } machine_license(): string { return this._machine_license; } machine_name(): string { return this._machine_name; } machine_version(): string { return this._machine_version; } raw_state_declarations(): Array<Object> { return this._raw_state_declaration; } state_declaration(which: StateType): JssmStateDeclaration { return this._state_declarations.get(which); } state_declarations(): Map<StateType, JssmStateDeclaration> { return this._state_declarations; } fsl_version(): string { return this._fsl_version; } machine_state(): JssmMachineInternalState<mDT> { return { internal_state_impl_version : 1, actions : this._actions, edge_map : this._edge_map, edges : this._edges, named_transitions : this._named_transitions, reverse_actions : this._reverse_actions, // reverse_action_targets : this._reverse_action_targets, state : this._state, states : this._states }; } /* load_machine_state(): boolean { return false; // todo whargarbl } */ states(): Array<StateType> { return Array.from(this._states.keys()); } state_for(whichState: StateType): JssmGenericState { const state: JssmGenericState = this._states.get(whichState); if (state) { return state; } else { throw new Error(`no such state ${JSON.stringify(state)}`); } } has_state(whichState: StateType): boolean { return this._states.get(whichState) !== undefined; } list_edges(): Array< JssmTransition<mDT> > { return this._edges; } list_named_transitions(): Map<StateType, number> { return this._named_transitions; } list_actions(): Array<StateType> { return Array.from(this._actions.keys()); } theme(): FslTheme { return this._theme; // constructor sets this to "default" otherwise } flow(): FslDirection { return this._flow; } get_transition_by_state_names(from: StateType, to: StateType): number { const emg : Map<StateType, number> = this._edge_map.get(from); if (emg) { return emg.get(to); } else { return undefined; } } lookup_transition_for(from: StateType, to: StateType): JssmTransition<mDT> { const id : number = this.get_transition_by_state_names(from, to); return ((id === undefined) || (id === null))? undefined : this._edges[id]; } list_transitions(whichState: StateType = this.state()): JssmTransitionList { return {entrances: this.list_entrances(whichState), exits: this.list_exits(whichState)}; } list_entrances(whichState: StateType = this.state()): Array<StateType> { return (this._states.get(whichState) || {from: undefined}).from || []; } list_exits(whichState: StateType = this.state()): Array<StateType> { return (this._states.get(whichState) || {to: undefined}).to || []; } probable_exits_for(whichState: StateType): Array< JssmTransition<mDT> > { const wstate: JssmGenericState = this._states.get(whichState); if (!(wstate)) { throw new Error(`No such state ${JSON.stringify(whichState)} in probable_exits_for`); } const wstate_to : Array<StateType> = wstate.to, wtf : Array< JssmTransition<mDT> > // wstate_to_filtered -> wtf = wstate_to .map( (ws) : JssmTransition<mDT> => this.lookup_transition_for(this.state(), ws)) .filter(Boolean); return wtf; } probabilistic_transition(): boolean { const selected : JssmTransition<mDT> = weighted_rand_select(this.probable_exits_for(this.state())); return this.transition( selected.to ); } probabilistic_walk(n: number): Array<StateType> { return seq(n) .map(() : StateType => { const state_was: StateType = this.state(); this.probabilistic_transition(); return state_was; }) .concat([this.state()]); } probabilistic_histo_walk(n: number): Map<StateType, number> { return histograph(this.probabilistic_walk(n)); } actions(whichState: StateType = this.state() ): Array<StateType> { const wstate : Map<StateType, number> = this._reverse_actions.get(whichState); if (wstate) { return Array.from(wstate.keys()); } else { throw new Error(`No such state ${JSON.stringify(whichState)}`); } } list_states_having_action(whichState: StateType): Array<StateType> { const wstate : Map<StateType, number> = this._actions.get(whichState); if (wstate) { return Array.from(wstate.keys()); } else { throw new Error(`No such state ${JSON.stringify(whichState)}`); } } // comeback /* list_entrance_actions(whichState: mNT = this.state() ) : Array<mNT> { return [... (this._reverse_action_targets.get(whichState) || new Map()).values()] // wasteful .map( (edgeId:any) => (this._edges[edgeId] : any)) // whargarbl burn out any .filter( (o:any) => o.to === whichState) .map( filtered => filtered.from ); } */ list_exit_actions(whichState: StateType = this.state() ): Array<StateType> { // these are mNT, not ?mNT const ra_base: Map<StateType, number> = this._reverse_actions.get(whichState); if (!(ra_base)) { throw new Error(`No such state ${JSON.stringify(whichState)}`); } return Array.from(ra_base.values()) .map ( (edgeId: number) : JssmTransition<mDT> => this._edges[edgeId] ) .filter ( (o: JssmTransition<mDT>) : boolean => o.from === whichState ) .map ( (filtered: JssmTransition<mDT>) : StateType => filtered.action ); } probable_action_exits(whichState: StateType = this.state() ) : Array<any> { // these are mNT // TODO FIXME no any const ra_base: Map<StateType, number> = this._reverse_actions.get(whichState); if (!(ra_base)) { throw new Error(`No such state ${JSON.stringify(whichState)}`); } return Array.from(ra_base.values()) .map ( (edgeId: number): JssmTransition<mDT> => this._edges[edgeId] ) .filter ( (o: JssmTransition<mDT>): boolean => o.from === whichState ) .map ( (filtered): any => ( { action : filtered.action, // TODO FIXME no any probability : filtered.probability } ) ); } // TODO FIXME test that is_unenterable on non-state throws is_unenterable(whichState: StateType): boolean { if (!(this.has_state(whichState))) { throw new Error(`No such state ${whichState}`); } return this.list_entrances(whichState).length === 0; } has_unenterables(): boolean { return this.states().some( (x: StateType): boolean => this.is_unenterable(x)); } is_terminal(): boolean { return this.state_is_terminal(this.state()); } // TODO FIXME test that state_is_terminal on non-state throws state_is_terminal(whichState: StateType): boolean { if (!(this.has_state(whichState))) { throw new Error(`No such state ${whichState}`); } return this.list_exits(whichState).length === 0; } has_terminals(): boolean { return this.states().some( (x): boolean => this.state_is_terminal(x)); } is_complete(): boolean { return this.state_is_complete(this.state()); } state_is_complete(whichState: StateType) : boolean { const wstate: JssmGenericState = this._states.get(whichState); if (wstate) { return wstate.complete; } else { throw new Error(`No such state ${JSON.stringify(whichState)}`); } } has_completes(): boolean { return this.states().some( (x): boolean => this.state_is_complete(x) ); } action(name: StateType, newData?: mDT): boolean { // todo whargarbl implement hooks // todo whargarbl implement data stuff // todo major incomplete whargarbl comeback if (this.valid_action(name, newData)) { const edge: JssmTransition<mDT> = this.current_action_edge_for(name); this._state = edge.to; return true; } else { return false; } } transition(newState: StateType, newData?: mDT): boolean { // todo whargarbl implement hooks // todo whargarbl implement data stuff // todo major incomplete whargarbl comeback if (this.valid_transition(newState, newData)) { this._state = newState; return true; } else { return false; } } // can leave machine in inconsistent state. generally do not use force_transition(newState: StateType, newData?: mDT): boolean { // todo whargarbl implement hooks // todo whargarbl implement data stuff // todo major incomplete whargarbl comeback if (this.valid_force_transition(newState, newData)) { this._state = newState; return true; } else { return false; } } current_action_for(action: StateType): number { const action_base: Map<StateType, number> = this._actions.get(action); return action_base? action_base.get(this.state()): undefined; } current_action_edge_for(action: StateType): JssmTransition<mDT> { const idx: number = this.current_action_for(action); if ((idx === undefined) || (idx === null)) { throw new Error(`No such action ${JSON.stringify(action)}`); } return this._edges[idx]; } valid_action(action: StateType, _newData?: mDT): boolean { // todo comeback unignore newData // todo whargarbl implement hooks // todo whargarbl implement data stuff // todo major incomplete whargarbl comeback return this.current_action_for(action) !== undefined; } valid_transition(newState: StateType, _newData?: mDT): boolean { // todo comeback unignore newData // todo whargarbl implement hooks // todo whargarbl implement data stuff // todo major incomplete whargarbl comeback const transition_for: JssmTransition<mDT> = this.lookup_transition_for(this.state(), newState); if (!(transition_for)) { return false; } if (transition_for.forced_only) { return false; } return true; } valid_force_transition(newState: StateType, _newData?: mDT): boolean { // todo comeback unignore newData // todo whargarbl implement hooks // todo whargarbl implement data stuff // todo major incomplete whargarbl comeback return (this.lookup_transition_for(this.state(), newState) !== undefined); } /* eslint-disable no-use-before-define */ /* eslint-disable class-methods-use-this */ sm(template_strings: TemplateStringsArray, ... remainder /* , arguments */): Machine<mDT> { return sm(template_strings, ... remainder); } /* eslint-enable class-methods-use-this */ /* eslint-enable no-use-before-define */ } function sm<mDT>(template_strings: TemplateStringsArray, ... remainder /* , arguments */): Machine<mDT> { // foo`a${1}b${2}c` will come in as (['a','b','c'],1,2) // this includes when a and c are empty strings // therefore template_strings will always have one more el than template_args // therefore map the smaller container and toss the last one on on the way out return new Machine(make(template_strings.reduce( // in general avoiding `arguments` is smart. however with the template // string notation, as designed, it's not really worth the hassle /* eslint-disable prefer-rest-params */ (acc, val, idx): string => `${acc}${remainder[idx-1]}${val}` // arguments[0] is never loaded, so args doesn't need to be gated /* eslint-enable prefer-rest-params */ ))); } export { version, transfer_state_properties, Machine, make, wrap_parse as parse, compile, sm, arrow_direction, arrow_left_kind, arrow_right_kind, // WHARGARBL TODO these should be exported to a utility library seq, weighted_rand_select, histograph, weighted_sample_select, weighted_histo_key };
the_stack
import {setup} from '#testHelpers' // On an unprevented mousedown the browser moves the cursor to the closest character. // As we have no layout, we are not able to determine the correct character. // So we try an approximation: // We treat any mousedown as if it happened on the space after the last character. test('single mousedown moves cursor to the end', async () => { const {element, user} = setup<HTMLInputElement>( `<input value="foo bar baz"/>`, ) await user.pointer({keys: '[MouseLeft>]', target: element}) expect(element).toHaveFocus() expect(element).toHaveProperty('selectionStart', 11) }) test('move focus to closest focusable element', async () => { const {element, user} = setup(` <div tabIndex="0"> <div>this is not focusable</div> <button>this is focusable</button> </div> `) await user.pointer({keys: '[MouseLeft>]', target: element.children[1]}) expect(element.children[1]).toHaveFocus() await user.pointer({keys: '[TouchA]', target: element.children[0]}) expect(element).toHaveFocus() }) test('blur when outside of focusable context', async () => { const { elements: [focusable, notFocusable], user, } = setup(` <div tabIndex="-1"></div> <div></div> `) expect(focusable).toHaveFocus() await user.pointer({keys: '[MouseLeft>]', target: notFocusable}) expect(document.body).toHaveFocus() }) test('mousedown handlers can prevent moving focus', async () => { const {element, user} = setup<HTMLInputElement>(`<input/>`, {focus: false}) element.addEventListener('mousedown', e => e.preventDefault()) await user.pointer({keys: '[MouseLeft>]', target: element}) await user.pointer({keys: '[TouchA]', target: element}) expect(element).not.toHaveFocus() expect(element).toHaveProperty('selectionStart', 0) }) test('single mousedown moves cursor to the last text', async () => { const {element, user} = setup<HTMLInputElement>( `<div contenteditable>foo bar baz</div>`, ) await user.pointer({keys: '[MouseLeft>]', target: element}) expect(element).toHaveFocus() expect(document.getSelection()).toHaveProperty( 'focusNode', element.firstChild, ) expect(document.getSelection()).toHaveProperty('focusOffset', 11) }) test('double mousedown selects a word or a sequence of whitespace', async () => { const {element, user} = setup<HTMLInputElement>( `<input value="foo bar baz"/>`, ) await user.pointer({keys: '[MouseLeft][MouseLeft>]', target: element}) expect(element).toHaveProperty('selectionStart', 8) expect(element).toHaveProperty('selectionEnd', 11) await user.pointer({ keys: '[MouseLeft][MouseLeft>]', target: element, offset: 0, }) expect(element).toHaveProperty('selectionStart', 0) expect(element).toHaveProperty('selectionEnd', 3) await user.pointer({ keys: '[MouseLeft][MouseLeft]', target: element, offset: 11, }) expect(element).toHaveProperty('selectionStart', 8) expect(element).toHaveProperty('selectionEnd', 11) element.value = 'foo bar ' await user.pointer({keys: '[MouseLeft][MouseLeft>]', target: element}) expect(element).toHaveProperty('selectionStart', 7) expect(element).toHaveProperty('selectionEnd', 9) }) test('triple mousedown selects whole line', async () => { const {element, user} = setup<HTMLInputElement>( `<input value="foo bar baz"/>`, ) await user.pointer({ keys: '[MouseLeft][MouseLeft][MouseLeft>]', target: element, }) expect(element).toHaveProperty('selectionStart', 0) expect(element).toHaveProperty('selectionEnd', 11) await user.pointer({ keys: '[MouseLeft][MouseLeft][MouseLeft>]', target: element, offset: 0, }) expect(element).toHaveProperty('selectionStart', 0) expect(element).toHaveProperty('selectionEnd', 11) await user.pointer({ keys: '[MouseLeft][MouseLeft][MouseLeft>]', target: element, offset: 11, }) expect(element).toHaveProperty('selectionStart', 0) expect(element).toHaveProperty('selectionEnd', 11) }) test('mousemove with pressed button extends selection', async () => { const {element, user} = setup<HTMLInputElement>( `<input value="foo bar baz"/>`, ) await user.pointer({ keys: '[MouseLeft][MouseLeft>]', target: element, offset: 6, }) expect(element).toHaveProperty('selectionStart', 4) expect(element).toHaveProperty('selectionEnd', 7) await user.pointer({offset: 2}) expect(element).toHaveProperty('selectionStart', 2) expect(element).toHaveProperty('selectionEnd', 7) await user.pointer({offset: 10}) expect(element).toHaveProperty('selectionStart', 4) expect(element).toHaveProperty('selectionEnd', 10) await user.pointer({}) expect(element).toHaveProperty('selectionStart', 4) expect(element).toHaveProperty('selectionEnd', 11) await user.pointer({offset: 5}) expect(element).toHaveProperty('selectionStart', 4) expect(element).toHaveProperty('selectionEnd', 7) }) test('selection is moved on non-input elements', async () => { const {element, user} = setup( `<section><a></a><span>foo</span> <span>bar</span> <span>baz</span></section>`, ) const span = element.querySelectorAll('span') await user.pointer({ keys: '[MouseLeft][MouseLeft>]', target: element, offset: 6, }) expect(document.getSelection()?.toString()).toBe('bar') expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startContainer', span[1].previousSibling, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startOffset', 1, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'endContainer', span[1].firstChild, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty('endOffset', 3) await user.pointer({offset: 2}) expect(document.getSelection()?.toString()).toBe('o bar') expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startContainer', span[0].firstChild, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startOffset', 2, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'endContainer', span[1].firstChild, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty('endOffset', 3) await user.pointer({offset: 10}) expect(document.getSelection()?.toString()).toBe('bar ba') expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startContainer', span[1].previousSibling, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startOffset', 1, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'endContainer', span[2].firstChild, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty('endOffset', 2) await user.pointer({}) expect(document.getSelection()?.toString()).toBe('bar baz') expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startContainer', span[1].previousSibling, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startOffset', 1, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'endContainer', span[2].firstChild, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty('endOffset', 3) }) test('`node` overrides the text offset approximation', async () => { const {element, user} = setup( `<section><div><span>foo</span> <span>bar</span></div> <span>baz</span></section>`, ) const div = element.firstChild as HTMLDivElement const span = element.querySelectorAll('span') await user.pointer({ keys: '[MouseLeft>]', target: element, node: span[0].firstChild as Node, offset: 1, }) await user.pointer({node: div, offset: 3}) expect(document.getSelection()?.toString()).toBe('oo bar') expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startContainer', span[0].firstChild, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startOffset', 1, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'endContainer', div, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty('endOffset', 3) await user.pointer({ keys: '[MouseLeft]', target: element, node: span[0].firstChild as Node, }) expect(document.getSelection()?.toString()).toBe('') expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startContainer', span[0].firstChild, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startOffset', 3, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'endContainer', span[0].firstChild, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty('endOffset', 3) await user.pointer({ keys: '[MouseLeft]', target: element, node: span[0] as Node, }) expect(document.getSelection()?.toString()).toBe('') expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startContainer', span[0], ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'startOffset', 1, ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty( 'endContainer', span[0], ) expect(document.getSelection()?.getRangeAt(0)).toHaveProperty('endOffset', 1) }) describe('focus control when clicking label', () => { test('click event on label moves focus to control', async () => { const { elements: [input, label], user, } = setup(`<input id="a" value="foo"/><label for="a" tabindex="-1"/>`) await user.pointer({ keys: '[MouseLeft>]', target: label, }) expect(label).toHaveFocus() await user.pointer('[/MouseLeft]') expect(label).not.toHaveFocus() expect(input).toHaveFocus() }) test('click handlers can prevent moving focus per label', async () => { const { elements: [input, label], user, } = setup(`<input id="a"/><label for="a" tabindex="-1"/>`) label.addEventListener('click', e => e.preventDefault()) await user.pointer({keys: '[MouseLeft]', target: label}) expect(input).not.toHaveFocus() }) test('do not move focus to disabled control', async () => { const { elements: [input, label], user, } = setup(`<input id="a" disabled/><label for="a" tabindex="-1"/>`) await user.pointer({keys: '[MouseLeft]', target: label}) expect(label).toHaveFocus() expect(input).not.toHaveFocus() }) }) test('focus event handler can override selection', async () => { const {element, user} = setup(`<input value="hello"/>`, { focus: false, }) element.addEventListener('focus', e => (e.target as HTMLInputElement).select(), ) await user.click(element) expect(element).toHaveProperty('selectionStart', 0) expect(element).toHaveProperty('selectionEnd', 5) })
the_stack
import Vue, { VueConstructor } from "vue" import { App } from "vue3" interface unicomGather { [propName: string]: Unicom // 任意类型 } // #id 存放id的unicom对象 let unicomGroupByID: unicomGather = {} /** * 寄存target(vm) * @param target * @param newId * @param oldId */ function updateUnicomGroupByID(target: Unicom, newId: string, oldId: string): void { // 更新 id 触发更新 if (oldId && unicomGroupByID[oldId] == target) { delete unicomGroupByID[oldId] } if (newId) { unicomGroupByID[newId] = target } } interface unicomGatherName { [propName: string]: Array<Unicom> // 任意类型 } // @name 存放name的数组对象 let unicomGroupByName: unicomGatherName = {} /** * 通过name存放 target(vm) * @param target * @param name */ function addUnicomGroupByNameOne(target: Unicom, name: string): void { // 加入一个name let unicoms = unicomGroupByName[name] if (!unicoms) { unicoms = unicomGroupByName[name] = [] } if (unicoms.indexOf(target) < 0) { unicoms.push(target) } } /** * 更新unicom name命名 * @param target * @param newName * @param oldNamegroup */ function updateUnicomGroupByName(target: Unicom, newName: Array<string>, oldName: Array<string>) { // 某个unicom对象更新 name if (oldName) { // 移除所有旧的 oldName.forEach(function (name) { let unicoms = unicomGroupByName[name] if (unicoms) { let index = unicoms.indexOf(target) if (index > -1) { unicoms.splice(index, 1) } } }) } if (newName) { // 加入新的 newName.forEach(function (name) { addUnicomGroupByNameOne(target, name) }) } } // @all 所有的unicom对象集合,发布指令是待用 let unicomGroup: Array<Unicom> = [] function addUnicomGroup(target: Unicom): void { // 添加 unicomGroup.push(target) } function removeUnicomGroup(target: Unicom): void { // 移除 let index = unicomGroup.indexOf(target) if (index > -1) { unicomGroup.splice(index, 1) } } // 发布指令时产生的事件的类 class UnicomEvent { from: any target: any data: any; [propName: string]: any constructor(from: any, args: Array<any>) { // 来自 this.from = from // 目标绑定的对象,vue中代表vue的实例 this.target = from.target // 第一号数据 this.data = args[0] // 多个数据 使用 $index 表示 args.forEach((arg, index) => { this["$" + (index + 1)] = arg }) } } // 发布事件 function emitAll(self: any, type: string, target: string, instruct: string, args: Array<any>): UnicomEvent | Unicom | Array<Unicom> { let targetUnicom: Array<Unicom> = [] if (type == "#") { // 目标唯一 let one = unicomGroupByID[target] if (!instruct) { // 只是获取 return one } if (one) { targetUnicom.push(one) } } else if (type == "@") { // 目标是个分组 let group = unicomGroupByName[target] if (!instruct) { // 只是获取 return group } if (group) { targetUnicom.push(...group) } } else { targetUnicom.push(...unicomGroup) } let uniEvent = new UnicomEvent(self, args) targetUnicom.forEach(function (emit) { // 每个都触发一遍 emit.emit(instruct, uniEvent, ...args) }) return uniEvent } interface unicomMonitor extends Array<any> { [0]: string [1]: string [2]: Function [3]?: Unicom } // 监控数据 let monitorArr: Array<unicomMonitor> = [] function monitorExec(that: Unicom) { for (let i = 0; i < monitorArr.length; i += 1) { let [type, target, callback] = monitorArr[i] if ((type == "#" && that.id == target) || (type == "@" && that.group.indexOf(target) > -1)) { // 运行监控回调 callback(that) } } } interface unicomArg { id?: string group?: string | Array<string> target?: any } interface unicomInstruct { [propName: string]: Array<Function> // 任意类型 } // 通讯基础类 export class Unicom { static install: Function = install // 事件存放 private _instruct_: unicomInstruct = {} // 绑定目标 可以是vue的vm 也可以是任意 target: any // 唯一的id id: string // 属于的分组 group: Array<string> // 私有属性 private _monitor_back_: number constructor({ id, group, target }: unicomArg = {}) { let _instruct_ = this._instruct_ this._instruct_ = {} if (_instruct_) { // 克隆一份 事件 // 通过 Unicom.prototype.on() 会把事件写入 Unicom.prototype._instruct_ // 所以要重写,防止全局冲突 for (let n in _instruct_) { this._instruct_[n] = [].concat(_instruct_[n]) } } // 绑定的目标对象 this.target = target // 分组 this.group = [] if (id) { this.setId(id) } if (group) { this.setGroup(group) } // 将实例加入到单例的队列 addUnicomGroup(this) // 查找监控中是否被监控中 this.monitorBack() } // 延迟合并执行 monitorBack(): Unicom { clearTimeout(this._monitor_back_) this._monitor_back_ = setTimeout(() => { monitorExec(this) }, 1) return this } // 监听目标创建 monitor(instruct: string, callback: Function): Unicom { let type = instruct.slice(0, 1) let target = instruct.slice(1, instruct.length) monitorArr.push([type, target, callback, this]) return this } // 销毁监听 monitorOff(instruct?: string, callback?: Function): Unicom { for (let i = 0; i < monitorArr.length; ) { let [type, target, fn, self] = monitorArr[i] if (self == this && (!instruct || instruct == type + target) && (!callback || callback == fn)) { monitorArr.splice(i, 1) continue } i += 1 } return this } // 销毁 destroy(): void { // 销毁队列 removeUnicomGroup(this) // 移除 updateUnicomGroupByID(this, null, this.id) updateUnicomGroupByName(this, null, this.group) // 监控销毁 this.monitorOff() // 订阅销毁 this.off() } // 唯一标识 setId(id: string): Unicom { if (this.id != id) { updateUnicomGroupByID(this, id, this.id) this.id = id // 运行延后执行 this.monitorBack() } return this } // 分组 setGroup(group: string | string[]) { if (typeof group == "string") { this.group.push(group) addUnicomGroupByNameOne(this, group) return this } // 重新更新 updateUnicomGroupByName(this, group, this.group) this.group = group // 运行延后执行 this.monitorBack() return this } has(type: string): boolean { let instruct: Function[] = (this._instruct_ || {})[type] return !!(instruct && instruct.length > 0) } // 订阅消息 on(type: string, fun: Function): Unicom { let instruct = this._instruct_ || (this._instruct_ = {}) instruct[type] || (instruct[type] = []) instruct[type].push(fun) return this } // 移除订阅 off(type?: string, fun?: Function): Unicom { let instruct = this._instruct_ if (instruct) { if (fun) { let es = instruct[type] if (es) { let index = es.indexOf(fun) if (index > -1) { es.splice(index, 1) } if (es.length == 0) { delete instruct[type] } } } else if (type) { delete instruct[type] } else { delete this._instruct_ } } return this } // 触发订阅 emit(query: string, ...args: any): any { let data = args[0] if (data && data.constructor == UnicomEvent) { // 只需要负责自己 let es = (this._instruct_ && this._instruct_[query]) || [] es.forEach(channelFn => { channelFn.apply(this.target || this, args) }) return data } // 以下是全局触发发布 let type, target, instruct instruct = query.replace(/([@#])([^@#]*)$/, function (s0, s1, s2) { target = s2 type = s1 return "" }) return emitAll(this, type, target, instruct, args) } } // vue 安装插槽 let unicomInstalled: boolean = false // install 参数 interface unicomInstallArg { useProps?: boolean name?: string unicomName?: string unicomId?: string unicomEmit?: string unicomClass?: string } // vue中指令 interface vueInstruct { [propName: string]: Function } // vue临时存储数据 interface vueUnicomData { isIgnore: boolean // 分组 initGroup?: Array<string> // 指令 instructs?: Array<vueInstruct> // 绑定的unicom对象 unicom?: Unicom } export function install(V: VueConstructor | App, { name = "unicom", useProps = true, unicomName, unicomId, unicomEmit, unicomClass }: unicomInstallArg = {}) { if (unicomInstalled) { // 防止重复install return } unicomInstalled = true function uniconExe(this: any, query: string, ...args: any) { return this._unicom_data_.unicom.emit(query, ...args) } var is3 = V.version.indexOf("3") == 0 var destroyed = "destroyed" // 添加原型方法 let unicomEmitName = unicomEmit || name if (is3) { destroyed = "unmounted" var vA = V as App vA.config.globalProperties["$" + unicomEmitName] = uniconExe } else { // 添加原型方法 var vV = V as VueConstructor vV.prototype["$" + unicomEmitName] = uniconExe } // 方便插件中引入 let VueUnicomClassName = unicomClass if (!VueUnicomClassName) { VueUnicomClassName = name.replace(/^\w/, function (s0) { return s0.toUpperCase() }) } V[VueUnicomClassName] = Unicom // unicom-id let unicomIdName = unicomId || name + "Id" // 分组 unicom-name let unicomGroupName = unicomName || name + "Name" // 组合分组 function getGroup(target: any) { let unicomData = target._unicom_data_ let names = target[unicomGroupName] || [] return unicomData.initGroup.concat(names) } let mixin = { // 创建的时候,加入事件机制 beforeCreate() { let self = this as any // 屏蔽不需要融合的 节点 let isIgnore = !is3 && (!self.$vnode || /-transition$/.test(self.$vnode.tag)) // unicomData 数据存放 let unicomData: vueUnicomData = { // 不需要,忽略 isIgnore } self._unicom_data_ = unicomData if (isIgnore) { return } let opt = this.$options unicomData.initGroup = opt[unicomGroupName] || [] unicomData.instructs = opt[name] || [] // 触发器 // unicomData.self = new Unicom({target: this}) }, created() { let self = this as any let unicomData = self._unicom_data_ if (unicomData.isIgnore) { // 忽略 return } // 初始化 let unicom = (unicomData.unicom = new Unicom({ target: self, id: self[unicomIdName], group: getGroup(self) })) // 订阅事件 unicomData.instructs.forEach(function (subs) { for (let n in subs) { unicom.on(n, subs[n]) } }) }, // 全局混合, 销毁实例的时候,销毁事件 [destroyed]() { // let self = this as any let unicomData = this._unicom_data_ if (unicomData.isIgnore) { // 忽略 return } // 销毁 unicom 对象 unicomData.unicom.destroy() } } if (useProps) { Object.assign(mixin, { props: { // 命名 [unicomIdName]: { type: String, default: "" }, // 分组 [unicomGroupName]: { type: [String, Array], default: "" } }, watch: { [unicomIdName](nv) { let self = this as any let unicom = self._unicom_data_ && self._unicom_data_.unicom if (unicom) { unicom.setId(nv) } }, [unicomGroupName]() { let self = this as any let unicom = self._unicom_data_ && self._unicom_data_.unicom if (unicom) { unicom.setGroup(getGroup(self)) } } } }) } // 全局混入 vue V.mixin(mixin) // 自定义属性合并策略 let merge = V.config.optionMergeStrategies merge[name] = function (parentVal, childVal) { let arr = parentVal || [] if (childVal) { arr.push(childVal) } return arr } merge[unicomGroupName] = function (parentVal, childVal) { let arr = parentVal || [] if (childVal) { if (typeof childVal == "string") { arr.push(childVal) } else { arr.push(...childVal) } } return arr } } export default Unicom
the_stack
import type { Constructor, GraphQLError } from '@apollo-elements/core/types'; import type * as I from '@apollo-elements/core/types'; import type { ApolloClient, DocumentNode, ErrorPolicy, WatchQueryFetchPolicy, NormalizedCacheObject, TypedDocumentNode, } from '@apollo/client/core'; import * as S from '@apollo-elements/test/schema'; import { defineCE, expect, fixture, nextFrame } from '@open-wc/testing'; import { assertType, isApolloError, stringify, TestableElement } from '@apollo-elements/test'; import { describeQuery, setupQueryClass } from '@apollo-elements/test/query.test'; import { makeClient, teardownClient } from '@apollo-elements/test'; import { NetworkStatus } from '@apollo/client/core'; import { ApolloQueryMixin } from './apollo-query-mixin'; import { spy } from 'sinon'; class XL extends HTMLElement { hi?: 'hi'; } class TestableApolloQuery<D = unknown, V = I.VariablesOf<D>> extends ApolloQueryMixin(XL)<D, V> implements TestableElement { declare shadowRoot: ShadowRoot; static get template() { const template = document.createElement('template'); template.innerHTML = /* html */` <output id="data"></output> <output id="error"></output> <output id="errors"></output> <output id="loading"></output> <output id="networkStatus"></output> `; return template; } $(id: keyof this) { return this.shadowRoot.getElementById(id as string); } observed: Array<keyof this> = ['data', 'error', 'errors', 'loading', 'networkStatus']; constructor() { super(); this.hi = 'hi'; this.attachShadow({ mode: 'open' }) .append(TestableApolloQuery.template.content.cloneNode(true)); } update() { this.render(); } render() { this.observed?.forEach(property => { if (this.$(property)) this.$(property)!.textContent = stringify(this[property]); }); } async hasRendered() { await this.controller.host.updateComplete; await nextFrame(); return this; } } const setupFunction = setupQueryClass(TestableApolloQuery); describe('[mixins] ApolloQueryMixin', function() { describeQuery({ setupFunction, class: TestableApolloQuery }); describe('when base does not define observedAttributes', function() { class TestBase extends HTMLElement { } let element: TestBase & I.ApolloQueryElement<any, any>; beforeEach(async function() { const tag = defineCE(ApolloQueryMixin(TestBase)); element = await fixture(`<${tag}></${tag}>`); }); it('defines observedAttributes', function() { // @ts-expect-error: ts doesn't track constructor type; expect(element.constructor.observedAttributes).to.deep.equal([ 'error-policy', 'fetch-policy', 'next-fetch-policy', 'no-auto-subscribe', ]); }); }); describe('when base defines observedAttributes', function() { class TestBase extends HTMLElement { static get observedAttributes() { return ['a']; } } let element: TestBase & I.ApolloQueryElement<any, any>; beforeEach(async function() { const tag = defineCE(ApolloQueryMixin(TestBase)); element = await fixture(`<${tag}></${tag}>`); }); it('defines observedAttributes', function() { // @ts-expect-error: ts doesn't track constructor type; expect(element.constructor.observedAttributes).to.deep.equal([ 'a', 'error-policy', 'fetch-policy', 'next-fetch-policy', 'no-auto-subscribe', ]); }); }); describe('basic instance', function() { let element: I.ApolloQueryElement<any, any>; beforeEach(async function() { const tag = defineCE(ApolloQueryMixin(HTMLElement)); element = await fixture(`<${tag}></${tag}>`); }); describe('setting nextFetchPolicy', function() { beforeEach(() => element.nextFetchPolicy = 'cache-and-network'); beforeEach(nextFrame); it('sets attribute', function() { expect(element.getAttribute('next-fetch-policy')).to.equal('cache-and-network'); }); describe('then unsetting nextFetchPolicy', function() { beforeEach(() => element.nextFetchPolicy = undefined); beforeEach(nextFrame); it('removes attribute', function() { expect(element.hasAttribute('next-fetch-policy')).to.be.false; }); }); describe('then setting nextFetchPolicy with a function', function() { beforeEach(() => element.nextFetchPolicy = () => 'cache-first'); beforeEach(nextFrame); it('removes attribute', function() { expect(element.hasAttribute('next-fetch-policy')).to.be.false; }); }); }); }); describe('with onData and onError', function() { let element: I.ApolloQueryElement<any, any>; const s = spy(); beforeEach(async function() { const tag = defineCE(class extends ApolloQueryMixin(HTMLElement)<any, any> { client = makeClient(); onData(x: unknown) { s(x); } onError(x: Error) { s(x); } }); element = await fixture(`<${tag}></${tag}>`); }); afterEach(() => s.resetHistory()); afterEach(teardownClient); describe('resolving a query', function() { beforeEach(() => element.executeQuery({ query: S.NullableParamQuery })); beforeEach(nextFrame); it('calls onData', function() { expect(s).to.have.been.calledOnce; }); }); describe('getting a query error', function() { beforeEach(() => element.executeQuery({ query: S.NullableParamQuery, variables: { nullable: 'error', }, }).catch(() => null)); beforeEach(nextFrame); it('calls onError', function() { expect(s).to.have.been.calledOnce; }); }); }); }); type TypeCheckData = { a: 'a', b: number }; type TypeCheckVars = { d: 'd', e: number }; class TypeCheck extends TestableApolloQuery<TypeCheckData, TypeCheckVars> { variables = { d: 'd' as const, e: 0 }; typeCheck(): void { /* eslint-disable max-len, func-call-spacing, no-multi-spaces */ assertType<HTMLElement> (this); // ApolloElementInterface assertType<ApolloClient<NormalizedCacheObject>> (this.client!); assertType<Record<string, unknown>> (this.context!); assertType<boolean> (this.loading); assertType<DocumentNode> (this.document!); assertType<Error> (this.error!); assertType<readonly GraphQLError[]> (this.errors!); assertType<TypeCheckData> (this.data!); assertType<string> (this.error.message); assertType<'a'> (this.data.a); // @ts-expect-error: b as number type assertType<'a'> (this.data.b); assertType<TypeCheckVars> (this.variables); assertType<'d'> (this.variables.d); assertType<number> (this.variables.e); if (isApolloError(this.error)) assertType<readonly GraphQLError[]> (this.error.graphQLErrors); // ApolloQueryInterface assertType<DocumentNode> (this.query!); assertType<ErrorPolicy> (this.errorPolicy!); // @ts-expect-error: ErrorPolicy is not a number assertType<number> (this.errorPolicy); assertType<WatchQueryFetchPolicy> (this.fetchPolicy!); assertType<string> (this.fetchPolicy); if (typeof this.nextFetchPolicy !== 'function') assertType<WatchQueryFetchPolicy> (this.nextFetchPolicy!); assertType<NetworkStatus> (this.networkStatus); assertType<number> (this.networkStatus); // @ts-expect-error: NetworkStatus is not a string assertType<string> (this.networkStatus); assertType<boolean> (this.notifyOnNetworkStatusChange!); assertType<number> (this.pollInterval!); assertType<boolean> (this.partial!); assertType<boolean> (this.partialRefetch!); assertType<boolean> (this.returnPartialData!); assertType<boolean> (this.noAutoSubscribe); /* eslint-enable max-len, func-call-spacing, no-multi-spaces */ } } type TDN = TypedDocumentNode<TypeCheckData, TypeCheckVars>; export class TDNTypeCheck extends ApolloQueryMixin(HTMLElement)<TDN> { typeCheck(): void { assertType<TypeCheckData>(this.data!); assertType<TypeCheckVars>(this.variables!); } } function RuntimeMixin<Base extends Constructor>(superclass: Base) { return class extends superclass { declare mixinProp: boolean; }; } class MixedClass<D, V = I.VariablesOf<D>> extends RuntimeMixin(ApolloQueryMixin(HTMLElement))<D, V> { } function ChildMixin<Base extends Constructor>(superclass: Base) { return class extends superclass { declare childProp: number; }; } class Inheritor<D, V = I.VariablesOf<D>> extends ChildMixin(MixedClass)<D, V> { } const runChecks = false; if (runChecks) { const instance = new MixedClass<{ foo: number }, unknown>(); const inheritor = new Inheritor<{ foo: string }, unknown>(); assertType<number>(instance.data!.foo); assertType<boolean>(instance.mixinProp); assertType<string>(inheritor.data!.foo); assertType<boolean>(inheritor.mixinProp); assertType<number>(inheritor.childProp); } type TCD = { hey: 'yo' }; type TCV = { hey: 'yo' }; export class TypeCheckAccessor extends ApolloQueryMixin(HTMLElement)<TCD, TCV> { // @ts-expect-error: don't allow using accessors. Run a function when dependencies change instead get variables(): TCV { return { hey: 'yo' as const }; } } export class TypeCheckField extends ApolloQueryMixin(HTMLElement)<TCD, TCV> { variables = { hey: 'yo' as const }; } export class TypeCheckFieldBad extends ApolloQueryMixin(HTMLElement)<TCD, TCV> { // @ts-expect-error: passes type check; variables = { hey: 'hey' }; }
the_stack
* @packageDocumentation * @module scene-graph */ import { ccclass, visible, type, displayOrder, readOnly, slide, range, rangeStep, editable, serializable, rangeMin, tooltip, formerlySerializedAs } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { TextureCube } from '../assets/texture-cube'; import { CCFloat, CCBoolean, CCInteger } from '../data/utils/attribute'; import { Color, Quat, Vec3, Vec2, Vec4 } from '../math'; import { Ambient } from '../renderer/scene/ambient'; import { Shadows, ShadowType, PCFType, ShadowSize } from '../renderer/scene/shadows'; import { Skybox } from '../renderer/scene/skybox'; import { Fog, FogType } from '../renderer/scene/fog'; import { Node } from './node'; import { legacyCC } from '../global-exports'; import { Root } from '../root'; const _up = new Vec3(0, 1, 0); const _v3 = new Vec3(); const _qt = new Quat(); // Normalize HDR color const normalizeHDRColor = (color : Vec4) => { const intensity = 1.0 / Math.max(Math.max(Math.max(color.x, color.y), color.z), 0.0001); if (intensity < 1.0) { color.x *= intensity; color.y *= intensity; color.z *= intensity; } }; /** * @en Environment lighting information in the Scene * @zh 场景的环境光照相关信息 */ @ccclass('cc.AmbientInfo') export class AmbientInfo { @serializable @formerlySerializedAs('_skyColor') protected _skyColorHDR = new Vec4(0.2, 0.5, 0.8, 1.0); @serializable @formerlySerializedAs('_skyIllum') protected _skyIllumHDR = Ambient.SKY_ILLUM; @serializable @formerlySerializedAs('_groundAlbedo') protected _groundAlbedoHDR = new Vec4(0.2, 0.2, 0.2, 1.0); @serializable protected _skyColorLDR = new Vec4(0.2, 0.5, 0.8, 1.0); @serializable protected _skyIllumLDR = Ambient.SKY_ILLUM; @serializable protected _groundAlbedoLDR = new Vec4(0.2, 0.2, 0.2, 1.0); protected _resource: Ambient | null = null; get skyColorHDR () { return this._skyColorHDR; } get groundAlbedoHDR () { return this._groundAlbedoHDR; } get skyIllumHDR () { return this._skyIllumHDR; } get skyColorLDR () { return this._skyColorLDR; } get groundAlbedoLDR () { return this._groundAlbedoLDR; } get skyIllumLDR () { return this._skyIllumLDR; } /** * @en Sky lighting color configurable in editor with color picker * @zh 编辑器中可配置的天空光照颜色(通过颜色拾取器) */ @editable set skyLightingColor (val: Color) { let result; const color = new Vec4(val.x, val.y, val.z, val.w); if ((legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR) { this._skyColorHDR = color; (result as Vec4) = this._skyColorHDR; } else { this._skyColorLDR = color; (result as Vec4) = this._skyColorLDR; } if (this._resource) { this._resource.skyColor = _v3.set(color.x, color.y, color.z); } } get skyLightingColor () { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; const color = isHDR ? this._skyColorHDR.clone() : this._skyColorLDR.clone(); normalizeHDRColor(color); return new Color(color.x * 255, color.y * 255, color.z * 255, 255); } set skyColor (val: Vec4) { if ((legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR) { this._skyColorHDR = val; } else { this._skyColorLDR = val; } if (this._resource) { this._resource.skyColor = val; } } /** * @en Sky illuminance * @zh 天空亮度 */ @editable @type(CCFloat) set skyIllum (val: number) { if ((legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR) { this._skyIllumHDR = val; } else { this._skyIllumLDR = val; } if (this._resource) { this._resource.skyIllum = val; } } get skyIllum () { if ((legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR) { return this._skyIllumHDR; } else { return this._skyIllumLDR; } } /** * @en Ground lighting color configurable in editor with color picker * @zh 编辑器中可配置的地面光照颜色(通过颜色拾取器) */ @editable set groundLightingColor (val: Color) { let result; const color = new Vec4(val.x, val.y, val.z, val.w); if ((legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR) { this._groundAlbedoHDR = color; (result as Vec4) = this._groundAlbedoHDR; } else { this._groundAlbedoLDR = color; (result as Vec4) = this._groundAlbedoLDR; } if (this._resource) { this._resource.groundAlbedo = _v3.set(color.x, color.y, color.z); } } get groundLightingColor () { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; const color = isHDR ? this._groundAlbedoHDR : this._groundAlbedoLDR; normalizeHDRColor(color); return new Color(color.x * 255, color.y * 255, color.z * 255, 255); } set groundAlbedo (val: Vec4) { if ((legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR) { this._groundAlbedoHDR = val; } else { this._groundAlbedoLDR = val; } if (this._resource) { this._resource.groundAlbedo = val; } } public activate (resource: Ambient) { this._resource = resource; this._resource.initialize(this); } } legacyCC.AmbientInfo = AmbientInfo; /** * @en Skybox related information * @zh 天空盒相关信息 */ @ccclass('cc.SkyboxInfo') export class SkyboxInfo { @serializable protected _applyDiffuseMap = false; @serializable @type(TextureCube) @formerlySerializedAs('_envmap') protected _envmapHDR: TextureCube | null = null; @serializable @type(TextureCube) protected _envmapLDR: TextureCube | null = null; @serializable @type(TextureCube) protected _diffuseMapHDR: TextureCube | null = null; @serializable @type(TextureCube) protected _diffuseMapLDR: TextureCube | null = null; @serializable protected _enabled = false; @serializable protected _useIBL = false; @serializable protected _useHDR = true; protected _resource: Skybox | null = null; /** * @en Whether to use diffuse convolution map. Enabled -> Will use map specified. Disabled -> Will revert to hemispheric lighting * @zh 是否为IBL启用漫反射卷积图?不启用的话将使用默认的半球光照 */ @visible(function (this : SkyboxInfo) { if (this.useIBL) { return true; } return false; }) @editable set applyDiffuseMap (val) { this._applyDiffuseMap = val; if (this._resource) { this._resource.useDiffuseMap = val; } } get applyDiffuseMap () { return this._applyDiffuseMap; } /** * @en Whether activate skybox in the scene * @zh 是否启用天空盒? */ @editable set enabled (val) { if (this._enabled === val) return; this._enabled = val; if (this._resource) { this._resource.enabled = this._enabled; } } get enabled () { return this._enabled; } /** * @en Whether use environment lighting * @zh 是否启用环境光照? */ @editable set useIBL (val) { this._useIBL = val; if (this._resource) { this._resource.useIBL = this._useIBL; } } get useIBL () { return this._useIBL; } /** * @en Toggle HDR (TODO: This SHOULD be moved into it's own subgroup away from skybox) * @zh 是否启用HDR? */ @editable set useHDR (val) { (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR = val; this._useHDR = val; // Switch UI to and from LDR/HDR textures depends on HDR state if (this._resource) { this.envmap = this._resource.envmap; this.diffuseMap = this._resource.diffuseMap; if (this.diffuseMap == null) { this.applyDiffuseMap = false; } } if (this._resource) { this._resource.useHDR = this._useHDR; } } get useHDR () { (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR = this._useHDR; return this._useHDR; } /** * @en The texture cube used for the skybox * @zh 使用的立方体贴图 */ @editable @type(TextureCube) set envmap (val) { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { this._envmapHDR = val; } else { this._envmapLDR = val; } if (!this._envmapHDR) { this._diffuseMapHDR = null; this._applyDiffuseMap = false; this.useIBL = false; } if (this._resource) { this._resource.setEnvMaps(this._envmapHDR, this._envmapLDR); this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR); this._resource.useDiffuseMap = this._applyDiffuseMap; this._resource.envmap = val; } } get envmap () { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { return this._envmapHDR; } else { return this._envmapLDR; } } /** * @en The optional diffusion convolution map used in tandem with IBL * @zh 使用的漫反射卷积图 */ @visible(function (this : SkyboxInfo) { if (this.useIBL) { return true; } return false; }) @editable @readOnly @type(TextureCube) set diffuseMap (val : TextureCube | null) { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { this._diffuseMapHDR = val; } else { this._diffuseMapLDR = val; } if (this._resource) { this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR); } } get diffuseMap () { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { return this._diffuseMapHDR; } else { return this._diffuseMapLDR; } } public activate (resource: Skybox) { this._resource = resource; this._resource.initialize(this); this._resource.setEnvMaps(this._envmapHDR, this._envmapLDR); this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR); this._resource.activate(); // update global DS first } } legacyCC.SkyboxInfo = SkyboxInfo; /** * @zh 全局雾相关信息 * @en Global fog info */ @ccclass('cc.FogInfo') export class FogInfo { public static FogType = FogType; @serializable protected _type = FogType.LINEAR; @serializable protected _fogColor = new Color('#C8C8C8'); @serializable protected _enabled = false; @serializable protected _fogDensity = 0.3; @serializable protected _fogStart = 0.5; @serializable protected _fogEnd = 300; @serializable protected _fogAtten = 5; @serializable protected _fogTop = 1.5; @serializable protected _fogRange = 1.2; protected _resource: Fog | null = null; /** * @zh 是否启用全局雾效 * @en Enable global fog */ @editable set enabled (val: boolean) { if (this._enabled === val) return; this._enabled = val; if (this._resource) { this._resource.enabled = val; if (val) { this._resource.type = this._type; } } } get enabled () { return this._enabled; } /** * @zh 全局雾颜色 * @en Global fog color */ @editable set fogColor (val: Color) { this._fogColor.set(val); if (this._resource) { this._resource.fogColor = this._fogColor; } } get fogColor () { return this._fogColor; } /** * @zh 全局雾类型 * @en Global fog type */ @editable @type(FogType) get type () { return this._type; } set type (val) { this._type = val; if (this._resource) { this._resource.type = val; } } /** * @zh 全局雾浓度 * @en Global fog density */ @visible(function (this: FogInfo) { return this._type !== FogType.LAYERED && this._type !== FogType.LINEAR; }) @type(CCFloat) @range([0, 1]) @rangeStep(0.01) @slide @displayOrder(3) get fogDensity () { return this._fogDensity; } set fogDensity (val) { this._fogDensity = val; if (this._resource) { this._resource.fogDensity = val; } } /** * @zh 雾效起始位置,只适用于线性雾 * @en Global fog start position, only for linear fog */ @visible(function (this: FogInfo) { return this._type === FogType.LINEAR; }) @type(CCFloat) @rangeStep(0.01) @displayOrder(4) get fogStart () { return this._fogStart; } set fogStart (val) { this._fogStart = val; if (this._resource) { this._resource.fogStart = val; } } /** * @zh 雾效结束位置,只适用于线性雾 * @en Global fog end position, only for linear fog */ @visible(function (this: FogInfo) { return this._type === FogType.LINEAR; }) @type(CCFloat) @rangeStep(0.01) @displayOrder(5) get fogEnd () { return this._fogEnd; } set fogEnd (val) { this._fogEnd = val; if (this._resource) { this._resource.fogEnd = val; } } /** * @zh 雾效衰减 * @en Global fog attenuation */ @visible(function (this: FogInfo) { return this._type !== FogType.LINEAR; }) @type(CCFloat) @rangeMin(0.01) @rangeStep(0.01) @displayOrder(6) get fogAtten () { return this._fogAtten; } set fogAtten (val) { this._fogAtten = val; if (this._resource) { this._resource.fogAtten = val; } } /** * @zh 雾效顶部范围,只适用于层级雾 * @en Global fog top range, only for layered fog */ @visible(function (this: FogInfo) { return this._type === FogType.LAYERED; }) @type(CCFloat) @rangeStep(0.01) @displayOrder(7) get fogTop () { return this._fogTop; } set fogTop (val) { this._fogTop = val; if (this._resource) { this._resource.fogTop = val; } } /** * @zh 雾效范围,只适用于层级雾 * @en Global fog range, only for layered fog */ @visible(function (this: FogInfo) { return this._type === FogType.LAYERED; }) @type(CCFloat) @rangeStep(0.01) @displayOrder(8) get fogRange () { return this._fogRange; } set fogRange (val) { this._fogRange = val; if (this._resource) { this._resource.fogRange = val; } } public activate (resource: Fog) { this._resource = resource; this._resource.initialize(this); this._resource.activate(); } } /** * @en Scene level planar shadow related information * @zh 平面阴影相关信息 */ @ccclass('cc.ShadowsInfo') export class ShadowsInfo { @serializable protected _type = ShadowType.Planar; @serializable protected _enabled = false; @serializable protected _normal = new Vec3(0, 1, 0); @serializable protected _distance = 0; @serializable protected _shadowColor = new Color(0, 0, 0, 76); @serializable protected _firstSetCSM = false; @serializable protected _fixedArea = false; @serializable protected _pcf = PCFType.HARD; @serializable protected _bias = 0.00001; @serializable protected _normalBias = 0.0; @serializable protected _near = 0.1; @serializable protected _far = 10.0; @serializable protected _shadowDistance = 100; @serializable protected _invisibleOcclusionRange = 200; @serializable protected _orthoSize = 5; @serializable protected _maxReceived = 4; @serializable protected _size = new Vec2(512, 512); @serializable protected _saturation = 0.75; protected _resource: Shadows | null = null; /** * @en Whether activate planar shadow * @zh 是否启用平面阴影? */ @editable set enabled (val: boolean) { if (this._enabled === val) return; this._enabled = val; if (this._resource) { this._resource.enabled = val; if (val) { this._resource.type = this._type; } } } get enabled () { return this._enabled; } @editable @type(ShadowType) set type (val) { this._type = val; if (this._resource) { this._resource.type = val; } } get type () { return this._type; } /** * @en Shadow color * @zh 阴影颜色 */ @visible(function (this: ShadowsInfo) { return this._type === ShadowType.Planar; }) set shadowColor (val: Color) { this._shadowColor.set(val); if (this._resource) { this._resource.shadowColor = val; } } get shadowColor () { return this._shadowColor; } /** * @en The normal of the plane which receives shadow * @zh 阴影接收平面的法线 */ @visible(function (this: ShadowsInfo) { return this._type === ShadowType.Planar; }) set normal (val: Vec3) { Vec3.copy(this._normal, val); if (this._resource) { this._resource.normal = val; } } get normal () { return this._normal; } /** * @en The distance from coordinate origin to the receiving plane. * @zh 阴影接收平面与原点的距离 */ @type(CCFloat) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.Planar; }) set distance (val: number) { this._distance = val; if (this._resource) { this._resource.distance = val; } } get distance () { return this._distance; } /** * @en Shadow color saturation * @zh 阴影颜色饱和度 */ @editable @range([0.0, 1.0, 0.01]) @slide @type(CCFloat) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap; }) set saturation (val: number) { if (val > 1.0) { this._saturation = val / val; if (this._resource) { this._resource.saturation = val / val; } } else { this._saturation = val; if (this._resource) { this._resource.saturation = val; } } } get saturation () { return this._saturation; } /** * @en The normal of the plane which receives shadow * @zh 阴影接收平面的法线 */ @type(PCFType) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap; }) set pcf (val) { this._pcf = val; if (this._resource) { this._resource.pcf = val; } } get pcf () { return this._pcf; } /** * @en get or set shadow max received * @zh 获取或者设置阴影接收的最大光源数量 */ @type(CCInteger) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap; }) set maxReceived (val: number) { this._maxReceived = val; if (this._resource) { this._resource.maxReceived = val; } } get maxReceived () { return this._maxReceived; } /** * @en get or set shadow map sampler offset * @zh 获取或者设置阴影纹理偏移值 */ @type(CCFloat) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap; }) set bias (val: number) { this._bias = val; if (this._resource) { this._resource.bias = val; } } get bias () { return this._bias; } /** * @en on or off Self-shadowing. * @zh 打开或者关闭自阴影。 */ @type(CCFloat) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap; }) set normalBias (val: number) { this._normalBias = val; if (this._resource) { this._resource.normalBias = val; } } get normalBias () { return this._normalBias; } /** * @en get or set shadow map size * @zh 获取或者设置阴影纹理大小 */ @type(ShadowSize) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap; }) set shadowMapSize (value: number) { this._size.set(value, value); if (this._resource) { this._resource.size.set(value, value); this._resource.shadowMapDirty = true; } } get shadowMapSize () { return this._size.x; } get size () { return this._size; } /** * @en get or set fixed area shadow * @zh 是否是固定区域阴影 */ @type(CCBoolean) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap; }) set fixedArea (val) { this._fixedArea = val; if (this._resource) { this._resource.fixedArea = val; } } get fixedArea () { return this._fixedArea; } /** * @en get or set shadow camera near * @zh 获取或者设置阴影相机近裁剪面 */ @type(CCFloat) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap && this._fixedArea === true; }) set near (val: number) { this._near = val; if (this._resource) { this._resource.near = val; } } get near () { return this._near; } /** * @en get or set shadow camera far * @zh 获取或者设置阴影相机远裁剪面 */ @type(CCFloat) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap && this._fixedArea === true; }) set far (val: number) { this._far = Math.min(val, Shadows.MAX_FAR); if (this._resource) { this._resource.far = this._far; } } get far () { return this._far; } /** * @en get or set shadow camera far * @zh 获取或者设置潜在阴影产生的范围 */ @editable @tooltip('if shadow has been culled, increase this value to fix it') @range([0.0, 2000.0, 0.1]) @slide @type(CCFloat) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap && this._fixedArea === false; }) set invisibleOcclusionRange (val: number) { this._invisibleOcclusionRange = Math.min(val, Shadows.MAX_FAR); if (this._resource) { this._resource.invisibleOcclusionRange = this._invisibleOcclusionRange; } } get invisibleOcclusionRange () { return this._invisibleOcclusionRange; } /** * @en get or set shadow camera far * @zh 获取或者设置潜在阴影产生的范围 */ @editable @tooltip('shadow visible distance: shadow quality is inversely proportional of the magnitude of this value') @range([0.0, 2000.0, 0.1]) @slide @type(CCFloat) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap && this._fixedArea === false; }) set shadowDistance (val: number) { this._shadowDistance = Math.min(val, Shadows.MAX_FAR); if (this._resource) { this._resource.shadowDistance = this._shadowDistance; } } get shadowDistance () { return this._shadowDistance; } /** * @en get or set shadow camera orthoSize * @zh 获取或者设置阴影相机正交大小 */ @type(CCFloat) @visible(function (this: ShadowsInfo) { return this._type === ShadowType.ShadowMap && this._fixedArea === true; }) set orthoSize (val: number) { this._orthoSize = val; if (this._resource) { this._resource.orthoSize = val; } } get orthoSize () { return this._orthoSize; } /** * @en Set plane which receives shadow with the given node's world transformation * @zh 根据指定节点的世界变换设置阴影接收平面的信息 * @param node The node for setting up the plane */ public setPlaneFromNode (node: Node) { node.getWorldRotation(_qt); this.normal = Vec3.transformQuat(_v3, _up, _qt); node.getWorldPosition(_v3); this.distance = Vec3.dot(this._normal, _v3); } public activate (resource: Shadows) { this.pcf = Math.min(this._pcf, PCFType.SOFT_2X); this._resource = resource; if (EDITOR && this._firstSetCSM) { this._resource.firstSetCSM = this._firstSetCSM; // Only the first time render in editor will trigger the auto calculation of shadowDistance legacyCC.director.once(legacyCC.Director.EVENT_AFTER_DRAW, () => { // Sync automatic calculated shadowDistance in renderer this._firstSetCSM = false; if (this._resource) { this.shadowDistance = Math.min(this._resource.shadowDistance, Shadows.MAX_FAR); } }); } this._resource.initialize(this); this._resource.activate(); } } legacyCC.ShadowsInfo = ShadowsInfo; /** * @en All scene related global parameters, it affects all content in the corresponding scene * @zh 各类场景级别的渲染参数,将影响全场景的所有物体 */ @ccclass('cc.SceneGlobals') export class SceneGlobals { /** * @en The environment light information * @zh 场景的环境光照相关信息 */ @serializable @editable public ambient = new AmbientInfo(); /** * @en Scene level planar shadow related information * @zh 平面阴影相关信息 */ @serializable @editable public shadows = new ShadowsInfo(); @serializable public _skybox = new SkyboxInfo(); @editable @serializable public fog = new FogInfo(); /** * @en Skybox related information * @zh 天空盒相关信息 */ @editable @type(SkyboxInfo) get skybox () { return this._skybox; } set skybox (value) { this._skybox = value; } public activate () { const sceneData = legacyCC.director.root.pipeline.pipelineSceneData; this.skybox.activate(sceneData.skybox); this.ambient.activate(sceneData.ambient); this.shadows.activate(sceneData.shadows); this.fog.activate(sceneData.fog); } } legacyCC.SceneGlobals = SceneGlobals;
the_stack
import InternalMouseEvent from '../event/InternalMouseEvent'; import EventObject from '../event/EventObject'; import InternalEvent from '../event/InternalEvent'; import { getClientX, getClientY, isAltDown, isConsumed, isControlDown, isLeftMouseButton, isMetaDown, isMouseEvent, isMultiTouchEvent, isPenEvent, isPopupTrigger, isShiftDown, isTouchEvent, } from '../../util/EventUtils'; import CellState from '../cell/CellState'; import Cell from '../cell/Cell'; import PanningHandler from '../handler/PanningHandler'; import ConnectionHandler from '../handler/ConnectionHandler'; import Point from '../geometry/Point'; import { mixInto } from '../../util/Utils'; import { convertPoint } from '../../util/styleUtils'; import { NONE } from '../../util/Constants'; import Client from '../../Client'; import EventSource from '../event/EventSource'; import CellEditorHandler from '../handler/CellEditorHandler'; import { Graph } from '../Graph'; import TooltipHandler from '../handler/TooltipHandler'; import type { MouseEventListener, MouseListenerSet } from '../../types'; declare module '../Graph' { interface Graph { mouseListeners: MouseListenerSet[]; lastTouchEvent: MouseEvent | null; doubleClickCounter: number; lastTouchCell: Cell | null; fireDoubleClick: boolean | null; tapAndHoldThread: number | null; lastMouseX: number | null; lastMouseY: number | null; isMouseTrigger: boolean | null; ignoreMouseEvents: boolean | null; mouseMoveRedirect: MouseEventListener | null; mouseUpRedirect: MouseEventListener | null; lastEvent: any; // FIXME: Check if this can be more specific - DOM events or mxEventObjects! escapeEnabled: boolean; invokesStopCellEditing: boolean; enterStopsCellEditing: boolean; isMouseDown: boolean; nativeDblClickEnabled: boolean; doubleTapEnabled: boolean; doubleTapTimeout: number; doubleTapTolerance: number; lastTouchX: number; lastTouchY: number; lastTouchTime: number; tapAndHoldEnabled: boolean; tapAndHoldDelay: number; tapAndHoldInProgress: boolean; tapAndHoldValid: boolean; initialTouchX: number; initialTouchY: number; tolerance: number; isNativeDblClickEnabled: () => boolean; getEventTolerance: () => number; setEventTolerance: (tolerance: number) => void; escape: (evt: Event) => void; click: (me: InternalMouseEvent) => boolean; dblClick: (evt: MouseEvent, cell?: Cell | null) => void; tapAndHold: (me: InternalMouseEvent) => void; addMouseListener: (listener: MouseListenerSet) => void; removeMouseListener: (listener: MouseListenerSet) => void; updateMouseEvent: (me: InternalMouseEvent, evtName: string) => InternalMouseEvent; getStateForTouchEvent: (evt: MouseEvent) => CellState | null; isEventIgnored: ( evtName: string, me: InternalMouseEvent, sender: EventSource ) => boolean; isSyntheticEventIgnored: ( evtName: string, me: InternalMouseEvent, sender: any ) => boolean; isEventSourceIgnored: (evtName: string, me: InternalMouseEvent) => boolean; getEventState: (state: CellState) => CellState; fireMouseEvent: ( evtName: string, me: InternalMouseEvent, sender?: EventSource ) => void; consumeMouseEvent: ( evtName: string, me: InternalMouseEvent, sender: EventSource ) => void; fireGestureEvent: (evt: MouseEvent, cell?: Cell | null) => void; sizeDidChange: () => void; isCloneEvent: (evt: MouseEvent) => boolean; isTransparentClickEvent: (evt: MouseEvent) => boolean; isToggleEvent: (evt: MouseEvent) => boolean; isGridEnabledEvent: (evt: MouseEvent) => boolean; isConstrainedEvent: (evt: MouseEvent) => boolean; isIgnoreTerminalEvent: (evt: MouseEvent) => boolean; getPointForEvent: (evt: MouseEvent, addOffset?: boolean) => Point; isEscapeEnabled: () => boolean; setEscapeEnabled: (value: boolean) => void; isInvokesStopCellEditing: () => boolean; setInvokesStopCellEditing: (value: boolean) => void; isEnterStopsCellEditing: () => boolean; setEnterStopsCellEditing: (value: boolean) => void; getCursorForMouseEvent: (me: InternalMouseEvent) => string | null; isSwimlaneSelectionEnabled: () => boolean; } } type PartialGraph = Pick< Graph, | 'fireEvent' | 'isEnabled' | 'getCellAt' | 'isCellSelected' | 'selectCellForEvent' | 'clearSelection' | 'isCellEditable' | 'isEditing' | 'startEditingAtCell' | 'getPlugin' | 'getView' | 'getContainer' | 'getPanDx' | 'getPanDy' | 'getEventSource' | 'setEventSource' | 'isAutoScroll' | 'getGraphBounds' | 'scrollPointToVisible' | 'isIgnoreScrollbars' | 'isTranslateToScrollPosition' | 'isAutoExtend' | 'isEditing' | 'stopEditing' | 'getBorder' | 'getMinimumContainerSize' | 'isResizeContainer' | 'doResizeContainer' | 'isPreferPageSize' | 'isPageVisible' | 'getPreferredPageSize' | 'getMinimumGraphSize' | 'getGridSize' | 'snap' | 'getCursorForCell' | 'paintBackground' | 'updatePageBreaks' | 'isPageBreaksVisible' | 'isSwimlaneSelectionEnabled' | 'getSwimlaneAt' | 'isSwimlane' >; type PartialEvents = Pick< Graph, | 'mouseListeners' | 'lastTouchEvent' | 'doubleClickCounter' | 'lastTouchCell' | 'fireDoubleClick' | 'tapAndHoldThread' | 'lastMouseX' | 'lastMouseY' | 'isMouseTrigger' | 'ignoreMouseEvents' | 'mouseMoveRedirect' | 'mouseUpRedirect' | 'lastEvent' | 'escapeEnabled' | 'invokesStopCellEditing' | 'enterStopsCellEditing' | 'isMouseDown' | 'nativeDblClickEnabled' | 'doubleTapEnabled' | 'doubleTapTimeout' | 'doubleTapTolerance' | 'lastTouchX' | 'lastTouchY' | 'lastTouchTime' | 'tapAndHoldEnabled' | 'tapAndHoldDelay' | 'tapAndHoldInProgress' | 'tapAndHoldValid' | 'initialTouchX' | 'initialTouchY' | 'tolerance' | 'isNativeDblClickEnabled' | 'getEventTolerance' | 'setEventTolerance' | 'escape' | 'click' | 'dblClick' | 'tapAndHold' | 'addMouseListener' | 'removeMouseListener' | 'updateMouseEvent' | 'getStateForTouchEvent' | 'isEventIgnored' | 'isSyntheticEventIgnored' | 'isEventSourceIgnored' | 'getEventState' | 'fireMouseEvent' | 'consumeMouseEvent' | 'fireGestureEvent' | 'sizeDidChange' | 'isCloneEvent' | 'isTransparentClickEvent' | 'isToggleEvent' | 'isGridEnabledEvent' | 'isConstrainedEvent' | 'isIgnoreTerminalEvent' | 'getPointForEvent' | 'isEscapeEnabled' | 'setEscapeEnabled' | 'isInvokesStopCellEditing' | 'setInvokesStopCellEditing' | 'isEnterStopsCellEditing' | 'setEnterStopsCellEditing' | 'getCursorForMouseEvent' >; type PartialType = PartialGraph & PartialEvents; // @ts-expect-error The properties of PartialGraph are defined elsewhere. const EventsMixin: PartialType = { // TODO: Document me! lastTouchEvent: null, doubleClickCounter: 0, lastTouchCell: null, fireDoubleClick: null, tapAndHoldThread: null, lastMouseX: null, lastMouseY: null, isMouseTrigger: null, ignoreMouseEvents: null, mouseMoveRedirect: null, mouseUpRedirect: null, lastEvent: null, // FIXME: Check if this can be more specific - DOM events or mxEventObjects! /** * Specifies if {@link KeyHandler} should invoke {@link escape} when the escape key * is pressed. * @default true */ escapeEnabled: true, /** * If `true`, when editing is to be stopped by way of selection changing, * data in diagram changing or other means stopCellEditing is invoked, and * changes are saved. This is implemented in a focus handler in * {@link CellEditorHandler}. * @default true */ invokesStopCellEditing: true, /** * If `true`, pressing the enter key without pressing control or shift will stop * editing and accept the new value. This is used in {@link CellEditorHandler} to stop * cell editing. Note: You can always use F2 and escape to stop editing. * @default false */ enterStopsCellEditing: false, /** * Holds the state of the mouse button. */ isMouseDown: false, /** * Specifies if native double click events should be detected. * @default true */ nativeDblClickEnabled: true, /** * Specifies if double taps on touch-based devices should be handled as a * double click. * @default true */ doubleTapEnabled: true, /** * Specifies the timeout in milliseconds for double taps and non-native double clicks. * @default 500 */ doubleTapTimeout: 500, /** * Specifies the tolerance in pixels for double taps and double clicks in quirks mode. * @default 25 */ doubleTapTolerance: 25, /** * Holds the x-coordinate of the last touch event for double tap detection. */ lastTouchX: 0, /** * Holds the x-coordinate of the last touch event for double tap detection. */ lastTouchY: 0, /** * Holds the time of the last touch event for double click detection. */ lastTouchTime: 0, /** * Specifies if tap and hold should be used for starting connections on touch-based * devices. * @default true */ tapAndHoldEnabled: true, /** * Specifies the time in milliseconds for a tap and hold. * @default 500 */ tapAndHoldDelay: 500, /** * `True` if the timer for tap and hold events is running. */ tapAndHoldInProgress: false, /** * `True` as long as the timer is running and the touch events * stay within the given {@link tapAndHoldTolerance}. */ tapAndHoldValid: false, /** * Holds the x-coordinate of the initial touch event for tap and hold. */ initialTouchX: 0, /** * Holds the y-coordinate of the initial touch event for tap and hold. */ initialTouchY: 0, /** * Tolerance in pixels for a move to be handled as a single click. * @default 4 */ tolerance: 4, isNativeDblClickEnabled() { return this.nativeDblClickEnabled; }, getEventTolerance() { return this.tolerance; }, setEventTolerance(tolerance: number) { this.tolerance = tolerance; }, /***************************************************************************** * Group: Event processing *****************************************************************************/ /** * Processes an escape keystroke. * * @param evt Mouseevent that represents the keystroke. */ escape(evt) { this.fireEvent(new EventObject(InternalEvent.ESCAPE, { event: evt })); }, /** * Processes a singleclick on an optional cell and fires a {@link click} event. * The click event is fired initially. If the graph is enabled and the * event has not been consumed, then the cell is selected using * {@link selectCellForEvent} or the selection is cleared using * {@link clearSelection}. The events consumed state is set to true if the * corresponding {@link InternalMouseEvent} has been consumed. * * To handle a click event, use the following code. * * ```javascript * graph.addListener(mxEvent.CLICK, function(sender, evt) * { * var e = evt.getProperty('event'); // mouse event * var cell = evt.getProperty('cell'); // cell may be null * * if (cell != null) * { * // Do something useful with cell and consume the event * evt.consume(); * } * }); * ``` * * @param me {@link mxMouseEvent} that represents the single click. */ click(me) { const evt = me.getEvent(); let cell = me.getCell(); const mxe = new EventObject(InternalEvent.CLICK, { event: evt, cell }); if (me.isConsumed()) { mxe.consume(); } this.fireEvent(mxe); if (this.isEnabled() && !isConsumed(evt) && !mxe.isConsumed()) { if (cell) { if (this.isTransparentClickEvent(evt)) { let active = false; const tmp = this.getCellAt( me.graphX, me.graphY, null, false, false, (state: CellState) => { const selected = this.isCellSelected(state.cell); active = active || selected; return ( !active || selected || (state.cell !== cell && state.cell.isAncestor(cell)) ); } ); if (tmp) { cell = tmp; } } } else if (this.isSwimlaneSelectionEnabled()) { cell = this.getSwimlaneAt(me.getGraphX(), me.getGraphY()); if (cell != null && (!this.isToggleEvent(evt) || !isAltDown(evt))) { let temp: Cell | null = cell; let swimlanes = []; while (temp != null) { temp = <Cell>temp.getParent(); const state = this.getView().getState(temp); if (this.isSwimlane(temp) && state != null) { swimlanes.push(temp); } } // Selects ancestors for selected swimlanes if (swimlanes.length > 0) { swimlanes = swimlanes.reverse(); swimlanes.splice(0, 0, cell); swimlanes.push(cell); for (let i = 0; i < swimlanes.length - 1; i += 1) { if (this.isCellSelected(swimlanes[i])) { cell = swimlanes[this.isToggleEvent(evt) ? i : i + 1]; } } } } } if (cell) { this.selectCellForEvent(cell, evt); } else if (!this.isToggleEvent(evt)) { this.clearSelection(); } } return false; }, /** * Processes a doubleclick on an optional cell and fires a {@link dblclick} * event. The event is fired initially. If the graph is enabled and the * event has not been consumed, then {@link edit} is called with the given * cell. The event is ignored if no cell was specified. * * Example for overriding this method. * * ```javascript * graph.dblClick = function(evt, cell) * { * var mxe = new mxEventObject(mxEvent.DOUBLE_CLICK, 'event', evt, 'cell', cell); * this.fireEvent(mxe); * * if (this.isEnabled() && !mxEvent.isConsumed(evt) && !mxe.isConsumed()) * { * mxUtils.alert('Hello, World!'); * mxe.consume(); * } * } * ``` * * Example listener for this event. * * ```javascript * graph.addListener(mxEvent.DOUBLE_CLICK, function(sender, evt) * { * var cell = evt.getProperty('cell'); * // do something with the cell and consume the * // event to prevent in-place editing from start * }); * ``` * * @param evt Mouseevent that represents the doubleclick. * @param cell Optional {@link Cell} under the mousepointer. */ dblClick(evt, cell = null) { const mxe = new EventObject(InternalEvent.DOUBLE_CLICK, { event: evt, cell }); this.fireEvent(mxe); // Handles the event if it has not been consumed if ( this.isEnabled() && !isConsumed(evt) && !mxe.isConsumed() && cell && this.isCellEditable(cell) && !this.isEditing(cell) ) { this.startEditingAtCell(cell, evt); InternalEvent.consume(evt); } }, /** * Handles the {@link InternalMouseEvent} by highlighting the {@link CellState}. * * @param me {@link mxMouseEvent} that represents the touch event. * @param state Optional {@link CellState} that is associated with the event. */ tapAndHold(me) { const evt = me.getEvent(); const mxe = new EventObject(InternalEvent.TAP_AND_HOLD, { event: evt, cell: me.getCell() }); const panningHandler = this.getPlugin('PanningHandler') as PanningHandler; const connectionHandler = this.getPlugin('ConnectionHandler') as ConnectionHandler; // LATER: Check if event should be consumed if me is consumed this.fireEvent(mxe); if (mxe.isConsumed()) { // Resets the state of the panning handler panningHandler.panningTrigger = false; } // Handles the event if it has not been consumed if ( this.isEnabled() && !isConsumed(evt) && !mxe.isConsumed() && connectionHandler.isEnabled() ) { const cell = connectionHandler.marker.getCell(me); if (cell) { const state = this.getView().getState(cell); if (state) { connectionHandler.marker.currentColor = connectionHandler.marker.validColor; connectionHandler.marker.markedState = state; connectionHandler.marker.mark(); connectionHandler.first = new Point(me.getGraphX(), me.getGraphY()); connectionHandler.edgeState = connectionHandler.createEdgeState(me); connectionHandler.previous = state; connectionHandler.fireEvent( new EventObject(InternalEvent.START, { state: connectionHandler.previous }) ); } } } }, /***************************************************************************** * Group: Graph events *****************************************************************************/ /** * Adds a listener to the graph event dispatch loop. The listener * must implement the mouseDown, mouseMove and mouseUp methods * as shown in the {@link InternalMouseEvent} class. * * @param listener Listener to be added to the graph event listeners. */ addMouseListener(listener) { this.mouseListeners.push(listener); }, /** * Removes the specified graph listener. * * @param listener Listener to be removed from the graph event listeners. */ removeMouseListener(listener) { for (let i = 0; i < this.mouseListeners.length; i += 1) { if (this.mouseListeners[i] === listener) { this.mouseListeners.splice(i, 1); break; } } }, /** * Sets the graphX and graphY properties if the given {@link InternalMouseEvent} if * required and returned the event. * * @param me {@link mxMouseEvent} to be updated. * @param evtName Name of the mouse event. */ updateMouseEvent(me, evtName) { const pt = convertPoint(this.getContainer(), me.getX(), me.getY()); me.graphX = pt.x - this.getPanDx(); me.graphY = pt.y - this.getPanDy(); // Searches for rectangles using method if native hit detection is disabled on shape if (!me.getCell() && this.isMouseDown && evtName === InternalEvent.MOUSE_MOVE) { const cell = this.getCellAt(pt.x, pt.y, null, true, true, (state: CellState) => { return ( !state.shape || state.shape.paintBackground !== this.paintBackground || state.style.pointerEvents || state.shape.fill !== NONE ); }); me.state = cell ? this.getView().getState(cell) : null; } return me; }, /** * Returns the state for the given touch event. */ getStateForTouchEvent(evt) { const x = getClientX(evt); const y = getClientY(evt); // Dispatches the drop event to the graph which // consumes and executes the source function const pt = convertPoint(this.getContainer(), x, y); const cell = this.getCellAt(pt.x, pt.y); return cell ? this.getView().getState(cell) : null; }, /** * Returns true if the event should be ignored in {@link fireMouseEvent}. */ isEventIgnored(evtName, me, sender) { const mouseEvent = isMouseEvent(me.getEvent()); let result = false; // Drops events that are fired more than once if (me.getEvent() === this.lastEvent) { result = true; } else { this.lastEvent = me.getEvent(); } // Installs event listeners to capture the complete gesture from the event source // for non-MS touch events as a workaround for all events for the same geture being // fired from the event source even if that was removed from the DOM. const eventSource = this.getEventSource(); if (eventSource && evtName !== InternalEvent.MOUSE_MOVE) { InternalEvent.removeGestureListeners( eventSource, null, this.mouseMoveRedirect, this.mouseUpRedirect ); this.mouseMoveRedirect = null; this.mouseUpRedirect = null; this.setEventSource(null); } else if (!Client.IS_GC && eventSource && me.getSource() !== eventSource) { result = true; } else if ( eventSource && Client.IS_TOUCH && evtName === InternalEvent.MOUSE_DOWN && !mouseEvent && !isPenEvent(me.getEvent()) ) { this.setEventSource(me.getSource()); (this.mouseMoveRedirect = (evt: MouseEvent) => { this.fireMouseEvent( InternalEvent.MOUSE_MOVE, new InternalMouseEvent(evt, this.getStateForTouchEvent(evt)) ); }), (this.mouseUpRedirect = (evt: MouseEvent) => { this.fireMouseEvent( InternalEvent.MOUSE_UP, new InternalMouseEvent(evt, this.getStateForTouchEvent(evt)) ); }), InternalEvent.addGestureListeners( eventSource, null, this.mouseMoveRedirect, this.mouseUpRedirect ); } // Factored out the workarounds for FF to make it easier to override/remove // Note this method has side-effects! if (this.isSyntheticEventIgnored(evtName, me, sender)) { result = true; } // Never fires mouseUp/-Down for double clicks if ( !isPopupTrigger(this.lastEvent) && evtName !== InternalEvent.MOUSE_MOVE && this.lastEvent.detail === 2 ) { return true; } // Filters out of sequence events or mixed event types during a gesture if (evtName === InternalEvent.MOUSE_UP && this.isMouseDown) { this.isMouseDown = false; } else if (evtName === InternalEvent.MOUSE_DOWN && !this.isMouseDown) { this.isMouseDown = true; this.isMouseTrigger = mouseEvent; } // Drops mouse events that are fired during touch gestures as a workaround for Webkit // and mouse events that are not in sync with the current internal button state else if ( !result && (((!Client.IS_FF || evtName !== InternalEvent.MOUSE_MOVE) && this.isMouseDown && this.isMouseTrigger !== mouseEvent) || (evtName === InternalEvent.MOUSE_DOWN && this.isMouseDown) || (evtName === InternalEvent.MOUSE_UP && !this.isMouseDown)) ) { result = true; } if (!result && evtName === InternalEvent.MOUSE_DOWN) { this.lastMouseX = me.getX(); this.lastMouseY = me.getY(); } return result; }, /** * Hook for ignoring synthetic mouse events after touchend in Firefox. */ isSyntheticEventIgnored(evtName, me, sender) { let result = false; const mouseEvent = isMouseEvent(me.getEvent()); // LATER: This does not cover all possible cases that can go wrong in FF if (this.ignoreMouseEvents && mouseEvent && evtName !== InternalEvent.MOUSE_MOVE) { this.ignoreMouseEvents = evtName !== InternalEvent.MOUSE_UP; result = true; } else if (Client.IS_FF && !mouseEvent && evtName === InternalEvent.MOUSE_UP) { this.ignoreMouseEvents = true; } return result; }, /** * Returns true if the event should be ignored in {@link fireMouseEvent}. This * implementation returns true for select, option and input (if not of type * checkbox, radio, button, submit or file) event sources if the event is not * a mouse event or a left mouse button press event. * * @param evtName The name of the event. * @param me {@link mxMouseEvent} that should be ignored. */ isEventSourceIgnored(evtName, me) { const source = me.getSource(); if (!source) return true; // @ts-ignore nodeName could exist const name = source.nodeName ? source.nodeName.toLowerCase() : ''; const candidate = !isMouseEvent(me.getEvent()) || isLeftMouseButton(me.getEvent()); return ( evtName === InternalEvent.MOUSE_DOWN && candidate && (name === 'select' || name === 'option' || (name === 'input' && // @ts-ignore type could exist source.type !== 'checkbox' && // @ts-ignore type could exist source.type !== 'radio' && // @ts-ignore type could exist source.type !== 'button' && // @ts-ignore type could exist source.type !== 'submit' && // @ts-ignore type could exist source.type !== 'file')) ); }, /** * Returns the {@link CellState} to be used when firing the mouse event for the * given state. This implementation returns the given state. * * {@link CellState} - State whose event source should be returned. */ getEventState(state) { return state; }, /** * Dispatches the given event in the graph event dispatch loop. Possible * event names are {@link InternalEvent.MOUSE_DOWN}, {@link InternalEvent.MOUSE_MOVE} and * {@link InternalEvent.MOUSE_UP}. All listeners are invoked for all events regardless * of the consumed state of the event. * * @param evtName String that specifies the type of event to be dispatched. * @param me {@link mxMouseEvent} to be fired. * @param sender Optional sender argument. Default is `this`. */ fireMouseEvent(evtName, me, sender) { sender = sender ?? (this as Graph); if (this.isEventSourceIgnored(evtName, me)) { const tooltipHandler = this.getPlugin('TooltipHandler') as TooltipHandler; if (tooltipHandler) { tooltipHandler.hide(); } return; } // Updates the graph coordinates in the event me = this.updateMouseEvent(me, evtName); // Detects and processes double taps for touch-based devices which do not have native double click events // or where detection of double click is not always possible (quirks, IE10+). Note that this can only handle // double clicks on cells because the sequence of events in IE prevents detection on the background, it fires // two mouse ups, one of which without a cell but no mousedown for the second click which means we cannot // detect which mouseup(s) are part of the first click, ie we do not know when the first click ends. if ( (!this.nativeDblClickEnabled && !isPopupTrigger(me.getEvent())) || (this.doubleTapEnabled && Client.IS_TOUCH && (isTouchEvent(me.getEvent()) || isPenEvent(me.getEvent()))) ) { const currentTime = new Date().getTime(); if (evtName === InternalEvent.MOUSE_DOWN) { if ( this.lastTouchEvent && this.lastTouchEvent !== me.getEvent() && currentTime - this.lastTouchTime < this.doubleTapTimeout && Math.abs(this.lastTouchX - me.getX()) < this.doubleTapTolerance && Math.abs(this.lastTouchY - me.getY()) < this.doubleTapTolerance && this.doubleClickCounter < 2 ) { this.doubleClickCounter += 1; let doubleClickFired = false; if (evtName === InternalEvent.MOUSE_UP) { if (me.getCell() === this.lastTouchCell && this.lastTouchCell) { this.lastTouchTime = 0; const cell = this.lastTouchCell; this.lastTouchCell = null; this.dblClick(me.getEvent(), cell); doubleClickFired = true; } } else { this.fireDoubleClick = true; this.lastTouchTime = 0; } if (doubleClickFired) { InternalEvent.consume(me.getEvent()); return; } } else if (!this.lastTouchEvent || this.lastTouchEvent !== me.getEvent()) { this.lastTouchCell = me.getCell(); this.lastTouchX = me.getX(); this.lastTouchY = me.getY(); this.lastTouchTime = currentTime; this.lastTouchEvent = me.getEvent(); this.doubleClickCounter = 0; } } else if ( (this.isMouseDown || evtName === InternalEvent.MOUSE_UP) && this.fireDoubleClick ) { this.fireDoubleClick = false; const cell = this.lastTouchCell; this.lastTouchCell = null; this.isMouseDown = false; // Workaround for Chrome/Safari not firing native double click events for double touch on background const valid = cell || ((isTouchEvent(me.getEvent()) || isPenEvent(me.getEvent())) && (Client.IS_GC || Client.IS_SF)); if ( valid && Math.abs(this.lastTouchX - me.getX()) < this.doubleTapTolerance && Math.abs(this.lastTouchY - me.getY()) < this.doubleTapTolerance ) { this.dblClick(me.getEvent(), cell); } else { InternalEvent.consume(me.getEvent()); } return; } } if (!this.isEventIgnored(evtName, me, sender)) { const state = me.getState(); // Updates the event state via getEventState me.state = state ? this.getEventState(state) : null; this.fireEvent( new EventObject(InternalEvent.FIRE_MOUSE_EVENT, { eventName: evtName, event: me }) ); if ( Client.IS_SF || Client.IS_GC || me.getEvent().target !== this.getContainer() ) { const container = this.getContainer(); if ( evtName === InternalEvent.MOUSE_MOVE && this.isMouseDown && this.isAutoScroll() && !isMultiTouchEvent(me.getEvent()) ) { this.scrollPointToVisible(me.getGraphX(), me.getGraphY(), this.isAutoExtend()); } else if ( evtName === InternalEvent.MOUSE_UP && this.isIgnoreScrollbars() && this.isTranslateToScrollPosition() && (container.scrollLeft !== 0 || container.scrollTop !== 0) ) { const s = this.getView().scale; const tr = this.getView().translate; this.getView().setTranslate( tr.x - container.scrollLeft / s, tr.y - container.scrollTop / s ); container.scrollLeft = 0; container.scrollTop = 0; } const mouseListeners = this.mouseListeners; // Does not change returnValue in Opera if (!me.getEvent().preventDefault) { me.getEvent().returnValue = true; } for (const l of mouseListeners) { if (evtName === InternalEvent.MOUSE_DOWN) { l.mouseDown(sender, me); } else if (evtName === InternalEvent.MOUSE_MOVE) { l.mouseMove(sender, me); } else if (evtName === InternalEvent.MOUSE_UP) { l.mouseUp(sender, me); } } // Invokes the click handler if (evtName === InternalEvent.MOUSE_UP) { this.click(me); } } // Detects tapAndHold events using a timer if ( (isTouchEvent(me.getEvent()) || isPenEvent(me.getEvent())) && evtName === InternalEvent.MOUSE_DOWN && this.tapAndHoldEnabled && !this.tapAndHoldInProgress ) { this.tapAndHoldInProgress = true; this.initialTouchX = me.getGraphX(); this.initialTouchY = me.getGraphY(); const handler = () => { if (this.tapAndHoldValid) { this.tapAndHold(me); } this.tapAndHoldInProgress = false; this.tapAndHoldValid = false; }; if (this.tapAndHoldThread) { window.clearTimeout(this.tapAndHoldThread); } this.tapAndHoldThread = window.setTimeout(handler, this.tapAndHoldDelay); this.tapAndHoldValid = true; } else if (evtName === InternalEvent.MOUSE_UP) { this.tapAndHoldInProgress = false; this.tapAndHoldValid = false; } else if (this.tapAndHoldValid) { this.tapAndHoldValid = Math.abs(this.initialTouchX - me.getGraphX()) < this.tolerance && Math.abs(this.initialTouchY - me.getGraphY()) < this.tolerance; } const cellEditor = this.getPlugin('CellEditorHandler') as CellEditorHandler; // Stops editing for all events other than from cellEditor if ( evtName === InternalEvent.MOUSE_DOWN && this.isEditing() && !cellEditor.isEventSource(me.getEvent()) ) { this.stopEditing(!this.isInvokesStopCellEditing()); } this.consumeMouseEvent(evtName, me, sender); } }, /** * Consumes the given {@link InternalMouseEvent} if it's a touchStart event. */ consumeMouseEvent(evtName, me, sender) { sender = sender ?? this; // Workaround for duplicate click in Windows 8 with Chrome/FF/Opera with touch if (evtName === InternalEvent.MOUSE_DOWN && isTouchEvent(me.getEvent())) { me.consume(false); } }, /** * Dispatches a {@link InternalEvent.GESTURE} event. The following example will resize the * cell under the mouse based on the scale property of the native touch event. * * ```javascript * graph.addListener(mxEvent.GESTURE, function(sender, eo) * { * var evt = eo.getProperty('event'); * var state = graph.view.getState(eo.getProperty('cell')); * * if (graph.isEnabled() && graph.isCellResizable(state.cell) && Math.abs(1 - evt.scale) > 0.2) * { * var scale = graph.view.scale; * var tr = graph.view.translate; * * var w = state.width * evt.scale; * var h = state.height * evt.scale; * var x = state.x - (w - state.width) / 2; * var y = state.y - (h - state.height) / 2; * * var bounds = new mxRectangle(graph.snap(x / scale) - tr.x, * graph.snap(y / scale) - tr.y, graph.snap(w / scale), graph.snap(h / scale)); * graph.resizeCell(state.cell, bounds); * eo.consume(); * } * }); * ``` * * @param evt Gestureend event that represents the gesture. * @param cell Optional {@link Cell} associated with the gesture. */ fireGestureEvent(evt, cell = null) { // Resets double tap event handling when gestures take place this.lastTouchTime = 0; this.fireEvent(new EventObject(InternalEvent.GESTURE, { event: evt, cell })); }, /** * Called when the size of the graph has changed. This implementation fires * a {@link size} event after updating the clipping region of the SVG element in * SVG-bases browsers. */ sizeDidChange() { const bounds = this.getGraphBounds(); const border = this.getBorder(); let width = Math.max(0, bounds.x) + bounds.width + 2 * border; let height = Math.max(0, bounds.y) + bounds.height + 2 * border; const minimumContainerSize = this.getMinimumContainerSize(); if (minimumContainerSize) { width = Math.max(width, minimumContainerSize.width); height = Math.max(height, minimumContainerSize.height); } if (this.isResizeContainer()) { this.doResizeContainer(width, height); } if (this.isPreferPageSize() || this.isPageVisible()) { const size = this.getPreferredPageSize( bounds, Math.max(1, width), Math.max(1, height) ); width = size.width * this.getView().scale; height = size.height * this.getView().scale; } const minimumGraphSize = this.getMinimumGraphSize(); if (minimumGraphSize) { width = Math.max(width, minimumGraphSize.width * this.getView().scale); height = Math.max(height, minimumGraphSize.height * this.getView().scale); } width = Math.ceil(width); height = Math.ceil(height); // @ts-ignore const root = this.getView().getDrawPane().ownerSVGElement; if (root) { root.style.minWidth = `${Math.max(1, width)}px`; root.style.minHeight = `${Math.max(1, height)}px`; root.style.width = '100%'; root.style.height = '100%'; } this.updatePageBreaks(this.isPageBreaksVisible(), width, height); this.fireEvent(new EventObject(InternalEvent.SIZE, { bounds })); }, /***************************************************************************** * Group: Graph display *****************************************************************************/ /** * Returns true if the given event is a clone event. This implementation * returns true if control is pressed. */ isCloneEvent(evt) { return isControlDown(evt); }, /** * Hook for implementing click-through behaviour on selected cells. If this * returns true the cell behind the selected cell will be selected. This * implementation returns false; */ isTransparentClickEvent(evt) { return false; }, /** * Returns true if the given event is a toggle event. This implementation * returns true if the meta key (Cmd) is pressed on Macs or if control is * pressed on any other platform. */ isToggleEvent(evt) { return Client.IS_MAC ? isMetaDown(evt) : isControlDown(evt); }, /** * Returns true if the given mouse event should be aligned to the grid. */ isGridEnabledEvent(evt) { return !isAltDown(evt); }, /** * Returns true if the given mouse event should be aligned to the grid. */ isConstrainedEvent(evt) { return isShiftDown(evt); }, /** * Returns true if the given mouse event should not allow any connections to be * made. This implementation returns false. */ isIgnoreTerminalEvent(evt) { return false; }, /** * Returns an {@link Point} representing the given event in the unscaled, * non-translated coordinate space of {@link container} and applies the grid. * * @param evt Mousevent that contains the mouse pointer location. * @param addOffset Optional boolean that specifies if the position should be * offset by half of the {@link gridSize}. Default is `true`. */ getPointForEvent(evt, addOffset = true) { const p = convertPoint(this.getContainer(), getClientX(evt), getClientY(evt)); const s = this.getView().scale; const tr = this.getView().translate; const off = addOffset ? this.getGridSize() / 2 : 0; p.x = this.snap(p.x / s - tr.x - off); p.y = this.snap(p.y / s - tr.y - off); return p; }, /***************************************************************************** * Group: Graph behaviour *****************************************************************************/ /** * Returns {@link escapeEnabled}. */ isEscapeEnabled() { return this.escapeEnabled; }, /** * Sets {@link escapeEnabled}. * * @param enabled Boolean indicating if escape should be enabled. */ setEscapeEnabled(value) { this.escapeEnabled = value; }, /** * Returns {@link invokesStopCellEditing}. */ isInvokesStopCellEditing() { return this.invokesStopCellEditing; }, /** * Sets {@link invokesStopCellEditing}. */ setInvokesStopCellEditing(value) { this.invokesStopCellEditing = value; }, /** * Returns {@link enterStopsCellEditing}. */ isEnterStopsCellEditing() { return this.enterStopsCellEditing; }, /** * Sets {@link enterStopsCellEditing}. */ setEnterStopsCellEditing(value) { this.enterStopsCellEditing = value; }, /***************************************************************************** * Group: Graph appearance *****************************************************************************/ /** * Returns the cursor value to be used for the CSS of the shape for the * given event. This implementation calls {@link getCursorForCell}. * * @param me {@link mxMouseEvent} whose cursor should be returned. */ getCursorForMouseEvent(me) { const cell = me.getCell(); return cell ? this.getCursorForCell(cell) : null; }, }; mixInto(Graph)(EventsMixin);
the_stack
import { grpc } from '@improbable-eng/grpc-web' import { Repeater } from '@repeaterjs/repeater' import { Archive as _Archive, ArchiveConfig as _ArchiveConfig, ArchiveRenew as _ArchiveRenew, ArchiveRequest, ArchivesRequest, ArchivesResponse, ArchiveStatus as _ArchiveStatus, ArchiveStatusMap as _ArchiveStatusMap, ArchiveWatchRequest, ArchiveWatchResponse, CreateRequest, CreateResponse as _CreateResponse, DealInfo as _DealInfo, DefaultArchiveConfigRequest, DefaultArchiveConfigResponse, LinksRequest, LinksResponse, ListIpfsPathRequest, ListIpfsPathResponse, ListPathRequest, ListPathResponse, ListRequest, ListResponse, Metadata as _Metadata, MovePathRequest, PathItem as _PathItem, PullIpfsPathRequest, PullIpfsPathResponse, PullPathAccessRolesRequest, PullPathAccessRolesResponse, PullPathRequest, PullPathResponse, PushPathAccessRolesRequest, PushPathRequest, PushPathResponse, PushPathsRequest, PushPathsResponse, RemovePathRequest, RemovePathResponse as _RemovePathResponse, RemoveRequest, Root as _Root, RootRequest, RootResponse, SetDefaultArchiveConfigRequest, SetPathRequest, } from '@textile/buckets-grpc/api/bucketsd/pb/bucketsd_pb' import { APIService, APIServiceClient, BidirectionalStream, Status, } from '@textile/buckets-grpc/api/bucketsd/pb/bucketsd_pb_service' import { Context, ContextInterface } from '@textile/context' import { GrpcConnection } from '@textile/grpc-connection' import { WebsocketTransport } from '@textile/grpc-transport' import CID from 'cids' import drain from 'it-drain' import log from 'loglevel' // @ts-expect-error: missing types import paramap from 'paramap-it' import { AbortError, Archive, ArchiveConfig, ArchiveDealInfo, ArchiveOptions, ArchiveRenew, Archives, ArchiveStatus, BuckMetadata, CreateResponse, Links, Path, PathAccessRole, PathItem, PushOptions, PushPathResult, PushPathsResult, RemovePathOptions, RemovePathResponse, Root, } from '../types' import { File, normaliseInput } from './normalize' export { File } const logger = log.getLogger('buckets-api') function fromPbRootObject(root: _Root): Root { return { key: root.getKey(), name: root.getName(), path: root.getPath(), createdAt: root.getCreatedAt(), updatedAt: root.getUpdatedAt(), thread: root.getThread(), } } function fromPbRootObjectNullable(root?: _Root): Root | undefined { if (!root) return return fromPbRootObject(root) } function fromPbMetadata(metadata?: _Metadata): BuckMetadata | undefined { if (!metadata) return const roles = metadata.getRolesMap() const typedRoles = new Map() roles.forEach((entry, key) => typedRoles.set(key, entry)) const response: BuckMetadata = { updatedAt: metadata.getUpdatedAt(), roles: typedRoles, } return response } export const CHUNK_SIZE = 1024 function fromPbPathItem(item: _PathItem): PathItem { const list = item.getItemsList() return { cid: item.getCid(), name: item.getName(), path: item.getPath(), size: item.getSize(), isDir: item.getIsDir(), items: list ? list.map(fromPbPathItem) : [], count: item.getItemsCount(), metadata: fromPbMetadata(item.getMetadata()), } } function fromPbPathItemNullable(item?: _PathItem): PathItem | undefined { if (!item) return return fromPbPathItem(item) } function fromProtoArchiveRenew(item: _ArchiveRenew.AsObject): ArchiveRenew { return { ...item } } function fromProtoArchiveConfig(item: _ArchiveConfig.AsObject): ArchiveConfig { return { ...item, countryCodes: item.countryCodesList, excludedMiners: item.excludedMinersList, trustedMiners: item.trustedMinersList, renew: item.renew ? fromProtoArchiveRenew(item.renew) : undefined, } } function toProtoArchiveConfig(config: ArchiveConfig): _ArchiveConfig { const protoConfig = new _ArchiveConfig() protoConfig.setCountryCodesList(config.countryCodes) protoConfig.setDealMinDuration(config.dealMinDuration) protoConfig.setDealStartOffset(config.dealStartOffset) protoConfig.setExcludedMinersList(config.excludedMiners) protoConfig.setFastRetrieval(config.fastRetrieval) protoConfig.setMaxPrice(config.maxPrice) protoConfig.setRepFactor(config.repFactor) protoConfig.setTrustedMinersList(config.trustedMiners) protoConfig.setVerifiedDeal(config.verifiedDeal) if (config.renew) { const renew = new _ArchiveRenew() renew.setEnabled(config.renew.enabled) renew.setThreshold(config.renew.threshold) protoConfig.setRenew(renew) } return protoConfig } function fromPbDealInfo(item: _DealInfo.AsObject): ArchiveDealInfo { return { ...item } } function fromPbArchiveStatus( item: _ArchiveStatusMap[keyof _ArchiveStatusMap], ): ArchiveStatus { switch (item) { case _ArchiveStatus.ARCHIVE_STATUS_CANCELED: return ArchiveStatus.Canceled case _ArchiveStatus.ARCHIVE_STATUS_EXECUTING: return ArchiveStatus.Executing case _ArchiveStatus.ARCHIVE_STATUS_FAILED: return ArchiveStatus.Failed case _ArchiveStatus.ARCHIVE_STATUS_QUEUED: return ArchiveStatus.Queued case _ArchiveStatus.ARCHIVE_STATUS_SUCCESS: return ArchiveStatus.Success case _ArchiveStatus.ARCHIVE_STATUS_UNSPECIFIED: return ArchiveStatus.Unspecified default: throw new Error('unknown status') } } function fromPbArchive(item: _Archive.AsObject): Archive { return { ...item, // TODO: standardize units coming from server. createdAt: new Date(item.createdAt * 1000), status: fromPbArchiveStatus(item.archiveStatus), dealInfo: item.dealInfoList.map(fromPbDealInfo), } } /** * Ensures that a Root | string | undefined is converted into a string */ async function ensureRootString( api: GrpcConnection, key: string, root?: Root | string, ctx?: ContextInterface, ): Promise<string> { if (root) { return typeof root === 'string' ? root : root.path } else { /* eslint-disable @typescript-eslint/no-use-before-define */ const root = await bucketsRoot(api, key, ctx) return root?.path ?? '' } } export function* genChunks( value: Uint8Array, size: number, ): Generator<Uint8Array, any, undefined> { return yield* Array.from(Array(Math.ceil(value.byteLength / size)), (_, i) => value.slice(i * size, i * size + size), ) } /** * Creates a new bucket. * @public * @param name Human-readable bucket name. It is only meant to help identify a bucket in a UI and is not unique. * @param isPrivate encrypt the bucket contents (default `false`) * @param cid (optional) Bootstrap the bucket with a UnixFS Cid from the IPFS network * @example * Creates a Bucket called "app-name-files" * ```typescript * import { Buckets } from '@textile/hub' * * const create = async (buckets: Buckets) => { * return buckets.create("app-name-files") * } * ``` * * @internal */ export async function bucketsCreate( api: GrpcConnection, name: string, isPrivate = false, cid?: string, ctx?: ContextInterface, ): Promise<CreateResponse> { logger.debug('create request') const req = new CreateRequest() req.setName(name) if (cid) { req.setBootstrapCid(cid) } req.setPrivate(isPrivate) const res: _CreateResponse = await api.unary(APIService.Create, req, ctx) const links = res.getLinks() return { seed: res.getSeed_asU8(), seedCid: res.getSeedCid(), root: fromPbRootObjectNullable(res.getRoot()), links: links ? links.toObject() : undefined, } } /** * Returns the bucket root CID * @param key Unique (IPNS compatible) identifier key for a bucket. * * @internal */ export async function bucketsRoot( api: GrpcConnection, key: string, ctx?: ContextInterface, ): Promise<Root | undefined> { logger.debug('root request') const req = new RootRequest() req.setKey(key) const res: RootResponse = await api.unary(APIService.Root, req, ctx) return fromPbRootObjectNullable(res.getRoot()) } /** * Returns a list of bucket links. * @param key Unique (IPNS compatible) identifier key for a bucket. * @example * Generate the HTTP, IPNS, and IPFS links for a Bucket * ```typescript * import { Buckets } from '@textile/hub' * * const getLinks = async (buckets: Buckets) => { * const links = buckets.links(bucketKey) * return links.ipfs * } * * const getIpfs = async (buckets: Buckets) => { * const links = buckets.links(bucketKey) * return links.ipfs * } * ``` * * @internal */ export async function bucketsLinks( api: GrpcConnection, key: string, path: string, ctx?: ContextInterface, ): Promise<Links> { logger.debug('link request') const req = new LinksRequest() req.setKey(key) req.setPath(path) const res: LinksResponse = await api.unary(APIService.Links, req, ctx) return res.toObject() } /** * Returns a list of all bucket roots. * @example * Find an existing Bucket named "app-name-files" * ```typescript * import { Buckets } from '@textile/hub' * * const exists = async (buckets: Buckets) => { * const roots = await buckets.list(); * return roots.find((bucket) => bucket.name === "app-name-files") * } * ``` * * @internal */ export async function bucketsList( api: GrpcConnection, ctx?: ContextInterface, ): Promise<Array<Root>> { logger.debug('list request') const req = new ListRequest() const res: ListResponse = await api.unary(APIService.List, req, ctx) const roots = res.getRootsList() const map = roots ? roots.map((m) => m).map((m) => fromPbRootObject(m)) : [] return map } /** * Returns information about a bucket path. * @param key Unique (IPNS compatible) identifier key for a bucket. * @param path A file/object (sub)-path within a bucket. * * @internal */ export async function bucketsListPath( api: GrpcConnection, key: string, path: string, ctx?: ContextInterface, ): Promise<Path> { logger.debug('list path request') const req = new ListPathRequest() req.setKey(key) req.setPath(path) const res: ListPathResponse = await api.unary(APIService.ListPath, req, ctx) return { item: fromPbPathItemNullable(res.getItem()), root: fromPbRootObjectNullable(res.getRoot()), } } /** * listIpfsPath returns items at a particular path in a UnixFS path living in the IPFS network. * @param path UnixFS path * * @internal */ export async function bucketsListIpfsPath( api: GrpcConnection, path: string, ctx?: ContextInterface, ): Promise<PathItem | undefined> { logger.debug('list path request') const req = new ListIpfsPathRequest() req.setPath(path) const res: ListIpfsPathResponse = await api.unary( APIService.ListIpfsPath, req, ctx, ) return fromPbPathItemNullable(res.getItem()) } /** * Move a file or subpath to a new path. * @internal */ export async function bucketsMovePath( api: GrpcConnection, key: string, fromPath: string, toPath: string, ctx?: ContextInterface, ): Promise<void> { const request = new MovePathRequest() request.setKey(key) request.setFromPath(fromPath) request.setToPath(toPath) await api.unary(APIService.MovePath, request, ctx) } /** * Pushes a file to a bucket path. * @param key Unique (IPNS compatible) identifier key for a bucket. * @param path A file/object (sub)-path within a bucket. * @param input The input file/stream/object. * @param opts Options to control response stream. * @remarks * This will return the resolved path and the bucket's new root path. * @example * Push a file to the root of a bucket * ```typescript * import { Buckets } from '@textile/hub' * * const pushFile = async (content: string, bucketKey: string) => { * const file = { path: '/index.html', content: Buffer.from(content) } * return await buckets.pushPath(bucketKey!, 'index.html', file) * } * ``` * @internal */ export async function bucketsPushPath( api: GrpcConnection, key: string, path: string, input: any, opts?: PushOptions, ctx?: ContextInterface, ): Promise<PushPathResult> { return new Promise<PushPathResult>(async (resolve, reject) => { // Only process the first input if there are more than one const source: File | undefined = (await normaliseInput(input).next()).value if (!source) { return reject(AbortError) } const clientjs = new APIServiceClient(api.serviceHost, api.rpcOptions) const metadata = { ...api.context.toJSON(), ...ctx?.toJSON() } const stream: BidirectionalStream< PushPathRequest, PushPathResponse > = clientjs.pushPath(metadata) if (opts?.signal !== undefined) { opts.signal.addEventListener('abort', () => { stream.cancel() return reject(AbortError) }) } stream.on('data', (message: PushPathResponse) => { // Let's just make sure we haven't aborted this outside this function if (opts?.signal?.aborted) { stream.cancel() return reject(AbortError) } if (message.hasEvent()) { const event = message.getEvent()?.toObject() if (event?.path) { // TODO: Is there an standard library/tool for this step in JS? const pth = event.path.startsWith('/ipfs/') ? event.path.split('/ipfs/')[1] : event.path const cid = new CID(pth) const res: PushPathResult = { path: { path: `/ipfs/${cid?.toString()}`, cid, root: cid, remainder: '', }, root: event.root?.path ?? '', } return resolve(res) } else if (opts?.progress) { opts.progress(event?.bytes) } } else { return reject(new Error('Invalid reply')) } }) stream.on('end', (status?: Status) => { if (status && status.code !== grpc.Code.OK) { return reject(new Error(status.details)) } else { return reject(new Error('undefined result')) } }) stream.on('status', (status?: Status) => { if (status && status.code !== grpc.Code.OK) { return reject(new Error(status.details)) } else { return reject(new Error('undefined result')) } }) const head = new PushPathRequest.Header() head.setPath(source.path || path) head.setKey(key) // Setting root here ensures pushes will error if root is out of date const root = await ensureRootString(api, key, opts?.root, ctx) head.setRoot(root) const req = new PushPathRequest() req.setHeader(head) stream.write(req) if (source.content) { for await (const chunk of source.content) { if (opts?.signal?.aborted) { // Let's just make sure we haven't aborted this outside this function try { // Should already have been handled stream.cancel() } catch {} // noop return reject(AbortError) } // Naively chunk into chunks smaller than CHUNK_SIZE bytes for (const chunklet of genChunks(chunk as Uint8Array, CHUNK_SIZE)) { const part = new PushPathRequest() part.setChunk(chunklet) stream.write(part) } } } stream.end() }) } /** * Pushes an iterable of files to a bucket. * @param key Unique (IPNS compatible) identifier key for a bucket. * @param input The input array of file/stream/objects. * @param opts Options to control response stream. * @internal */ export function bucketsPushPaths( api: GrpcConnection, key: string, input: any, opts?: Omit<PushOptions, 'progress'>, ctx?: ContextInterface, ): AsyncIterableIterator<PushPathsResult> { return new Repeater<PushPathsResult>(async (push, stop) => { const clientjs = new APIServiceClient(api.serviceHost, api.rpcOptions) const metadata = { ...api.context.toJSON(), ...ctx?.toJSON() } const stream: BidirectionalStream< PushPathsRequest, PushPathsResponse > = clientjs.pushPaths(metadata) if (opts?.signal !== undefined) { opts.signal.addEventListener('abort', () => { stream.cancel() throw AbortError }) } stream.on('data', (message: PushPathsResponse) => { // Let's just make sure we haven't aborted this outside this function if (opts?.signal?.aborted) { stream.cancel() return stop(AbortError) } const obj: PushPathsResult = { path: message.getPath(), root: fromPbRootObjectNullable(message.getRoot()), cid: new CID(message.getCid()), pinned: message.getPinned(), size: message.getSize(), } push(obj) }) stream.on('end', (status?: Status) => { if (status && status.code !== grpc.Code.OK) { return stop(new Error(status.details)) } return stop() }) stream.on('status', (status?: Status) => { if (status && status.code !== grpc.Code.OK) { return stop(new Error(status.details)) } return stop() }) const head = new PushPathsRequest.Header() head.setKey(key) // Setting root here ensures pushes will error if root is out of date const root = await ensureRootString(api, key, opts?.root, ctx) head.setRoot(root) const req = new PushPathsRequest() req.setHeader(head) stream.write(req) // Map the following over the top level inputs for parallel pushes const mapper = async ({ path, content }: File): Promise<void> => { const req = new PushPathsRequest() const chunk = new PushPathsRequest.Chunk() chunk.setPath(path) if (content) { for await (const data of content) { if (opts?.signal?.aborted) { // Let's just make sure we haven't aborted this outside this function try { // Should already have been handled stream.cancel() } catch {} // noop return stop(AbortError) } // Naively chunk into chunks smaller than CHUNK_SIZE bytes for (const chunklet of genChunks(data as Uint8Array, CHUNK_SIZE)) { chunk.setData(chunklet) req.setChunk(chunk) stream.write(req) } } } // Close out the file const final = new PushPathsRequest.Chunk() final.setPath(path) req.setChunk(final) stream.write(req) } // We don't care about the top level order, progress is labeled by path await drain(paramap(normaliseInput(input), mapper, { ordered: false })) stream.end() }) } /** * Sets a file at a given bucket path. * @internal */ export async function bucketsSetPath( api: GrpcConnection, key: string, path: string, cid: string, ctx?: ContextInterface, ): Promise<void> { const request = new SetPathRequest() request.setKey(key) request.setPath(path) request.setCid(cid) await api.unary(APIService.SetPath, request, ctx) } /** * Pulls the bucket path, returning the bytes of the given file. * @param key Unique (IPNS compatible) identifier key for a bucket. * @param path A file/object (sub)-path within a bucket. * @param opts Options to control response stream. Currently only supports a progress function. * * @internal */ export function bucketsPullPath( api: GrpcConnection, key: string, path: string, opts?: { progress?: (num?: number) => void }, ctx?: ContextInterface, ): AsyncIterableIterator<Uint8Array> { return new Repeater<Uint8Array>((push, stop) => { const metadata = { ...api.context.toJSON(), ...ctx?.toJSON() } const request = new PullPathRequest() request.setKey(key) request.setPath(path) let written = 0 const resp = grpc.invoke(APIService.PullPath, { host: api.serviceHost, transport: api.rpcOptions.transport, debug: api.rpcOptions.debug, request, metadata, onMessage: async (res: PullPathResponse) => { const chunk = res.getChunk_asU8() written += chunk.byteLength if (opts?.progress) { opts.progress(written) } push(chunk) }, onEnd: async ( status: grpc.Code, message: string, // _trailers: grpc.Metadata, ) => { if (status !== grpc.Code.OK) { stop(new Error(message)) } stop() }, }) // Cleanup afterwards stop.then(() => resp.close()) }) } /** * pullIpfsPath pulls the path from a remote UnixFS dag, writing it to writer if it's a file. * @param path A file/object (sub)-path within a bucket. * @param opts Options to control response stream. Currently only supports a progress function. * * @internal */ export function bucketsPullIpfsPath( api: GrpcConnection, path: string, opts?: { progress?: (num?: number) => void }, ctx?: ContextInterface, ): AsyncIterableIterator<Uint8Array> { return new Repeater<Uint8Array>((push, stop) => { const metadata = { ...api.context.toJSON(), ...ctx?.toJSON() } const request = new PullIpfsPathRequest() request.setPath(path) let written = 0 const resp = grpc.invoke(APIService.PullIpfsPath, { host: api.serviceHost, transport: api.rpcOptions.transport, debug: api.rpcOptions.debug, request, metadata, onMessage: async (res: PullIpfsPathResponse) => { const chunk = res.getChunk_asU8() push(chunk) written += chunk.byteLength if (opts?.progress) { opts.progress(written) } }, onEnd: async ( status: grpc.Code, message: string, // _trailers: grpc.Metadata, ) => { if (status !== grpc.Code.OK) { stop(new Error(message)) } stop() }, }) stop.then(() => resp.close()) }) } /** * Removes an entire bucket. Files and directories will be unpinned. * @param key Unique (IPNS compatible) identifier key for a bucket. * * @internal */ export async function bucketsRemove( api: GrpcConnection, key: string, ctx?: ContextInterface, ): Promise<void> { logger.debug('remove request') const req = new RemoveRequest() req.setKey(key) await api.unary(APIService.Remove, req, ctx) return } /** * Returns information about a bucket path. * @param key Unique (IPNS compatible) identifier key for a bucket. * @param path A file/object (sub)-path within a bucket. * @param root optional to specify a root * * @internal */ export async function bucketsRemovePath( api: GrpcConnection, key: string, path: string, opts?: RemovePathOptions, ctx?: ContextInterface, ): Promise<RemovePathResponse> { logger.debug('remove path request') const req = new RemovePathRequest() req.setKey(key) req.setPath(path) const root = await ensureRootString(api, key, opts?.root, ctx) req.setRoot(root) const res: _RemovePathResponse = await api.unary( APIService.RemovePath, req, ctx, ) return { pinned: res.getPinned(), root: fromPbRootObjectNullable(res.getRoot()), } } export async function bucketsPushPathAccessRoles( api: GrpcConnection, key: string, path: string, roles: Map<string, PathAccessRole>, ctx?: ContextInterface, ): Promise<void> { logger.debug('remove path request') const req = new PushPathAccessRolesRequest() req.setKey(key) req.setPath(path) roles.forEach((value, key) => req.getRolesMap().set(key, value)) await api.unary(APIService.PushPathAccessRoles, req, ctx) return } export async function bucketsPullPathAccessRoles( api: GrpcConnection, key: string, path = '/', ctx?: ContextInterface, ): Promise<Map<string, 0 | 1 | 2 | 3>> { logger.debug('remove path request') const req = new PullPathAccessRolesRequest() req.setKey(key) req.setPath(path) const response: PullPathAccessRolesResponse = await api.unary( APIService.PullPathAccessRoles, req, ctx, ) const roles = response.getRolesMap() const typedRoles = new Map() roles.forEach((entry, key) => typedRoles.set(key, entry)) return typedRoles } /** * @internal */ export async function bucketsDefaultArchiveConfig( api: GrpcConnection, key: string, ctx?: ContextInterface, ): Promise<ArchiveConfig> { logger.debug('default archive config request') const req = new DefaultArchiveConfigRequest() req.setKey(key) const res: DefaultArchiveConfigResponse = await api.unary( APIService.DefaultArchiveConfig, req, ctx, ) const config = res.getArchiveConfig() if (!config) { throw new Error('no archive config returned') } return fromProtoArchiveConfig(config.toObject()) } /** * @internal */ export async function bucketsSetDefaultArchiveConfig( api: GrpcConnection, key: string, config: ArchiveConfig, ctx?: ContextInterface, ): Promise<void> { logger.debug('set default archive config request') const req = new SetDefaultArchiveConfigRequest() req.setKey(key) req.setArchiveConfig(toProtoArchiveConfig(config)) await api.unary(APIService.SetDefaultArchiveConfig, req, ctx) return } /** * archive creates a Filecoin bucket archive. * @internal * @param key Unique (IPNS compatible) identifier key for a bucket. * @param options Options that control the behavior of the bucket archive * @param skipAutomaticVerifiedDeal skips logic that automatically uses available datacap to make a verified deal for the archive. */ export async function bucketsArchive( api: GrpcConnection, key: string, options?: ArchiveOptions, skipAutomaticVerifiedDeal?: boolean, ctx?: ContextInterface, ): Promise<void> { logger.debug('archive request') const req = new ArchiveRequest() req.setKey(key) if (skipAutomaticVerifiedDeal !== undefined) { req.setSkipAutomaticVerifiedDeal(skipAutomaticVerifiedDeal) } if (options?.archiveConfig) { req.setArchiveConfig(toProtoArchiveConfig(options.archiveConfig)) } await api.unary(APIService.Archive, req, ctx) return } /** * @internal */ export async function bucketsArchives( api: GrpcConnection, key: string, ctx?: ContextInterface, ): Promise<Archives> { logger.debug('archives request') const req = new ArchivesRequest() req.setKey(key) const res: ArchivesResponse = await api.unary(APIService.Archives, req, ctx) const current = res.toObject().current return { current: current ? fromPbArchive(current) : undefined, history: res.toObject().historyList.map(fromPbArchive), } } /** * archiveWatch watches status events from a Filecoin bucket archive. * @internal * @param key Unique (IPNS compatible) identifier key for a bucket. */ export async function bucketsArchiveWatch( api: GrpcConnection, key: string, callback: ( reply?: { id: string | undefined; msg: string }, err?: Error, ) => void, ctx?: ContextInterface, ): Promise<() => void> { logger.debug('archive watch request') const req = new ArchiveWatchRequest() req.setKey(key) const metadata = { ...api.context.toJSON(), ...ctx?.toJSON() } const res = grpc.invoke(APIService.ArchiveWatch, { host: api.context.host, request: req, metadata, onMessage: (rec: ArchiveWatchResponse) => { const response = { id: rec.getJsPbMessageId(), msg: rec.getMsg(), } callback(response) }, onEnd: ( status: grpc.Code, message: string /** _trailers: grpc.Metadata */, ) => { if (status !== grpc.Code.OK) { return callback(undefined, new Error(message)) } callback() }, }) return res.close.bind(res) } /** * Raw API connected needed by Buckets CI code (compile friendly) * see more https://github.com/textileio/github-action-buckets */ export class BucketsGrpcClient { public serviceHost: string public rpcOptions: grpc.RpcOptions /** * Creates a new gRPC client instance for accessing the Textile Buckets API. * @param context The context to use for interacting with the APIs. Can be modified later. */ constructor(public context: ContextInterface = new Context(), debug = false) { this.serviceHost = context.host this.rpcOptions = { transport: WebsocketTransport(), debug, } } public unary< R extends grpc.ProtobufMessage, T extends grpc.ProtobufMessage, M extends grpc.UnaryMethodDefinition<R, T> >(methodDescriptor: M, req: R, ctx?: ContextInterface): Promise<T | void> { return new Promise<T | void>((resolve, reject) => { const metadata = { ...this.context.toJSON(), ...ctx?.toJSON() } grpc.unary(methodDescriptor, { request: req, host: this.serviceHost, transport: this.rpcOptions.transport, debug: this.rpcOptions.debug, metadata, onEnd: (res: grpc.UnaryOutput<T>) => { const { status, statusMessage, message } = res if (status === grpc.Code.OK) { if (message) { resolve(message) } else { resolve() } } else { reject(new Error(statusMessage)) } }, }) }) } }
the_stack
import { XrpError, XrpErrorType } from '..' import { Utils, XrplNetwork } from 'xpring-common-js' import XrpUtils from '../shared/xrp-utils' import { Transaction } from '../Generated/web/org/xrpl/rpc/v1/transaction_pb' import PaymentFlags from '../shared/payment-flags' import XrpSigner from './xrp-signer' import XrpTransactionType from '../shared/xrp-transaction-type' import XrpPayment from './xrp-payment' import XrpMemo from './xrp-memo' import { GetTransactionResponse } from '../Generated/web/org/xrpl/rpc/v1/get_transaction_pb' /** * A transaction on the XRP Ledger. * * @see: https://xrpl.org/transaction-formats.html */ export default class XrpTransaction { /** * Constructs an XrpTransaction from a Transaction. * * @param transaction a Transaction (protobuf object) whose field values will be used * to construct an XrpTransaction * @param xrplNetwork The XRP Ledger network from which this object was retrieved. * @returns an XrpTransaction with its fields set via the analogous protobuf fields. * @see https://github.com/ripple/rippled/blob/develop/src/ripple/proto/org/xrpl/rpc/v1/transaction.proto#L13 */ public static from( getTransactionResponse: GetTransactionResponse, xrplNetwork: XrplNetwork, ): XrpTransaction { const transaction = getTransactionResponse.getTransaction() if (!transaction) { throw new XrpError( XrpErrorType.MalformedProtobuf, 'Transaction protobuf is missing valid `transaction` field.', ) } const account = transaction.getAccount()?.getValue()?.getAddress() if (!account) { throw new XrpError( XrpErrorType.MalformedProtobuf, 'Transaction protobuf is missing valid `account` field.', ) } const sourceTag = transaction.getSourceTag()?.getValue() const sourceXAddress = XrpUtils.encodeXAddress( account, sourceTag, xrplNetwork === XrplNetwork.Test || xrplNetwork === XrplNetwork.Dev, ) if (!sourceXAddress) { throw new XrpError( XrpErrorType.MalformedProtobuf, 'Cannot construct XAddress from Transaction protobuf `account` and `sourceTag` fields.', ) } const fee = transaction.getFee()?.getDrops() if (!fee) { throw new XrpError( XrpErrorType.MalformedProtobuf, 'Transaction protobuf is missing valid `fee` field.', ) } const intFee = Number(fee) if (isNaN(intFee)) { throw new XrpError( XrpErrorType.MalformedProtobuf, 'Transaction protobuf `fee` field is not a valid integer number of XRP drops.', ) } const sequence = transaction.getSequence()?.getValue() if (!sequence) { throw new XrpError( XrpErrorType.MalformedProtobuf, 'Transaction protobuf is missing valid `sequence` field.', ) } const accountTransactionID = transaction .getAccountTransactionId() ?.getValue_asU8() const flags = transaction.getFlags()?.getValue() const lastLedgerSequence = transaction.getLastLedgerSequence()?.getValue() let memos if (transaction.getMemosList().length > 0) { memos = transaction.getMemosList().map((memo) => XrpMemo.from(memo)) } let signers if (transaction.getSignersList().length > 0) { signers = transaction .getSignersList() .map((signer) => XrpSigner.from(signer, xrplNetwork)) } const signingPublicKey = transaction.getSigningPublicKey()?.getValue_asB64() if (signingPublicKey === undefined) { throw new XrpError( XrpErrorType.MalformedProtobuf, 'Transaction protobuf is missing valid `signingPublicKey` field.', ) } if (!signers && signingPublicKey === '') { throw new XrpError( XrpErrorType.MalformedProtobuf, 'Transaction protobuf does not have a `signingPublicKey` field or a `signers` field.', ) } const transactionSignature = transaction .getTransactionSignature() ?.getValue_asU8() if (!transactionSignature) { throw new XrpError( XrpErrorType.MalformedProtobuf, 'Transaction protobuf is missing valid `transactionSignature` field.', ) } let paymentFields let type switch (transaction.getTransactionDataCase()) { case Transaction.TransactionDataCase.PAYMENT: { const payment = transaction.getPayment() if (!payment) { throw new XrpError( XrpErrorType.MalformedProtobuf, 'Transaction protobuf is type Payment but is missing `payment` field.', ) } paymentFields = XrpPayment.from(payment, xrplNetwork) type = XrpTransactionType.Payment break } case Transaction.TransactionDataCase.TRANSACTION_DATA_NOT_SET: { throw new XrpError( XrpErrorType.MalformedProtobuf, 'Transaction protobuf is missing transaction data case.', ) } default: throw new XrpError( XrpErrorType.MalformedProtobuf, 'Transaction protobuf is of a transaction type unsupported by xpring-js.', ) } const transactionHashBytes = getTransactionResponse.getHash_asU8() const transactionHash = Utils.toHex(transactionHashBytes) if (!transactionHash) { throw new XrpError( XrpErrorType.MalformedProtobuf, 'Transaction protobuf is missing valid `hash` field.', ) } // Transactions report their timestamps since the Ripple Epoch, which is 946,684,800 seconds after // the unix epoch. Convert transaction's timestamp to a unix timestamp. // See: https://xrpl.org/basic-data-types.html#specifying-time const rippleTransactionDate = getTransactionResponse.getDate()?.getValue() const timestamp = rippleTransactionDate !== undefined ? rippleTransactionDate + 946684800 : undefined const deliveredAmountProto = getTransactionResponse .getMeta() ?.getDeliveredAmount() const deliveredAmountXrp = deliveredAmountProto ?.getValue() ?.getXrpAmount() ?.getDrops() const deliveredAmountIssuedCurrency = deliveredAmountProto ?.getValue() ?.getIssuedCurrencyAmount() ?.getValue() const deliveredAmount = deliveredAmountXrp ?? deliveredAmountIssuedCurrency const validated = getTransactionResponse.getValidated() const ledgerIndex = getTransactionResponse.getLedgerIndex() return new XrpTransaction( transactionHash, sourceXAddress, type, fee, sequence, signingPublicKey, transactionSignature, validated, ledgerIndex, accountTransactionID, flags, lastLedgerSequence, memos, signers, paymentFields, timestamp, deliveredAmount, ) } /** * @param hash The identifying hash of the transaction. * @param accountTransactionID (Optional) Hash value identifying another transaction. * If provided, this transaction is only valid if the sending account's * previously-sent transaction matches the provided hash. * @param fee Integer amount of XRP, in drops, to be destroyed as a cost for distributing this transaction to the network. * @param flags (Optional) Set of bit-flags for this transaction. * @param lastLedgerSequence (Optional; strongly recommended) Highest ledger index this transaction can appear in. * Specifying this field places a strict upper limit on how long the transaction can wait to be * validated or rejected. * @param memos (Optional) Additional arbitrary information used to identify this transaction. * @param sequence The sequence number of the account sending the transaction. A transaction is only valid if the Sequence * number is exactly 1 greater than the previous transaction from the same account. * @param signers (Optional) Array of objects that represent a multi-signature which authorizes this transaction. * @param signingPublicKey Hex representation of the public key that corresponds to the private key used to sign this transaction. * If an empty string, indicates a multi-signature is present in the Signers field instead. * @param sourceXAddress: The unique address and source tag of the sender that initiated the transaction, encoded as an X-address. * See "https://xrpaddress.info" * @param transactionSignature The signature that verifies this transaction as originating from the account it says it is from. * @param type The type of transaction. * @param paymentFields An XrpPayment object representing the additional fields present in a PAYMENT transaction. * See "https://xrpl.org/payment.html#payment-fields" * @param deliveredAmount The actual amount delivered by this transaction, in the case of a partial payment. * See "https://xrpl.org/partial-payments.html#the-delivered_amount-field" * @param timestamp The transaction's timestamp, converted to a unix timestamp. * @param validated A boolean indicating whether or not this transaction was found on a validated ledger, and not an open or closed ledger. * See "https://xrpl.org/ledgers.html#open-closed-and-validated-ledgers" * @param ledgerIndex The index of the ledger on which this transaction was found. */ private constructor( readonly hash: string, readonly sourceXAddress: string, readonly type: XrpTransactionType, readonly fee: string, readonly sequence: number, readonly signingPublicKey: string, readonly transactionSignature: Uint8Array, readonly validated: boolean, readonly ledgerIndex: number, readonly accountTransactionID?: Uint8Array, readonly flags?: PaymentFlags, readonly lastLedgerSequence?: number, readonly memos?: Array<XrpMemo>, readonly signers?: Array<XrpSigner>, readonly paymentFields?: XrpPayment, readonly timestamp?: number, readonly deliveredAmount?: string, ) {} }
the_stack
import { should } from 'chai'; import { tokenize, Input, Token } from './utils/tokenize'; describe("Property", () => { before(() => { should(); }); describe("Property", () => { it("declaration", async () => { const input = Input.InClass(` public IBooom Property { get { return null; } set { something = value; } }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.Type("IBooom"), Token.Identifiers.PropertyName("Property"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.OpenBrace, Token.Keywords.Control.Return, Token.Literals.Null, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace, Token.Keywords.Set, Token.Punctuation.OpenBrace, Token.Variables.ReadWrite("something"), Token.Operators.Assignment, Token.Variables.ReadWrite("value"), Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace, Token.Punctuation.CloseBrace]); }); it("declaration single line", async () => { const input = Input.InClass(`public IBooom Property { get { return null; } private set { something = value; } }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.Type("IBooom"), Token.Identifiers.PropertyName("Property"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.OpenBrace, Token.Keywords.Control.Return, Token.Literals.Null, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace, Token.Keywords.Modifiers.Private, Token.Keywords.Set, Token.Punctuation.OpenBrace, Token.Variables.ReadWrite("something"), Token.Operators.Assignment, Token.Variables.ReadWrite("value"), Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace, Token.Punctuation.CloseBrace]); }); it("declaration without modifiers", async () => { const input = Input.InClass(`IBooom Property {get; set;}`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Type("IBooom"), Token.Identifiers.PropertyName("Property"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.Semicolon, Token.Keywords.Set, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("auto-property single line", async function () { const input = Input.InClass(`public IBooom Property { get; set; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.Type("IBooom"), Token.Identifiers.PropertyName("Property"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.Semicolon, Token.Keywords.Set, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("auto-property single line (protected internal)", async function () { const input = Input.InClass(`protected internal IBooom Property { get; set; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Protected, Token.Keywords.Modifiers.Internal, Token.Type("IBooom"), Token.Identifiers.PropertyName("Property"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.Semicolon, Token.Keywords.Set, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("auto-property", async () => { const input = Input.InClass(` public IBooom Property { get; set; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.Type("IBooom"), Token.Identifiers.PropertyName("Property"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.Semicolon, Token.Keywords.Set, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("init auto-property", async () => { const input = Input.InClass(`public int X { get; init; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.PrimitiveType.Int, Token.Identifiers.PropertyName("X"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.Semicolon, Token.Keywords.Init, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("generic auto-property", async () => { const input = Input.InClass(`public Dictionary<string, List<T>[]> Property { get; set; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.Type("Dictionary"), Token.Punctuation.TypeParameters.Begin, Token.PrimitiveType.String, Token.Punctuation.Comma, Token.Type("List"), Token.Punctuation.TypeParameters.Begin, Token.Type("T"), Token.Punctuation.TypeParameters.End, Token.Punctuation.OpenBracket, Token.Punctuation.CloseBracket, Token.Punctuation.TypeParameters.End, Token.Identifiers.PropertyName("Property"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.Semicolon, Token.Keywords.Set, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("auto-property initializer", async () => { const input = Input.InClass(`public Dictionary<string, List<T>[]> Property { get; } = new Dictionary<string, List<T>[]>();`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.Type("Dictionary"), Token.Punctuation.TypeParameters.Begin, Token.PrimitiveType.String, Token.Punctuation.Comma, Token.Type("List"), Token.Punctuation.TypeParameters.Begin, Token.Type("T"), Token.Punctuation.TypeParameters.End, Token.Punctuation.OpenBracket, Token.Punctuation.CloseBracket, Token.Punctuation.TypeParameters.End, Token.Identifiers.PropertyName("Property"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace, Token.Operators.Assignment, Token.Keywords.New, Token.Type("Dictionary"), Token.Punctuation.TypeParameters.Begin, Token.PrimitiveType.String, Token.Punctuation.Comma, Token.Type("List"), Token.Punctuation.TypeParameters.Begin, Token.Type("T"), Token.Punctuation.TypeParameters.End, Token.Punctuation.OpenBracket, Token.Punctuation.CloseBracket, Token.Punctuation.TypeParameters.End, Token.Punctuation.OpenParen, Token.Punctuation.CloseParen, Token.Punctuation.Semicolon]); }); it("expression body", async () => { const input = Input.InClass(` private string prop1 => "hello"; private bool prop2 => true;`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Private, Token.PrimitiveType.String, Token.Identifiers.PropertyName("prop1"), Token.Operators.Arrow, Token.Punctuation.String.Begin, Token.Literals.String("hello"), Token.Punctuation.String.End, Token.Punctuation.Semicolon, Token.Keywords.Modifiers.Private, Token.PrimitiveType.Bool, Token.Identifiers.PropertyName("prop2"), Token.Operators.Arrow, Token.Literals.Boolean.True, Token.Punctuation.Semicolon]); }); it("explicitly-implemented interface member", async () => { const input = Input.InClass(`string IFoo<string>.Bar { get; set; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.PrimitiveType.String, Token.Type("IFoo"), Token.Punctuation.TypeParameters.Begin, Token.PrimitiveType.String, Token.Punctuation.TypeParameters.End, Token.Punctuation.Accessor, Token.Identifiers.PropertyName("Bar"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.Semicolon, Token.Keywords.Set, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("declaration in interface", async () => { const input = Input.InInterface(`string Bar { get; set; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.PrimitiveType.String, Token.Identifiers.PropertyName("Bar"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.Semicolon, Token.Keywords.Set, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("declaration in interface (read-only)", async () => { const input = Input.InInterface(`string Bar { get; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.PrimitiveType.String, Token.Identifiers.PropertyName("Bar"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("declaration in interface (write-only)", async () => { const input = Input.InInterface(`string Bar { set; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.PrimitiveType.String, Token.Identifiers.PropertyName("Bar"), Token.Punctuation.OpenBrace, Token.Keywords.Set, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("declaration with attributes", async () => { const input = Input.InClass(` [Obsolete] public int P1 { [Obsolete] get { } [Obsolete] set { } }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Punctuation.OpenBracket, Token.Type("Obsolete"), Token.Punctuation.CloseBracket, Token.Keywords.Modifiers.Public, Token.PrimitiveType.Int, Token.Identifiers.PropertyName("P1"), Token.Punctuation.OpenBrace, Token.Punctuation.OpenBracket, Token.Type("Obsolete"), Token.Punctuation.CloseBracket, Token.Keywords.Get, Token.Punctuation.OpenBrace, Token.Punctuation.CloseBrace, Token.Punctuation.OpenBracket, Token.Type("Obsolete"), Token.Punctuation.CloseBracket, Token.Keywords.Set, Token.Punctuation.OpenBrace, Token.Punctuation.CloseBrace, Token.Punctuation.CloseBrace]); }); it("Expression-bodied property accessors (issue #44)", async () => { const input = Input.InClass(` public int Timeout { get => Socket.ReceiveTimeout; set => Socket.ReceiveTimeout = value; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Public, Token.PrimitiveType.Int, Token.Identifiers.PropertyName("Timeout"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Operators.Arrow, Token.Variables.Object("Socket"), Token.Punctuation.Accessor, Token.Variables.Property("ReceiveTimeout"), Token.Punctuation.Semicolon, Token.Keywords.Set, Token.Operators.Arrow, Token.Variables.Object("Socket"), Token.Punctuation.Accessor, Token.Variables.Property("ReceiveTimeout"), Token.Operators.Assignment, Token.Variables.ReadWrite("value"), Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("ref return", async () => { const input = Input.InInterface(`ref int P { get; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Ref, Token.PrimitiveType.Int, Token.Identifiers.PropertyName("P"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("ref readonly return", async () => { const input = Input.InInterface(`ref readonly int P { get; }`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Ref, Token.Keywords.Modifiers.ReadOnly, Token.PrimitiveType.Int, Token.Identifiers.PropertyName("P"), Token.Punctuation.OpenBrace, Token.Keywords.Get, Token.Punctuation.Semicolon, Token.Punctuation.CloseBrace]); }); it("expression body ref return", async () => { const input = Input.InClass(`ref int P => ref x;`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Ref, Token.PrimitiveType.Int, Token.Identifiers.PropertyName("P"), Token.Operators.Arrow, Token.Keywords.Modifiers.Ref, Token.Variables.ReadWrite("x"), Token.Punctuation.Semicolon]); }); it("expression body ref readonly return", async () => { const input = Input.InClass(`ref readonly int P => ref x;`); const tokens = await tokenize(input); tokens.should.deep.equal([ Token.Keywords.Modifiers.Ref, Token.Keywords.Modifiers.ReadOnly, Token.PrimitiveType.Int, Token.Identifiers.PropertyName("P"), Token.Operators.Arrow, Token.Keywords.Modifiers.Ref, Token.Variables.ReadWrite("x"), Token.Punctuation.Semicolon]); }); }); });
the_stack
import localforage from "localforage"; export type LocalForage = typeof localforage; import { nanoid } from "nanoid"; import { requireApiVersion, TAbstractFile, TFile, TFolder } from "obsidian"; import { API_VER_STAT_FOLDER, SUPPORTED_SERVICES_TYPE } from "./baseTypes"; import type { SyncPlanType } from "./sync"; import { statFix, toText, unixTimeToStr } from "./misc"; import { log } from "./moreOnLog"; const DB_VERSION_NUMBER_IN_HISTORY = [20211114, 20220108, 20220326]; export const DEFAULT_DB_VERSION_NUMBER: number = 20220326; export const DEFAULT_DB_NAME = "remotelysavedb"; export const DEFAULT_TBL_VERSION = "schemaversion"; export const DEFAULT_TBL_FILE_HISTORY = "filefolderoperationhistory"; export const DEFAULT_TBL_SYNC_MAPPING = "syncmetadatahistory"; export const DEFAULT_SYNC_PLANS_HISTORY = "syncplanshistory"; export const DEFAULT_TBL_VAULT_RANDOM_ID_MAPPING = "vaultrandomidmapping"; export const DEFAULT_TBL_LOGGER_OUTPUT = "loggeroutput"; export interface FileFolderHistoryRecord { key: string; ctime: number; mtime: number; size: number; actionWhen: number; actionType: "delete" | "rename" | "renameDestination"; keyType: "folder" | "file"; renameTo: string; vaultRandomID: string; } interface SyncMetaMappingRecord { localKey: string; remoteKey: string; localSize: number; remoteSize: number; localMtime: number; remoteMtime: number; remoteExtraKey: string; remoteType: SUPPORTED_SERVICES_TYPE; keyType: "folder" | "file"; vaultRandomID: string; } interface SyncPlanRecord { ts: number; remoteType: string; syncPlan: string; vaultRandomID: string; } export interface InternalDBs { versionTbl: LocalForage; fileHistoryTbl: LocalForage; syncMappingTbl: LocalForage; syncPlansTbl: LocalForage; vaultRandomIDMappingTbl: LocalForage; loggerOutputTbl: LocalForage; } /** * This migration mainly aims to assign vault name or vault id into all tables. * @param db * @param vaultRandomID */ const migrateDBsFrom20211114To20220108 = async ( db: InternalDBs, vaultRandomID: string ) => { const oldVer = 20211114; const newVer = 20220108; log.debug(`start upgrading internal db from ${oldVer} to ${newVer}`); const allPromisesToWait: Promise<any>[] = []; log.debug("assign vault id to any delete history"); const keysInDeleteHistoryTbl = await db.fileHistoryTbl.keys(); for (const key of keysInDeleteHistoryTbl) { if (key.startsWith(vaultRandomID)) { continue; } const value = (await db.fileHistoryTbl.getItem( key )) as FileFolderHistoryRecord; if (value === null || value === undefined) { continue; } if (value.vaultRandomID === undefined || value.vaultRandomID === "") { value.vaultRandomID = vaultRandomID; } const newKey = `${vaultRandomID}\t${key}`; allPromisesToWait.push(db.fileHistoryTbl.setItem(newKey, value)); allPromisesToWait.push(db.fileHistoryTbl.removeItem(key)); } log.debug("assign vault id to any sync mapping"); const keysInSyncMappingTbl = await db.syncMappingTbl.keys(); for (const key of keysInSyncMappingTbl) { if (key.startsWith(vaultRandomID)) { continue; } const value = (await db.syncMappingTbl.getItem( key )) as SyncMetaMappingRecord; if (value === null || value === undefined) { continue; } if (value.vaultRandomID === undefined || value.vaultRandomID === "") { value.vaultRandomID = vaultRandomID; } const newKey = `${vaultRandomID}\t${key}`; allPromisesToWait.push(db.syncMappingTbl.setItem(newKey, value)); allPromisesToWait.push(db.syncMappingTbl.removeItem(key)); } log.debug("assign vault id to any sync plan records"); const keysInSyncPlansTbl = await db.syncPlansTbl.keys(); for (const key of keysInSyncPlansTbl) { if (key.startsWith(vaultRandomID)) { continue; } const value = (await db.syncPlansTbl.getItem(key)) as SyncPlanRecord; if (value === null || value === undefined) { continue; } if (value.vaultRandomID === undefined || value.vaultRandomID === "") { value.vaultRandomID = vaultRandomID; } const newKey = `${vaultRandomID}\t${key}`; allPromisesToWait.push(db.syncPlansTbl.setItem(newKey, value)); allPromisesToWait.push(db.syncPlansTbl.removeItem(key)); } log.debug("finally update version if everything is ok"); await Promise.all(allPromisesToWait); await db.versionTbl.setItem("version", newVer); log.debug(`finish upgrading internal db from ${oldVer} to ${newVer}`); }; /** * no need to do anything except changing version * we just add more file operations in db, and no schema is changed. * @param db * @param vaultRandomID */ const migrateDBsFrom20220108To20220326 = async ( db: InternalDBs, vaultRandomID: string ) => { const oldVer = 20220108; const newVer = 20220326; log.debug(`start upgrading internal db from ${oldVer} to ${newVer}`); await db.versionTbl.setItem("version", newVer); log.debug(`finish upgrading internal db from ${oldVer} to ${newVer}`); }; const migrateDBs = async ( db: InternalDBs, oldVer: number, newVer: number, vaultRandomID: string ) => { if (oldVer === newVer) { return; } if (oldVer === 20211114 && newVer === 20220108) { return await migrateDBsFrom20211114To20220108(db, vaultRandomID); } if (oldVer === 20220108 && newVer === 20220326) { return await migrateDBsFrom20220108To20220326(db, vaultRandomID); } if (oldVer === 20211114 && newVer === 20220326) { // TODO: more steps with more versions in the future await migrateDBsFrom20211114To20220108(db, vaultRandomID); await migrateDBsFrom20220108To20220326(db, vaultRandomID); return; } if (newVer < oldVer) { throw Error( "You've installed a new version, but then downgrade to an old version. Stop working!" ); } // not implemented throw Error(`not supported internal db changes from ${oldVer} to ${newVer}`); }; export const prepareDBs = async ( vaultBasePath: string, vaultRandomIDFromOldConfigFile: string ) => { const db = { versionTbl: localforage.createInstance({ name: DEFAULT_DB_NAME, storeName: DEFAULT_TBL_VERSION, }), fileHistoryTbl: localforage.createInstance({ name: DEFAULT_DB_NAME, storeName: DEFAULT_TBL_FILE_HISTORY, }), syncMappingTbl: localforage.createInstance({ name: DEFAULT_DB_NAME, storeName: DEFAULT_TBL_SYNC_MAPPING, }), syncPlansTbl: localforage.createInstance({ name: DEFAULT_DB_NAME, storeName: DEFAULT_SYNC_PLANS_HISTORY, }), vaultRandomIDMappingTbl: localforage.createInstance({ name: DEFAULT_DB_NAME, storeName: DEFAULT_TBL_VAULT_RANDOM_ID_MAPPING, }), loggerOutputTbl: localforage.createInstance({ name: DEFAULT_DB_NAME, storeName: DEFAULT_TBL_LOGGER_OUTPUT, }), } as InternalDBs; // try to get vaultRandomID firstly let vaultRandomID = ""; const vaultRandomIDInDB: string | null = await db.vaultRandomIDMappingTbl.getItem(`path2id\t${vaultBasePath}`); if (vaultRandomIDInDB === null) { if (vaultRandomIDFromOldConfigFile !== "") { // reuse the old config id vaultRandomID = vaultRandomIDFromOldConfigFile; } else { // no old config id, we create a random one vaultRandomID = nanoid(); } // save the id back await db.vaultRandomIDMappingTbl.setItem( `path2id\t${vaultBasePath}`, vaultRandomID ); await db.vaultRandomIDMappingTbl.setItem( `id2path\t${vaultRandomID}`, vaultBasePath ); } else { vaultRandomID = vaultRandomIDInDB; } if (vaultRandomID === "") { throw Error("no vaultRandomID found or generated"); } const originalVersion: number | null = await db.versionTbl.getItem("version"); if (originalVersion === null) { log.debug( `no internal db version, setting it to ${DEFAULT_DB_VERSION_NUMBER}` ); await db.versionTbl.setItem("version", DEFAULT_DB_VERSION_NUMBER); } else if (originalVersion === DEFAULT_DB_VERSION_NUMBER) { // do nothing } else { log.debug( `trying to upgrade db version from ${originalVersion} to ${DEFAULT_DB_VERSION_NUMBER}` ); await migrateDBs( db, originalVersion, DEFAULT_DB_VERSION_NUMBER, vaultRandomID ); } log.info("db connected"); return { db: db, vaultRandomID: vaultRandomID, }; }; export const destroyDBs = async () => { // await localforage.dropInstance({ // name: DEFAULT_DB_NAME, // }); // log.info("db deleted"); const req = indexedDB.deleteDatabase(DEFAULT_DB_NAME); req.onsuccess = (event) => { log.info("db deleted"); }; req.onblocked = (event) => { log.warn("trying to delete db but it was blocked"); }; req.onerror = (event) => { log.error("tried to delete db but something goes wrong!"); log.error(event); }; }; export const loadFileHistoryTableByVault = async ( db: InternalDBs, vaultRandomID: string ) => { const records = [] as FileFolderHistoryRecord[]; await db.fileHistoryTbl.iterate((value, key, iterationNumber) => { if (key.startsWith(`${vaultRandomID}\t`)) { records.push(value as FileFolderHistoryRecord); } }); records.sort((a, b) => a.actionWhen - b.actionWhen); // ascending return records; }; export const clearDeleteRenameHistoryOfKeyAndVault = async ( db: InternalDBs, key: string, vaultRandomID: string ) => { const fullKey = `${vaultRandomID}\t${key}`; const item: FileFolderHistoryRecord | null = await db.fileHistoryTbl.getItem( fullKey ); if ( item !== null && (item.actionType === "delete" || item.actionType === "rename") ) { await db.fileHistoryTbl.removeItem(fullKey); } }; export const insertDeleteRecordByVault = async ( db: InternalDBs, fileOrFolder: TAbstractFile, vaultRandomID: string ) => { // log.info(fileOrFolder); let k: FileFolderHistoryRecord; if (fileOrFolder instanceof TFile) { k = { key: fileOrFolder.path, ctime: fileOrFolder.stat.ctime, mtime: fileOrFolder.stat.mtime, size: fileOrFolder.stat.size, actionWhen: Date.now(), actionType: "delete", keyType: "file", renameTo: "", vaultRandomID: vaultRandomID, }; } else if (fileOrFolder instanceof TFolder) { // key should endswith "/" const key = fileOrFolder.path.endsWith("/") ? fileOrFolder.path : `${fileOrFolder.path}/`; const ctime = 0; // they are deleted, so no way to get ctime, mtime const mtime = 0; // they are deleted, so no way to get ctime, mtime k = { key: key, ctime: ctime, mtime: mtime, size: 0, actionWhen: Date.now(), actionType: "delete", keyType: "folder", renameTo: "", vaultRandomID: vaultRandomID, }; } await db.fileHistoryTbl.setItem(`${vaultRandomID}\t${k.key}`, k); }; /** * A file/folder is renamed from A to B * We insert two records: * A with actionType="rename" * B with actionType="renameDestination" * @param db * @param fileOrFolder * @param oldPath * @param vaultRandomID */ export const insertRenameRecordByVault = async ( db: InternalDBs, fileOrFolder: TAbstractFile, oldPath: string, vaultRandomID: string ) => { // log.info(fileOrFolder); let k1: FileFolderHistoryRecord; let k2: FileFolderHistoryRecord; const actionWhen = Date.now(); if (fileOrFolder instanceof TFile) { k1 = { key: oldPath, ctime: fileOrFolder.stat.ctime, mtime: fileOrFolder.stat.mtime, size: fileOrFolder.stat.size, actionWhen: actionWhen, actionType: "rename", keyType: "file", renameTo: fileOrFolder.path, vaultRandomID: vaultRandomID, }; k2 = { key: fileOrFolder.path, ctime: fileOrFolder.stat.ctime, mtime: fileOrFolder.stat.mtime, size: fileOrFolder.stat.size, actionWhen: actionWhen, actionType: "renameDestination", keyType: "file", renameTo: "", // itself is the destination, so no need to set this field vaultRandomID: vaultRandomID, }; } else if (fileOrFolder instanceof TFolder) { const key = oldPath.endsWith("/") ? oldPath : `${oldPath}/`; const renameTo = fileOrFolder.path.endsWith("/") ? fileOrFolder.path : `${fileOrFolder.path}/`; let ctime = 0; let mtime = 0; if (requireApiVersion(API_VER_STAT_FOLDER)) { // TAbstractFile does not contain these info // but from API_VER_STAT_FOLDER we can manually stat them by path. const s = await statFix(fileOrFolder.vault, fileOrFolder.path); ctime = s.ctime; mtime = s.mtime; } k1 = { key: key, ctime: ctime, mtime: mtime, size: 0, actionWhen: actionWhen, actionType: "rename", keyType: "folder", renameTo: renameTo, vaultRandomID: vaultRandomID, }; k2 = { key: renameTo, ctime: ctime, mtime: mtime, size: 0, actionWhen: actionWhen, actionType: "renameDestination", keyType: "folder", renameTo: "", // itself is the destination, so no need to set this field vaultRandomID: vaultRandomID, }; } await Promise.all([ db.fileHistoryTbl.setItem(`${vaultRandomID}\t${k1.key}`, k1), db.fileHistoryTbl.setItem(`${vaultRandomID}\t${k2.key}`, k2), ]); }; export const upsertSyncMetaMappingDataByVault = async ( serviceType: SUPPORTED_SERVICES_TYPE, db: InternalDBs, localKey: string, localMTime: number, localSize: number, remoteKey: string, remoteMTime: number, remoteSize: number, remoteExtraKey: string, vaultRandomID: string ) => { const aggregratedInfo: SyncMetaMappingRecord = { localKey: localKey, localMtime: localMTime, localSize: localSize, remoteKey: remoteKey, remoteMtime: remoteMTime, remoteSize: remoteSize, remoteExtraKey: remoteExtraKey, remoteType: serviceType, keyType: localKey.endsWith("/") ? "folder" : "file", vaultRandomID: vaultRandomID, }; await db.syncMappingTbl.setItem( `${vaultRandomID}\t${remoteKey}`, aggregratedInfo ); }; export const getSyncMetaMappingByRemoteKeyAndVault = async ( serviceType: SUPPORTED_SERVICES_TYPE, db: InternalDBs, remoteKey: string, remoteMTime: number, remoteExtraKey: string, vaultRandomID: string ) => { const potentialItem = (await db.syncMappingTbl.getItem( `${vaultRandomID}\t${remoteKey}` )) as SyncMetaMappingRecord; if (potentialItem === null) { // no result was found return undefined; } if ( potentialItem.remoteKey === remoteKey && potentialItem.remoteMtime === remoteMTime && potentialItem.remoteExtraKey === remoteExtraKey && potentialItem.remoteType === serviceType ) { // the result was found return potentialItem; } else { return undefined; } }; export const clearAllSyncMetaMapping = async (db: InternalDBs) => { await db.syncMappingTbl.clear(); }; export const insertSyncPlanRecordByVault = async ( db: InternalDBs, syncPlan: SyncPlanType, vaultRandomID: string ) => { const record = { ts: syncPlan.ts, tsFmt: syncPlan.tsFmt, vaultRandomID: vaultRandomID, remoteType: syncPlan.remoteType, syncPlan: JSON.stringify(syncPlan /* directly stringify */, null, 2), } as SyncPlanRecord; await db.syncPlansTbl.setItem(`${vaultRandomID}\t${syncPlan.ts}`, record); }; export const clearAllSyncPlanRecords = async (db: InternalDBs) => { await db.syncPlansTbl.clear(); }; export const readAllSyncPlanRecordTextsByVault = async ( db: InternalDBs, vaultRandomID: string ) => { const records = [] as SyncPlanRecord[]; await db.syncPlansTbl.iterate((value, key, iterationNumber) => { if (key.startsWith(`${vaultRandomID}\t`)) { records.push(value as SyncPlanRecord); } }); records.sort((a, b) => -(a.ts - b.ts)); // descending if (records === undefined) { return [] as string[]; } else { return records.map((x) => x.syncPlan); } }; /** * We remove records that are older than 7 days or 10000 records. * It's a heavy operation, so we shall not place it in the start up. * @param db */ export const clearExpiredSyncPlanRecords = async (db: InternalDBs) => { const MILLISECONDS_OLD = 1000 * 60 * 60 * 24 * 7; // 7 days const COUNT_TO_MANY = 10000; const currTs = Date.now(); const expiredTs = currTs - MILLISECONDS_OLD; let records = (await db.syncPlansTbl.keys()).map((key) => { const ts = parseInt(key.split("\t")[1]); const expired = ts <= expiredTs; return { ts: ts, key: key, expired: expired, }; }); const keysToRemove = new Set( records.filter((x) => x.expired).map((x) => x.key) ); if (records.length - keysToRemove.size > COUNT_TO_MANY) { // we need to find out records beyond 10000 records records = records.filter((x) => !x.expired); // shrink the array records.sort((a, b) => -(a.ts - b.ts)); // descending records.slice(COUNT_TO_MANY).forEach((element) => { keysToRemove.add(element.key); }); } const ps = [] as Promise<void>[]; keysToRemove.forEach((element) => { ps.push(db.syncPlansTbl.removeItem(element)); }); await Promise.all(ps); }; export const readAllLogRecordTextsByVault = async ( db: InternalDBs, vaultRandomID: string ) => { const records = [] as { ts: number; r: string }[]; await db.loggerOutputTbl.iterate((value, key, iterationNumber) => { if (key.startsWith(`${vaultRandomID}\t`)) { const item = { ts: parseInt(key.split("\t")[1]), r: value as string, }; records.push(item); } }); // while reading the logs, we want it to be ascending records.sort((a, b) => a.ts - b.ts); if (records === undefined) { return [] as string[]; } else { return records.map((x) => x.r); } }; export const insertLoggerOutputByVault = async ( db: InternalDBs, vaultRandomID: string, ...msg: any[] ) => { const ts = Date.now(); const tsFmt = unixTimeToStr(ts); const key = `${vaultRandomID}\t${ts}`; try { const val = [`[${tsFmt}]`, ...msg.map((x) => toText(x))].join(" "); db.loggerOutputTbl.setItem(key, val); } catch (err) { // give up, and let it pass } }; export const clearAllLoggerOutputRecords = async (db: InternalDBs) => { await db.loggerOutputTbl.clear(); }; /** * We remove records that are older than 7 days or 10000 records. * It's a heavy operation, so we shall not place it in the start up. * @param db */ export const clearExpiredLoggerOutputRecords = async (db: InternalDBs) => { const MILLISECONDS_OLD = 1000 * 60 * 60 * 24 * 7; // 7 days const COUNT_TO_MANY = 10000; const currTs = Date.now(); const expiredTs = currTs - MILLISECONDS_OLD; let records = (await db.loggerOutputTbl.keys()).map((key) => { const ts = parseInt(key.split("\t")[1]); const expired = ts <= expiredTs; return { ts: ts, key: key, expired: expired, }; }); const keysToRemove = new Set( records.filter((x) => x.expired).map((x) => x.key) ); if (records.length - keysToRemove.size > COUNT_TO_MANY) { // we need to find out records beyond 10000 records records = records.filter((x) => !x.expired); // shrink the array records.sort((a, b) => -(a.ts - b.ts)); // descending records.slice(COUNT_TO_MANY).forEach((element) => { keysToRemove.add(element.key); }); } const ps = [] as Promise<void>[]; keysToRemove.forEach((element) => { ps.push(db.loggerOutputTbl.removeItem(element)); }); await Promise.all(ps); };
the_stack
import { ICommandPalette, ISplashScreen, IThemeManager } from '@jupyterlab/apputils'; import { IMainMenu, MainMenu } from '@jupyterlab/mainmenu'; import { ISessions } from '../../../main/sessions'; import { JSONObject } from '@lumino/coreutils'; import { Application } from '../../app'; import { DataConnector, StateDB } from '@jupyterlab/statedb'; import { ISettingRegistry, SettingRegistry } from '@jupyterlab/settingregistry'; import { nullTranslator } from '@jupyterlab/translation'; import { Menu, Widget } from '@lumino/widgets'; import { IRouter, JupyterFrontEndPlugin, JupyterLab } from '@jupyterlab/application'; import { ElectronJupyterLab } from '../electron-extension'; import { NativeMenu } from './nativemenu'; import { ThemeManager } from '@jupyterlab/apputils'; import { asyncRemoteRenderer } from '../../../asyncremote'; import { IElectronDataConnector } from '../../../main/utils'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import plugins from '@jupyterlab/apputils-extension'; import log from 'electron-log'; import { createEditMenu, createFileMenu, createKernelMenu, createRunMenu, /*createSettingsMenu, */ createTabsMenu, createViewMenu, CommandIDs as MainMenuExtensionCommandIDs } from '@jupyterlab/mainmenu-extension'; let mainMenuExtension = import('@jupyterlab/mainmenu-extension'); namespace CommandIDs { export const activateServerManager = 'electron-jupyterlab:activate-server-manager'; export const connectToServer = 'electron-jupyterlab:connect-to-server'; } interface IServerManagerMenuArgs extends JSONObject { name: string; type: 'local' | 'remote'; remoteServerId?: number; } const serverManagerPlugin: JupyterFrontEndPlugin<void> = { id: 'jupyter.extensions.server-manager', requires: [ICommandPalette, IMainMenu], activate: ( app: ElectronJupyterLab, palette: ICommandPalette, menu: IMainMenu ) => { let serverState = new StateDB(/*{ namespace: Application.STATE_NAMESPACE }*/); // Insert a local server let servers: IServerManagerMenuArgs[] = [{ name: 'Local', type: 'local' }]; serverState .fetch(Application.SERVER_STATE_ID) .then((data: Application.IRemoteServerState | null) => { if (!data) { createServerManager(app, palette, menu, servers); } else { servers.concat( data.remotes.map(remote => { return { type: 'remote', name: remote.name, id: remote.id } as IServerManagerMenuArgs; }) ); createServerManager(app, palette, menu, servers); } }) .catch(e => { log.log(e); createServerManager(app, palette, menu, servers); }); return null; }, autoStart: true }; function createServerManager( app: ElectronJupyterLab, palette: ICommandPalette, menu: IMainMenu, servers: IServerManagerMenuArgs[] ) { app.commands.addCommand(CommandIDs.activateServerManager, { label: 'Add Server', execute: () => { asyncRemoteRenderer.runRemoteMethod(ISessions.createSession, { state: 'new' }); } }); app.commands.addCommand(CommandIDs.connectToServer, { label: args => args.name as string, execute: (args: IServerManagerMenuArgs) => { asyncRemoteRenderer.runRemoteMethod(ISessions.createSession, { state: args.type, remoteServerId: args.remoteServerId }); } }); const { commands } = app; const serverMenu = new Menu({ commands }); serverMenu.title.label = 'Servers'; for (let s of servers) { serverMenu.addItem({ command: CommandIDs.connectToServer, args: s }); palette.addItem({ command: CommandIDs.connectToServer, args: s, category: 'Servers' }); } serverMenu.addItem({ type: 'separator' }); serverMenu.addItem({ command: CommandIDs.activateServerManager }); menu.addMenu(serverMenu, { rank: 25 }); palette.addItem({ command: CommandIDs.activateServerManager, category: 'Servers' }); } function buildTitleBar(app: ElectronJupyterLab): Widget { let titleBar = new Widget(); ReactDOM.render( // <TitleBar uiState={app.info.uiState} />, <div />, titleBar.node ); return titleBar; } function buildPhosphorMenu(app: ElectronJupyterLab): IMainMenu { let menu = new MainMenu(app.commands); let titleBar = buildTitleBar(app); menu.id = 'jpe-MainMenu-widget'; titleBar.id = 'jpe-TitleBar-widget'; titleBar.addClass('jpe-mod-' + app.info.uiState); let logo = new Widget(); logo.addClass('jp-MainAreaPortraitIcon'); logo.addClass('jpe-JupyterIcon'); logo.id = 'jp-MainLogo'; app.shell.add(logo, 'top'); app.shell.add(menu, 'top'); app.shell.add(titleBar, 'top'); return menu; } function buildNativeMenu( app: ElectronJupyterLab, palette: ICommandPalette, router: IRouter ): IMainMenu { let menu = new NativeMenu(app); const trans = nullTranslator.load('jupyterlab'); let titleBar = buildTitleBar(app); titleBar.id = 'jpe-TitleBar-widget'; titleBar.addClass('jpe-mod-' + app.info.uiState); app.shell.add(titleBar, 'top'); createEditMenu(app, menu.editMenu, trans); createFileMenu(app, menu.fileMenu, router, trans); createKernelMenu(app, menu.kernelMenu, trans); createRunMenu(app, menu.runMenu, trans); // createSettingsMenu(app, menu.settingsMenu, trans); createViewMenu(app, menu.viewMenu, trans); createTabsMenu(app, menu.tabsMenu, app.shell, trans); palette.addItem({ command: MainMenuExtensionCommandIDs.shutdownAllKernels, category: 'Kernel Operations' }); return menu; } /** * Override main menu plugin in @jupyterlab/mainmenu-extension */ mainMenuExtension .then(ext => { /** * A service providing an native menu bar. */ // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore // eslint-disable-next-line @typescript-eslint/no-unused-vars const nativeMainMenuPlugin: JupyterFrontEndPlugin<IMainMenu> = { id: '@jupyterlab/mainmenu-extension:plugin', requires: [ICommandPalette, IRouter], provides: IMainMenu, activate: ( app: ElectronJupyterLab, palette: ICommandPalette, router: IRouter ): IMainMenu | Promise<IMainMenu> => { let menu: IMainMenu | Promise<IMainMenu>; let uiState = app.info.uiState; if (uiState === 'linux' || uiState === 'mac') { menu = buildNativeMenu(app, palette, router); } else { menu = buildPhosphorMenu(app); } return menu; } }; //ext.default = nativeMainMenuPlugin; }) .catch(reason => { log.error( `Failed to load @jupyterlab/mainmenu-extension because ${reason}` ); }); class SettingsConnector extends DataConnector< ISettingRegistry.IPlugin, string > { constructor() { super(); } fetch(id: string): Promise<ISettingRegistry.IPlugin> { return asyncRemoteRenderer.runRemoteMethod( IElectronDataConnector.fetch, id ); } remove(): Promise<void> { return Promise.reject( new Error('Removing setting resource is not supported.') ); } save(id: string, raw: string): Promise<void> { return asyncRemoteRenderer.runRemoteMethod(IElectronDataConnector.save, { id, raw }); } } /** * The default setting registry provider. */ // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore // eslint-disable-next-line @typescript-eslint/no-unused-vars const settingPlugin: JupyterFrontEndPlugin<ISettingRegistry> = { id: '@jupyterlab/apputils-extension:settings', activate: (): ISettingRegistry => { return new SettingRegistry({ connector: new SettingsConnector() }); }, autoStart: true, provides: ISettingRegistry }; /** * The native theme manager provider. */ // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const themesPlugin: JupyterFrontEndPlugin<IThemeManager> = { id: '@jupyterlab/apputils-extension:themes', requires: [ISettingRegistry, ISplashScreen], optional: [ICommandPalette, IMainMenu], activate: ( app: JupyterLab, settingRegistry: ISettingRegistry, splash: ISplashScreen, palette: ICommandPalette | null, mainMenu: IMainMenu | null ): IThemeManager => { const host = app.shell; // const when = app.started; const commands = app.commands; const manager = new ThemeManager({ key: themesPlugin.id, host, settings: settingRegistry, url: app.paths.urls.base + app.paths.urls.themes, splash // when }); commands.addCommand('apputils:change-theme', { label: args => { const theme = args['theme'] as string; return args['isPalette'] ? `Use ${theme} Theme` : theme; }, isToggled: args => args['theme'] === manager.theme, execute: args => { if (args['theme'] === manager.theme) { return; } manager.setTheme(args['theme'] as string); } }); // If we have a main menu, add the theme manager // to the settings menu. if (mainMenu) { const themeMenu = new Menu({ commands }); themeMenu.title.label = 'JupyterLab Theme'; // manager.ready.then(() => { const command = 'apputils:change-theme'; const isPalette = false; manager.themes.forEach(theme => { themeMenu.addItem({ command, args: { isPalette, theme } }); }); mainMenu.settingsMenu.addGroup( [ { type: 'submenu' as Menu.ItemType, submenu: themeMenu } ], 0 ); // }); } // If we have a command palette, add theme switching options to it. if (palette) { // manager.ready.then(() => { const category = 'Settings'; const command = 'apputils:change-theme'; const isPalette = true; manager.themes.forEach(theme => { palette.addItem({ command, args: { isPalette, theme }, category }); }); // }); } return manager; }, autoStart: true, provides: IThemeManager }; /** * Override Main Menu plugin from apputils-extension */ let nPlugins = plugins.map((p: JupyterFrontEndPlugin<any>) => { switch (p.id) { // case settingPlugin.id: // return settingPlugin; // case themesPlugin.id: // return themesPlugin; default: return p; } }); nPlugins.push(serverManagerPlugin); export default nPlugins;
the_stack
import { Op } from "sequelize"; import Database from "../../database"; import { toWhere } from "../../utils"; import { getDatabase } from ".."; describe('utils.toWhere', () => { let db: Database; beforeAll(() => { db = getDatabase(); db.table({ name: 'users', }); db.table({ name: 'posts', fields: [ { type: 'string', name: 'title' }, { type: 'belongsTo', name: 'user', } ] }); db.table({ name: 'categories', fields: [ { type: 'hasMany', name: 'posts', } ], }); }); afterAll(() => db.close()); describe('single', () => { it('=', () => { const where = toWhere({ id: 12, }); expect(where).toEqual({ id: 12, }); }); it('Op.eq', () => { const where = toWhere({ id: { eq: 12 }, }); expect(where).toEqual({ id: { [Op.eq]: 12, }, }); }); it('Op.ilike', () => { const where = toWhere({ id: { ilike: 'val1' }, }); expect(where).toEqual({ id: { [Op.iLike]: 'val1', }, }); }); it('Op.ilike', () => { const where = toWhere({ 'id.ilike': 'val1', }); expect(where).toEqual({ id: { [Op.iLike]: 'val1', }, }); }); it('Op.is null', () => { const where = toWhere({ 'id.is': null, }); expect(where).toEqual({ id: { [Op.is]: null, }, }); }); it('Op.in', () => { const where = toWhere({ id: { in: [12] }, }); expect(where).toEqual({ id: { [Op.in]: [12], }, }); }); it('Op.in', () => { const where = toWhere({ 'id.in': [11, 12], }); expect(where).toEqual({ id: { [Op.in]: [11, 12], }, }); }); it('Op.lt', () => { expect(toWhere({ 'id.lt': 1 })).toEqual({ id: { [Op.lt]: 1 } }); }); it('Op.between', () => { expect(toWhere({ 'id.between': [1, 2] })).toEqual({ id: { [Op.between]: [1, 2] } }); }); it('Op.between date', () => { expect(toWhere({ 'id.between': ['2020-11-01T00:00:00.000Z', '2020-12-01T00:00:00.000Z'] })).toEqual({ id: { [Op.between]: ['2020-11-01T00:00:00.000Z', '2020-12-01T00:00:00.000Z'] } }); }); it('Op.$null', () => { expect(toWhere({ 'id.$null': true })).toEqual({ id: { [Op.is]: null } }); }); it('Op.$null', () => { expect(toWhere({ 'id.$null': false })).toEqual({ id: { [Op.is]: null } }); }); it('Op.$null', () => { expect(toWhere({ 'id.$null': null })).toEqual({ id: { [Op.is]: null } }); }); it('Op.$notNull', () => { expect(toWhere({ 'id.$notNull': true })).toEqual({ id: { [Op.not]: null } }); }); it('Op.$notNull', () => { expect(toWhere({ 'id.$notNull': false })).toEqual({ id: { [Op.not]: null } }); }); it('Op.$notNull', () => { expect(toWhere({ 'id.$notNull': null })).toEqual({ id: { [Op.not]: null } }); }); it('Op.$includes', () => { expect(toWhere({ 'string.$includes': 'a' })).toEqual({ string: { [Op.iLike]: '%a%' } }); }); it('Op.$notIncludes', () => { expect(toWhere({ 'string.$notIncludes': 'a' })).toEqual({ string: { [Op.notILike]: '%a%' } }); }); it('Op.$startsWith', () => { expect(toWhere({ 'string.$startsWith': 'a' })).toEqual({ string: { [Op.iLike]: 'a%' } }); }); it('Op.$notStartsWith', () => { expect(toWhere({ 'string.$notStartsWith': 'a' })).toEqual({ string: { [Op.notILike]: 'a%' } }); }); it('Op.$endsWith', () => { expect(toWhere({ 'string.$endsWith': 'a' })).toEqual({ string: { [Op.iLike]: '%a' } }); }); it('Op.$notEndsWith', () => { expect(toWhere({ 'string.$notEndsWith': 'a' })).toEqual({ string: { [Op.notILike]: '%a' } }); }); // TODO(test): 需要把之前的运算符换成 literal 表达 it.skip('Op.$anyOf', () => { expect(toWhere({ 'array.$anyOf': ['a', 'b'] })).toEqual({ array: { [Op.or]: [{ [Op.contains]: 'a' }, { [Op.contains]: 'b' }] } }); }); // TODO(bug) it.skip('Op.$noneOf', () => { expect(toWhere({ 'array.$noneOf': ['a', 'b'] })).toEqual({ array: { [Op.not]: [{ [Op.contains]: 'a' }, { [Op.contains]: 'b' }] } }); }); }); describe('group by logical operator', () => { it('field.or', () => { expect(toWhere({ 'id.or': [1, 2] })).toEqual({ id: { [Op.or]: [1, 2] } }); }); it('field.and', () => { expect(toWhere({ 'id.and': [1, 2] })).toEqual({ id: { [Op.and]: [1, 2] } }); }); it('root or', () => { expect(toWhere({ or: [{ a: 1 }, { b: 2 }] })).toEqual({ [Op.or]: [{ a: 1 }, { b: 2 }] }); }); it('root and', () => { expect(toWhere({ and: [{ a: 1 }, { b: 2 }] })).toEqual({ [Op.and]: [{ a: 1 }, { b: 2 }] }); }); it('root "and" and "or"', () => { expect(toWhere({ and: [{ a: 1 }, { b: 2 }], or: [{ c: 3 }, { d: 4 }] })).toEqual({ [Op.and]: [{ a: 1 }, { b: 2 }], [Op.or]: [{ c: 3 }, { d: 4 }] }); }); it('root "and" and field', () => { expect(toWhere({ and: [{ a: 1 }, { b: 2 }], 'id.or': [3, 4] })).toEqual({ [Op.and]: [{ a: 1 }, { b: 2 }], id: { [Op.or]: [3, 4] } }); }); it('or in or (not fully parsed)', () => { expect(toWhere({ or: [{ a: 1 }, { 'b.or': [3, 4] }], })).toEqual({ [Op.or]: [{ a: 1 }, { b: { [Op.or]: [3, 4] } }], }); }); it('or in or (parsed)', () => { expect(toWhere({ or: [{ a: 1 }, { b: { or: [3, 4] } }], })).toEqual({ [Op.or]: [{ a: 1 }, { b: { [Op.or]: [3, 4] } }], }); }); it('or in or in or', () => { expect(toWhere({ or: [{ a: 1 }, { or: { b: 3, c: { or: [5, 6] } } }], })).toEqual({ [Op.or]: [{ a: 1 }, { [Op.or]: { b: 3, c: { [Op.or]: [5, 6] } } }], }); }); it('or in and', () => { expect(toWhere({ and: [{ a: 1 }, { 'b.or': [3, 4] }], })).toEqual({ [Op.and]: [{ a: 1 }, { b: { [Op.or]: [3, 4] } }], }); }); it('and in or', () => { expect(toWhere({ or: [{ a: 1 }, { and: [{ c: 3 }, { d: 4 }] }], })).toEqual({ [Op.or]: [{ a: 1 }, { [Op.and]: [{ c: 3 }, { d: 4 }] }], }); }); it('logical and other comparation', () => { expect(toWhere({ or: [{ a: 1 }, { b: { gt: 2 } }], })).toEqual({ [Op.or]: [{ a: 1 }, { b: { [Op.gt]: 2 } }], }); }); it('logical and with condition operator in field', () => { const Post = db.getModel('posts'); const data = toWhere({ "and": [{ "title.eq": '23' }] }, { model: Post }); expect(data).toEqual({ [Op.and]: [ { title: { [Op.eq]: '23' } } ] }); }); // TODO: bug it.skip('field as "or"', () => { expect(toWhere({ or: 1, })).toEqual({ or: 1, }); }); // TODO: bug it.skip('or for field as "or"', () => { expect(toWhere({ 'or.or': [1, 2], })).toEqual({ or: { [Op.or]: [1, 2] }, }); }); }); describe('association', () => { const toWhereExpect = (options: any) => { const Category = db.getModel('categories'); const where = toWhere(options, { associations: Category.associations, }); return expect(where); } it('logical and other comparation', () => { toWhereExpect({ or: [ { a: 1 }, { b: { gt: 2 } }, { and: [ { 'c.and': [ { gt: 3, lt: 6 } ], }, ] }, ], }) .toEqual({ [Op.or]: [ { a: 1 }, { b: { [Op.gt]: 2 } }, { [Op.and]: [ { c: { [Op.and]: [ { [Op.gt]: 3, [Op.lt]: 6 } ] }, } ] }, ], }); }); it('with included association where', () => { toWhereExpect({ col1: 'val1', posts: { name: { ilike: 'aa', }, col2: { lt: 2, }, user: { col1: 12, 'col2.lt': 2, }, }, 'posts.col3.ilike': 'aa', }).toEqual({ col1: 'val1', $__include: { posts: { name: { [Op.iLike]: 'aa', }, col2: { [Op.lt]: 2, }, col3: { [Op.iLike]: 'aa', }, $__include: { user: { col1: 12, col2: { [Op.lt]: 2, }, }, }, }, }, }); }); // TODO: 是否要考虑跨关联表的逻辑分组这种情况 it.skip('logical across association', () => { toWhereExpect({ or: { status: 1, posts: { status: 1 } } }).toEqual({ }) }); }); });
the_stack
import Promise from 'bluebird'; import crypto from 'crypto'; import httpStatusCodes from 'http-status'; import { Readable, Writable } from 'stream'; import urlTemplate from 'url-template'; import BoxClient from '../box-client'; import errors from '../util/errors'; import urlPath from '../util/url-path'; const ChunkedUploader = require('../chunked-uploader'); // ----------------------------------------------------------------------------- // Typedefs // ----------------------------------------------------------------------------- /** * Enum of valid x-rep- hint values for generating representation info * * @readonly * @enum {FileRepresentationType} */ enum FileRepresentationType { PDF = '[pdf]', THUMBNAIL = '[jpg?dimensions=320x320]', IMAGE_MEDIUM = '[jpg?dimensions=1024x1024][png?dimensions=1024x1024]', IMAGE_LARGE = '[jpg?dimensions=2048x2048][png?dimensions=2048x2048]', EXTRACTED_TEXT = '[extracted_text]', } /** * @typedef {Object} UploadPart * @property {string} part_id An 8-character hexadecimal string identifying the part * @property {int} offset The byte offset of the part within the whole file * @property {int} size The size of the part in bytes */ type UploadPart = { part_id: string; offset: number; size: number; }; /** * Enum of valid lock types * * @readonly * @enum {LockType} */ enum LockType { LOCK = 'lock', UNLOCK = 'unlock', } // ----------------------------------------------------------------------------- // Private // ----------------------------------------------------------------------------- // Base path for all files endpoints const BASE_PATH = '/files', VERSIONS_SUBRESOURCE = '/versions', WATERMARK_SUBRESOURCE = '/watermark', UPLOAD_SESSION_SUBRESOURCE = '/upload_sessions', ZIP_DOWNLOAD_PATH = '/zip_downloads'; /** * Returns the multipart form value for file upload metadata. * @param {string} parentFolderID - the ID of the parent folder to upload to * @param {string} filename - the file name that the uploaded file should have * @param {Object} [options] - Optional metadata * @returns {Object} - the form value expected by the API for the 'metadata' key * @private */ function createFileMetadataFormData( parentFolderID: string, filename: string, options?: Record<string, any> ) { // Although the filename and parent folder ID can be specified without using a // metadata form field, Platform has recommended that we use the metadata form // field to specify these parameters (one benefit is that UTF-8 characters can // be specified in the filename). var metadata = { name: filename, parent: { id: parentFolderID }, }; Object.assign(metadata, options); return JSON.stringify(metadata); } /** * Returns the multipart form value for file upload content. * @param {string|Buffer|Stream} content - the content of the file being uploaded * @param {Object} options - options for the content * @returns {Object} - the form value expected by the API for the 'content' key * @private */ function createFileContentFormData( content: string | Buffer | Readable, options?: Record<string, any> ) { // The upload API appears to look for a form field that contains a filename // property and assume that this form field contains the file content. Thus, // the value of name does not actually matter (as long as it does not conflict // with other field names). Similarly, the value of options.filename does not // matter either (as long as it exists), since the upload API will use the // filename specified in the metadata form field instead. return { value: content, options: Object.assign({ filename: 'unused' }, options), }; } /** * Poll the representation info URL until representation is generated, * then return content URL template. * @param {BoxClient} client The client to use for making API calls * @param {string} infoURL The URL to use for getting representation info * @returns {Promise<string>} A promise resolving to the content URL template */ function pollRepresentationInfo(client: BoxClient, infoURL: string) { return client.get(infoURL).then((response: any /* FIXME */) => { if (response.statusCode !== 200) { throw errors.buildUnexpectedResponseError(response); } var info = response.body; switch (info.status.state) { case 'success': case 'viewable': case 'error': return info; case 'none': case 'pending': return Promise.delay(1000).then(() => pollRepresentationInfo(client, infoURL) ); default: throw new Error(`Unknown representation status: ${info.status.state}`); } }); } // ------------------------------------------------------------------------------ // Public // ------------------------------------------------------------------------------ /** * Simple manager for interacting with all 'File' endpoints and actions. * * @param {BoxClient} client The Box API Client that is responsible for making calls to the API * @constructor */ class Files { client: BoxClient; representation!: typeof FileRepresentationType; constructor(client: BoxClient) { // Attach the client, for making API calls this.client = client; } /** * Requests a file object with the given ID. * * API Endpoint: '/files/:fileID' * Method: GET * * @param {string} fileID - Box ID of the file being requested * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed the file information if it was acquired successfully * @returns {Promise<Object>} A promise resolving to the file object */ get(fileID: string, options?: Record<string, any>, callback?: Function) { var params = { qs: options, }; var apiPath = urlPath(BASE_PATH, fileID); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Requests a download URL for a given file. * * API Endpoint: '/files/:fileID/content' * Method: GET * Special Expected Responses: * 202 ACCEPTED - Download isn't available yet. Returns an error. * 302 FOUND - Download is available. A Download URL is returned. * * @param {string} fileID - Box ID of the file being requested * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed the download URL if request was successful. * @returns {Promise<string>} A promise resolving to the file's download URL */ getDownloadURL( fileID: string, options?: Record<string, any>, callback?: Function ) { var params = { qs: options, }; var apiPath = urlPath(BASE_PATH, fileID, '/content'); // Handle Special API Response return this.client .get(apiPath, params) .then((response: any /* FIXME */) => { switch (response.statusCode) { // 302 - Found // No data returned, but the location header points to a download link for that file. case httpStatusCodes.FOUND: return response.headers.location; // 202 - Download isn't ready yet. case httpStatusCodes.ACCEPTED: throw errors.buildResponseError( response, 'Download not ready at this time' ); // Unexpected Response default: throw errors.buildUnexpectedResponseError(response); } }) .asCallback(callback); } /** * Requests a Readable Stream for the given file ID. * * API Endpoint: '/files/:fileID/content' * Method: GET * Special Expected Responses: * 202 ACCEPTED - Download isn't available yet. Returns an error. * 302 FOUND - Download is available. A Download stream is returned. * * @param {string} fileID - Box ID of the file being requested * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {string} [options.version] - ID of the version of this file to download * @param {int[]} [options.byteRange] - starting and ending bytes of the file to read, e.g. [0, 99] to read the first 100 bytes * @param {Function} [callback] - passed the readable stream if request was successful * @returns {Promise<Readable>} A promise resolving for the file stream */ getReadStream( fileID: string, options?: { version?: string; byteRange?: number[]; }, callback?: Function ) { options = options || {}; var downloadStreamOptions = { streaming: true, headers: {} as Record<string, any>, }; if (options.byteRange) { var range = options.byteRange; delete options.byteRange; downloadStreamOptions.headers.Range = `bytes=${range[0]}-${range[1]}`; } // Get the download URL to download from return ( this.getDownloadURL(fileID, options) // Return a read stream to download the file .then((url: string) => this.client.get(url, downloadStreamOptions)) .asCallback(callback) ); } /** * Requests a Thumbnail for a given file. * * API Endpoint: '/files/:fileID/thumbnail.png' * Method: GET * Special Expected Responses: * 200 OK - Thumbnail available. Returns a thumbnail file. * 202 ACCEPTED - Thumbnail isn't available yet. Returns a `location` URL for a generic placeholder thumbnail. * 302 FOUND - Unable to generate thumbnail. Returns a `location` URL for a generic placeholder thumbnail. * * @param {string} fileID - Box ID of the file being requested * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed the thumbnail file or the URL to a placeholder thumbnail if successful. * @returns {Promise<Object>} A promise resolving to the thumbnail information * @deprecated use getRepresentationContent() instead */ getThumbnail( fileID: string, options?: Record<string, any>, callback?: Function ) { var params = { qs: options, json: false, }; var apiPath = urlPath(BASE_PATH, fileID, '/thumbnail.png'); // Handle Special API Response return this.client .get(apiPath, params) .then((response: any /* FIXME */) => { switch (response.statusCode) { // 202 - Thumbnail will be generated, but is not ready yet // 302 - Thumbnail can not be generated // return the url for a thumbnail placeholder case httpStatusCodes.ACCEPTED: case httpStatusCodes.FOUND: return { statusCode: response.statusCode, location: response.headers.location, }; // 200 - Thumbnail image recieved // return the thumbnail file case httpStatusCodes.OK: return { statusCode: response.statusCode, file: response.body, }; // Unexpected Response default: throw errors.buildUnexpectedResponseError(response); } }) .asCallback(callback); } /** * Gets the comments on a file. * * API Endpoint: '/files/:fileID/comments' * Method: GET * * @param {string} fileID - Box file id of the file * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - passed the file comments if they were successfully acquired * @returns {Promise<Object>} A promise resolving to the collection of comments */ getComments( fileID: string, options?: Record<string, any>, callback?: Function ) { var params = { qs: options, }; var apiPath = urlPath(BASE_PATH, fileID, '/comments'); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Update some information about a given file. * * API Endpoint: '/files/:fileID' * Method: PUT * * @param {string} fileID - Box ID of the file being requested * @param {Object} updates - File fields to update * @param {string} [updates.etag] Only apply the updates if the file etag matches * @param {Function} [callback] - Passed the updated file information if it was acquired successfully * @returns {Promise<Object>} A promise resolving to the update file object */ update( fileID: string, updates: { [key: string]: any; etag?: string; }, callback?: Function ) { var params: Record<string, any> = { body: updates, }; if (updates && updates.etag) { params.headers = { 'If-Match': updates.etag, }; delete updates.etag; } var apiPath = urlPath(BASE_PATH, fileID); return this.client.wrapWithDefaultHandler(this.client.put)( apiPath, params, callback ); } /** * Add a file to a given collection * * API Endpoint: '/files/:fileID' * Method: PUT * * @param {string} fileID - The file to add to the collection * @param {string} collectionID - The collection to add the file to * @param {Function} [callback] - Passed the updated file if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the updated file object */ addToCollection(fileID: string, collectionID: string, callback?: Function) { return this.get(fileID, { fields: 'collections' }) .then((data: Record<string, any>) => { var collections = data.collections || []; // Convert to correct format collections = collections.map((c: any /* FIXME */) => ({ id: c.id })); if (!collections.find((c: any /* FIXME */) => c.id === collectionID)) { collections.push({ id: collectionID }); } return this.update(fileID, { collections }); }) .asCallback(callback); } /** * Remove a file from a given collection * * API Endpoint: '/files/:fileID' * Method: PUT * * @param {string} fileID - The file to remove from the collection * @param {string} collectionID - The collection to remove the file from * @param {Function} [callback] - Passed the updated file if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the updated file object */ removeFromCollection( fileID: string, collectionID: string, callback?: Function ) { return this.get(fileID, { fields: 'collections' }) .then((data: any /* FIXME */) => { var collections = data.collections || []; // Convert to correct object format and remove the specified collection collections = collections .map((c: any /* FIXME */) => ({ id: c.id })) .filter((c: any /* FIXME */) => c.id !== collectionID); return this.update(fileID, { collections }); }) .asCallback(callback); } /** * Move a file into a new parent folder. * * API Endpoint: '/files/:fileID' * Method: PUT * * @param {string} fileID - The Box ID of the file being requested * @param {string} newParentID - The Box ID for the new parent folder. '0' to move to All Files. * @param {Function} [callback] - Passed the updated file information if it was acquired successfully * @returns {Promise<Object>} A promise resolving to the updated file object */ move(fileID: string, newParentID: string, callback?: Function) { var params = { body: { parent: { id: newParentID, }, }, }; var apiPath = urlPath(BASE_PATH, fileID); return this.client.wrapWithDefaultHandler(this.client.put)( apiPath, params, callback ); } /** * Copy a file into a new folder. * * API Endpoint: '/files/:fileID/copy * Method: POST * * @param {string} fileID - The Box ID of the file being requested * @param {string} newParentID - The Box ID for the new parent folder. '0' to copy to All Files. * @param {Object} [options] - Optional parameters for the copy operation, can be left null in most cases * @param {string} [options.name] - A new name to use if there is an identically-named item in the new parent folder * @param {Function} [callback] - passed the new file info if call was successful * @returns {Promise<Object>} A promise resolving to the new file object */ copy( fileID: string, newParentID: string, options?: | { name?: string; } | Function, callback?: Function ) { // @NOTE(mwiller) 2016-10-25: Shuffle arguments to maintain backward compatibility // This can be removed at the v2.0 update if (typeof options === 'function') { callback = options; options = {}; } options = options || {}; (options as Record<string, any>).parent = { id: newParentID, }; var params = { body: options, }; var apiPath = urlPath(BASE_PATH, fileID, '/copy'); return this.client.wrapWithDefaultHandler(this.client.post)( apiPath, params, callback ); } /** * Delete a given file. * * API Endpoint: '/files/:fileID' * Method: DELETE * * @param {string} fileID - Box ID of the file being requested * @param {Object} [options] Optional parameters * @param {string} [options.etag] Only delete the file if the etag value matches * @param {Function} [callback] - Empty response body passed if successful. * @returns {Promise<void>} A promise resolving to nothing */ delete( fileID: string, options?: | { [key: string]: any; etag?: string; } | Function, callback?: Function ) { // Switch around arguments if necessary for backwards compatibility if (typeof options === 'function') { callback = options; options = {}; } var params: Record<string, any> = {}; if (options && options.etag) { params.headers = { 'If-Match': options.etag, }; } var apiPath = urlPath(BASE_PATH, fileID); return this.client.wrapWithDefaultHandler(this.client.del)( apiPath, params, callback ); } /** * Get preflight information for a new file upload. Without any file data, * this will return an upload URL and token to be used when uploading the file. * Using this upload URL will allow for the fastest upload, and the one-time * token can be passed to a worker or other client to actually perform the * upload with. If file data (e.g. size, parent, name) is passed, it will be * validated as if the actual file were being uploaded. This enables checking * of preconditions such as name uniqueness and available storage space before * attempting a large file upload. * * API Endpoint: '/files/content' * Method: OPTIONS * * @param {string} parentFolderID - The id of the parent folder to upload to * @param {Object} [fileData] - Optional data about the file to be uploaded * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Called with upload data if successful, or err if the upload would not succeed * @returns {Promise<Object>} A promise resolving to the upload data */ preflightUploadFile( parentFolderID: string, fileData?: Record<string, any>, options?: Record<string, any>, callback?: Function ) { var params = { body: { parent: { id: parentFolderID, }, }, qs: options, }; if (fileData) { Object.assign(params.body, fileData); } var apiPath = urlPath(BASE_PATH, '/content'); return this.client.wrapWithDefaultHandler(this.client.options)( apiPath, params, callback ); } /** * Get preflight information for a file version upload. Without any file data, * this will return an upload URL and token to be used when uploading the file. * Using this upload URL will allow for the fastest upload, and the one-time * token can be passed to a worker or other client to actually perform the * upload with. If file data (e.g. size, parent, name) is passed, it will be * validated as if the actual file were being uploaded. This enables checking * of preconditions such as name uniqueness and available storage space before * attempting a large file upload. * * API Endpoint: '/files/:fileID/content' * Method: OPTIONS * * @param {string} fileID - The file ID to which a new version will be uploaded * @param {Object} [fileData] - Optional data about the file to be uploaded * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Called with upload data if successful, or err if the upload would not succeed * @returns {Promise<Object>} A promise resolving to the upload data */ preflightUploadNewFileVersion( fileID: string, fileData?: Record<string, any>, options?: Record<string, any>, callback?: Function ) { var params: Record<string, any> = { qs: options, }; if (fileData) { params.body = fileData; } var apiPath = urlPath(BASE_PATH, fileID, '/content'); return this.client.wrapWithDefaultHandler(this.client.options)( apiPath, params, callback ); } /** * If there are previous versions of this file, this method can be used to promote one of the older * versions to the top of the stack. This actually mints a copy of the old version and puts it on * the top of the versions stack. The file will have the exact same contents, the same SHA1/etag, * and the same name as the original. Other properties such as comments do not get updated to their former values. * * API Endpoint: '/files/:fileID/versions/current' * Method: POST * * @param {string} fileID - The file ID which version will be promoted * @param {string} versionID - The ID of the file_version that you want to make current * @param {Function} [callback] - Passed the promoted file version information if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the promoted file version */ promoteVersion(fileID: string, versionID: string, callback?: Function) { var apiPath = urlPath(BASE_PATH, fileID, VERSIONS_SUBRESOURCE, '/current'), params = { body: { type: 'file_version', id: versionID, }, }; return this.client.wrapWithDefaultHandler(this.client.post)( apiPath, params, callback ); } /** * Uploads a new file. Unlike non-upload methods, this method will not perform any retries. * This method currently does not support any optional parameters such as contentModifiedAt. * * API Endpoint: '/files/content' * Method: POST * * @param {string} parentFolderID - the id of the parent folder to upload to * @param {string} filename - the file name that the uploaded file should have * @param {string|Buffer|ReadStream} content - the content of the file. It can be a string, a Buffer, or a read stream * (like that returned by fs.createReadStream()). * @param {Object} [options] - Optional parameters * @param {string} [options.content_created_at] - RFC 3339 timestamp when the file was created * @param {string} [options.content_modified_at] - RFC 3339 timestamp when the file was last modified * @param {int} [options.content_length] - Optional length of the content. Required if content is a read stream of any type other than fs stream. * @param {Function} [callback] - called with data about the upload if successful, or an error if the * upload failed * @returns {Promise<Object>} A promise resolving to the uploaded file */ uploadFile( parentFolderID: string, filename: string, content: string | Buffer | Readable, options?: | { content_created_at?: string; content_modified_at?: string; content_length?: number; } | Function, callback?: Function ) { // Shuffle around optional parameter if (typeof options === 'function') { callback = options; options = {}; } var formOptions: Record<string, any> = {}; if (options && options.hasOwnProperty('content_length')) { formOptions.knownLength = options.content_length; // Delete content_length from options so it's not added to the attributes of the form delete options.content_length; } var apiPath = urlPath(BASE_PATH, '/content'), multipartFormData = { attributes: createFileMetadataFormData( parentFolderID, filename, options ), content: createFileContentFormData(content, formOptions), }; return this.client.wrapWithDefaultHandler(this.client.upload)( apiPath, null, multipartFormData, callback ); } /** * Uploads a new version of a file. Unlike non-upload methods, this method will not perform any retries. * This method currently does not support any optional parameters such as contentModifiedAt. * * API Endpoint: '/files/:fileID/content' * Method: POST * * @param {string} fileID - the id of the file to upload a new version of * @param {string|Buffer|Stream} content - the content of the file. It can be a string, a Buffer, or a read stream * (like that returned by fs.createReadStream()). * @param {Object} [options] - Optional parameters * @param {string} [options.content_modified_at] - RFC 3339 timestamp when the file was last modified * @param {string} [options.name] - A new name for the file * @param {int} [options.content_length] - Optional length of the content. Required if content is a read stream of any type other than fs stream. * @param {Function} [callback] - called with data about the upload if successful, or an error if the * upload failed * @returns {Promise<Object>} A promise resolving to the uploaded file */ uploadNewFileVersion( fileID: string, content: string | Buffer | Readable, options?: | { content_modified_at?: string; name?: string; content_length?: number; } | Function, callback?: Function ) { // Shuffle around optional parameter if (typeof options === 'function') { callback = options; options = {}; } var apiPath = urlPath(BASE_PATH, fileID, '/content'), multipartFormData: Record<string, any> = {}; var formOptions: Record<string, any> = {}; if (options) { if (options.hasOwnProperty('content_length')) { formOptions.knownLength = options.content_length; // Delete content_length from options so it's not added to the attributes of the form delete options.content_length; } multipartFormData.attributes = JSON.stringify(options); } multipartFormData.content = createFileContentFormData(content, formOptions); return this.client.wrapWithDefaultHandler(this.client.upload)( apiPath, null, multipartFormData, callback ); } /** * Retrieves all metadata associated with a file. * * API Endpoint: '/files/:fileID/metadata' * Method: GET * * @param {string} fileID - the ID of the file to get metadata for * @param {Function} [callback] - called with an array of metadata when successful * @returns {Promise<Object>} A promise resolving to a collection of metadata on the file */ getAllMetadata(fileID: string, callback?: Function) { var apiPath = urlPath(BASE_PATH, fileID, 'metadata'); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, null, callback ); } /** * Retrieve a single metadata template instance for a file. * * API Endpoint: '/files/:fileID/metadata/:scope/:template' * Method: GET * * @param {string} fileID - The ID of the file to retrive the metadata of * @param {string} scope - The scope of the metadata template, e.g. "global" * @param {string} template - The metadata template to retrieve * @param {Function} [callback] - Passed the metadata template if successful * @returns {Promise<Object>} A promise resolving to the metadata template */ getMetadata( fileID: string, scope: string, template: string, callback?: Function ) { var apiPath = urlPath(BASE_PATH, fileID, 'metadata', scope, template); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, null, callback ); } /** * Adds metadata to a file. Metadata must either match a template schema or * be placed into the unstructured "properties" template in global scope. * * API Endpoint: '/files/:fileID/metadata/:scope/:template' * Method: POST * * @param {string} fileID - The ID of the file to add metadata to * @param {string} scope - The scope of the metadata template, e.g. "enterprise" * @param {string} template - The metadata template schema to add * @param {Object} data - Key/value pairs tp add as metadata * @param {Function} [callback] - Called with error if unsuccessful * @returns {Promise<Object>} A promise resolving to the new metadata */ addMetadata( fileID: string, scope: string, template: string, data: Record<string, any>, callback?: Function ) { var apiPath = urlPath(BASE_PATH, fileID, 'metadata', scope, template), params = { body: data, }; return this.client.wrapWithDefaultHandler(this.client.post)( apiPath, params, callback ); } /** * Updates a metadata template instance with JSON Patch-formatted data. * * API Endpoint: '/files/:fileID/metadata/:scope/:template' * Method: PUT * * @param {string} fileID - The file to update metadata for * @param {string} scope - The scope of the template to update * @param {string} template - The template to update * @param {Object} patch - The patch data * @param {Function} [callback] - Called with updated metadata if successful * @returns {Promise<Object>} A promise resolving to the updated metadata */ updateMetadata( fileID: string, scope: string, template: string, patch: Record<string, any>, callback?: Function ) { var apiPath = urlPath(BASE_PATH, fileID, 'metadata', scope, template), params = { body: patch, headers: { 'Content-Type': 'application/json-patch+json', }, }; return this.client.wrapWithDefaultHandler(this.client.put)( apiPath, params, callback ); } /** * Sets metadata on a file, overwriting any metadata that exists for the provided keys. * * @param {string} fileID - The file to set metadata on * @param {string} scope - The scope of the metadata template * @param {string} template - The key of the metadata template * @param {Object} metadata - The metadata to set * @param {Function} [callback] - Called with updated metadata if successful * @returns {Promise<Object>} A promise resolving to the updated metadata */ setMetadata( fileID: string, scope: string, template: string, metadata: Record<string, any>, callback?: Function ) { return this.addMetadata(fileID, scope, template, metadata) .catch((err: any /* FIXME */) => { if (err.statusCode !== 409) { throw err; } // Metadata already exists on the file; update instead var updates = Object.keys(metadata).map((key) => ({ op: 'add', path: `/${key}`, value: metadata[key], })); return this.updateMetadata(fileID, scope, template, updates); }) .asCallback(callback); } /** * Deletes a metadata template from a file. * * API Endpoint: '/files/:fileID/metadata/:scope/:template' * Method: DELETE * * @param {string} fileID - The ID of the file to remove metadata from * @param {string} scope - The scope of the metadata template * @param {string} template - The template to remove from the file * @param {Function} [callback] - Called with nothing if successful, error otherwise * @returns {Promise<void>} A promise resolving to nothing */ deleteMetadata( fileID: string, scope: string, template: string, callback?: Function ) { var apiPath = urlPath(BASE_PATH, fileID, 'metadata', scope, template); return this.client.wrapWithDefaultHandler(this.client.del)( apiPath, null, callback ); } /** * Permanently deletes an item that is in the trash. The item will no longer exist in Box. This action cannot be undone. * * API Endpoint: '/files/:fileID/trash' * Method: DELETE * * @param {string} fileID - The ID of the file to remove metadata from * @param {Object} [options] Optional parameters * @param {string} [options.etag] Only delete the file if the etag matches * @param {Function} [callback] - Called with nothing if successful, error otherwise * @returns {Promise<void>} A promise resolving to nothing */ deletePermanently( fileID: string, options?: | { [key: string]: any; etag?: string; } | Function, callback?: Function ) { if (typeof options === 'function') { callback = options; options = {}; } var params: Record<string, any> = {}; if (options && options.etag) { params.headers = { 'If-Match': options.etag, }; } var apiPath = urlPath(BASE_PATH, fileID, '/trash'); return this.client.wrapWithDefaultHandler(this.client.del)( apiPath, params, callback ); } /** * Retrieves a file that has been moved to the trash. * * API Endpoint: '/files/:fileID/trash' * Method: GET * * @param {string} fileID - The ID of the file being requested * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed the trashed file information if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the trashed file */ getTrashedFile( fileID: string, options?: Record<string, any>, callback?: Function ) { var params = { qs: options, }; var apiPath = urlPath(BASE_PATH, fileID, 'trash'); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Retrieves all of the tasks for given file. * * API Endpoint: '/files/:fileID/tasks' * Method: GET * * @param {string} fileID - The ID of the file to get tasks for * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed the file tasks if successful, error otherwise * @returns {Promise<Object>} A promise resolving to a collections of tasks on the file */ getTasks(fileID: string, options?: Record<string, any>, callback?: Function) { var params = { qs: options, }; var apiPath = urlPath(BASE_PATH, fileID, '/tasks'); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Used to retrieve an expiring URL for creating an embedded preview session. * The URL will expire after 60 seconds and the preview session will expire after 60 minutes. * * API Endpoint: '/files/:fileID?fields=expiring_embed_link' * Method: GET * * @param {string} fileID - The ID of the file to generate embed link for * @param {Function} [callback] - Passed with the embed link if successful, error otherwise * @returns {Promise<string>} A promise resolving to the file embed link URL */ getEmbedLink(fileID: string, callback?: Function) { var params = { qs: { fields: 'expiring_embed_link', }, }; var apiPath = urlPath(BASE_PATH, fileID); return this.client .get(apiPath, params) .then((response: any /* FIXME */) => { if (response.statusCode !== httpStatusCodes.OK) { throw errors.buildUnexpectedResponseError(response); } return response.body.expiring_embed_link.url; }) .asCallback(callback); } /** * Locks a file. * * API Endpoint: '/files/:fileID' * Method: PUT * * @param {string} fileID - The ID of the file to lock * @param {Object} [options] - Optional parameters, can be left null in most cases * @param {?string} [options.expires_at] - The time the lock expires * @param {boolean} [options.is_download_prevented] - Whether or not the file can be downloaded while locked * @param {Function} [callback] - Passed with the locked file information if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the locked file object */ lock( fileID: string, options?: { expires_at?: string; is_download_prevented?: boolean; }, callback?: Function ) { var apiPath = urlPath(BASE_PATH, fileID), params = { body: { lock: { type: LockType.LOCK, }, }, }; Object.assign(params.body.lock, options); return this.client.wrapWithDefaultHandler(this.client.put)( apiPath, params, callback ); } /** * Unlocks a file. * * API Endpoint: '/files/:fileID' * Method: PUT * * @param {string} fileID - The ID of the file to unlock * @param {Function} [callback] - Passed with the unlocked file information if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the unlocked file object */ unlock(fileID: string, callback?: Function) { var apiPath = urlPath(BASE_PATH, fileID), params = { body: { lock: null, }, }; return this.client.wrapWithDefaultHandler(this.client.put)( apiPath, params, callback ); } /** * Restores an item that has been moved to the trash. Default behavior is to * restore the item to the folder it was in before it was moved to the trash. * If that parent folder no longer exists or if there is now an item with the * same name in that parent folder, the new parent folder and/or new name will * need to be included in the request. * * API Endpoint: '/files/:fileID' * Method: POST * * @param {string} fileID - The ID of the file to restore * @param {Object} [options] - Optional parameters, can be left null in most cases * @param {string} [options.name] - The new name for this item * @param {string} [options.parent_id] - The new parent folder for this item * @param {Function} [callback] - Called with item information if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the restored file object */ restoreFromTrash( fileID: string, options?: { name?: string; parent_id?: string; }, callback?: Function ) { // Set up the parent_id parameter if (options && options.parent_id) { (options as Record<string, any>).parent = { id: options.parent_id, }; delete options.parent_id; } var apiPath = urlPath(BASE_PATH, fileID), params = { body: options || {}, }; return this.client.wrapWithDefaultHandler(this.client.post)( apiPath, params, callback ); } /** * If there are previous versions of this file, this method can be used to retrieve information * about the older versions. * * API Endpoint: '/files/:fileID/versions' * Method: GET * * @param {string} fileID - The ID of the file to view version for * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed a list of previous file versions if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the collection of file versions */ getVersions( fileID: string, options?: Record<string, any>, callback?: Function ) { var apiPath = urlPath(BASE_PATH, fileID, VERSIONS_SUBRESOURCE), params = { qs: options, }; return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Used to retrieve the watermark for a corresponding Box file. * * API Endpoint: '/files/:fileID/watermark' * Method: GET * * @param {string} fileID - The Box ID of the file to get watermark for * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed the watermark information if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the watermark info */ getWatermark( fileID: string, options?: Record<string, any>, callback?: Function ) { var apiPath = urlPath(BASE_PATH, fileID, WATERMARK_SUBRESOURCE), params = { qs: options, }; return this.client .get(apiPath, params) .then((response: any /* FIXME */) => { if (response.statusCode !== 200) { throw errors.buildUnexpectedResponseError(response); } return response.body.watermark; }) .asCallback(callback); } /** * Used to apply or update the watermark for a corresponding Box file. * * API Endpoint: '/files/:fileID/watermark' * Method: PUT * * @param {string} fileID - The Box ID of the file to update watermark for * @param {Object} [options] - Optional parameters, can be left null * @param {Function} [callback] - Passed the watermark information if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the watermark info */ applyWatermark( fileID: string, options?: Record<string, any>, callback?: Function ) { var apiPath = urlPath(BASE_PATH, fileID, WATERMARK_SUBRESOURCE), params = { body: { watermark: { imprint: 'default', // Currently the API only supports default imprint }, }, }; Object.assign(params.body.watermark, options); return this.client.wrapWithDefaultHandler(this.client.put)( apiPath, params, callback ); } /** * Used to remove the watermark for a corresponding Box file. * * API Endpoint: '/files/:fileID/watermark' * Method: DELETE * * @param {string} fileID - The Box ID of the file to remove watermark from * @param {Function} [callback] - Empty response body passed if successful, error otherwise * @returns {Promise<void>} A promise resolving to nothing */ removeWatermark(fileID: string, callback: Function) { var apiPath = urlPath(BASE_PATH, fileID, WATERMARK_SUBRESOURCE); return this.client.wrapWithDefaultHandler(this.client.del)( apiPath, null, callback ); } /** * Discards a specific file version to the trash. Depending on the enterprise settings * for this user, the item will either be actually deleted from Box or moved to the trash. * * API Endpoint: '/files/:fileID/version/:versionID' * Method: DELETE * * @param {string} fileID - The file ID which old version will be moved to the trash or delete permanently * @param {string} versionID - The ID of the version to move to the trash or delete permanently * @param {Object} [options] Optional parameters * @param {string} [options.etag] Only delete the version of the file etag matches * @param {Function} [callback] - Empty response body, error otherwise * @returns {Promise<void>} A promise resolving to nothing */ deleteVersion( fileID: string, versionID: string, options?: | { [key: string]: any; etag?: string; } | Function, callback?: Function ) { // Switch around arguments if necessary for backwwards compatibility if (typeof options === 'function') { callback = options; options = {}; } var params = {}; if (options && options.etag) { (params as Record<string, any>).headers = { 'If-Match': options.etag, }; } var apiPath = urlPath(BASE_PATH, fileID, VERSIONS_SUBRESOURCE, versionID); return this.client.wrapWithDefaultHandler(this.client.del)( apiPath, params, callback ); } /** * Creates a session used to upload a new file in chunks.. This will first * verify that the file can be created and then open a session for uploading * pieces of the file. * * API Endpoint: '/files/upload_sessions' * Method: POST * * @param {string} folderID - The ID of the folder to upload the file to * @param {int} size - The size of the file that will be uploaded * @param {string} name - The name of the file to be created * @param {Function} [callback] - Passed the upload session info if successful * @returns {Promise<Object>} A promise resolving to the new upload session object */ createUploadSession( folderID: string, size: number, name: string, callback?: Function ) { var apiURL = this.client._uploadBaseURL + urlPath(BASE_PATH, UPLOAD_SESSION_SUBRESOURCE), params = { body: { folder_id: folderID, file_size: size, file_name: name, }, }; return this.client.wrapWithDefaultHandler(this.client.post)( apiURL, params, callback ); } /** * Creates a session used to upload a new version of a file in chunks. This * will first verify that the version can be created and then open a session for * uploading pieces of the file. * * API Endpoint: '/files/:fileID/upload_sessions' * Method: POST * * @param {string} fileID - The ID of the file to upload a new version of * @param {int} size - The size of the file that will be uploaded * @param {Function} [callback] - Passed the upload session info if successful * @returns {Promise<Object>} A promise resolving to the new upload session object */ createNewVersionUploadSession( fileID: string, size: number, callback?: Function ) { var apiURL = this.client._uploadBaseURL + urlPath(BASE_PATH, fileID, UPLOAD_SESSION_SUBRESOURCE), params = { body: { file_size: size, }, }; return this.client.wrapWithDefaultHandler(this.client.post)( apiURL, params, callback ); } /** * Uploads a chunk of a file to an open upload session * * API Endpoint: '/files/upload_sessions/:sessionID' * Method: PUT * * @param {string} sessionID - The ID of the upload session to upload to * @param {Buffer|string} part - The chunk of the file to upload * @param {int} offset - The byte position where the chunk begins in the file * @param {int} totalSize - The total size of the file being uploaded * @param {Function} [callback] - Passed the part definition if successful * @returns {Promise<Object>} A promise resolving to the part object */ uploadPart( sessionID: string, part: Buffer | string, offset: number, totalSize: number, callback?: Function ) { var apiURL = this.client._uploadBaseURL + urlPath(BASE_PATH, UPLOAD_SESSION_SUBRESOURCE, sessionID); var hash = crypto.createHash('sha1').update(part).digest('base64'); var params = { headers: { 'Content-Type': 'application/octet-stream', Digest: `SHA=${hash}`, 'Content-Range': `bytes ${offset}-${ offset + part.length - 1 }/${totalSize}`, }, json: false, body: part, }; return this.client .put(apiURL, params) .then((response: any /* FIXME */) => { if (response.statusCode !== 200) { throw errors.buildUnexpectedResponseError(response); } return JSON.parse(response.body); }) .asCallback(callback); } /** * Commit an upload session after all parts have been uploaded, creating the new file * * API Endpoint: '/files/upload_sessions/:sessionID/commit' * Method: POST * * @param {string} sessionID - The ID of the upload session to commit * @param {string} fileHash - The base64-encoded SHA-1 hash of the file being uploaded * @param {Object} [options] - Optional parameters set on the created file, can be left null * @param {UploadPart[]} [options.parts] The list of uploaded parts to be committed, will be fetched from the API otherwise * @param {Function} [callback] - Passed the new file information if successful * @returns {Promise<Object>} A promise resolving to the uploaded file object */ commitUploadSession( sessionID: string, fileHash: string, options?: { parts?: UploadPart[]; }, callback?: Function ) { options = options || {}; var userParts; if (options.parts) { userParts = options.parts; delete options.parts; } var apiURL = this.client._uploadBaseURL + urlPath(BASE_PATH, UPLOAD_SESSION_SUBRESOURCE, sessionID, 'commit'), params = { headers: { Digest: `SHA=${fileHash}`, }, body: { attributes: options, } as Record<string, any>, }; var fetchParts = ( offset: any /* FIXME */, fetchedParts: any /* FIXME */ ) => { let pagingOptions = { limit: 1000, offset, }; return this.getUploadSessionParts(sessionID, pagingOptions).then(( data: any /* FIXME */ ) => { fetchedParts = fetchedParts.concat(data.entries); if (data.offset + data.entries.length >= data.total_count) { return Promise.resolve(fetchedParts); } return fetchParts(offset + data.limit, fetchedParts); }); }; return (userParts ? Promise.resolve(userParts) : fetchParts(0, [])) .then((parts: any[] /* FIXME */) => { // Commit the upload with the list of parts params.body.parts = parts; return this.client.post(apiURL, params); }) .then((response: any /* FIXME */) => { if (response.statusCode === 201) { return response.body; } if (response.statusCode === 202) { var retryInterval = response.headers['retry-after'] || 1; return Promise.delay(retryInterval * 1000).then(() => { // Ensure we don't have to fetch parts from the API again on retry options = Object.assign({}, options, { parts: params.body.parts }); return this.commitUploadSession(sessionID, fileHash, options); }); } throw errors.buildUnexpectedResponseError(response); }) .asCallback(callback); } /** * Abort an upload session, discarding any chunks that were uploaded to it * * API Endpoint: '/files/upload_sessions/:sessionID' * Method: DELETE * * @param {string} sessionID - The ID of the upload session to commit * @param {Function} [callback] - Passed nothing if successful, error otherwise * @returns {Promise<void>} A promise resolving to nothing */ abortUploadSession(sessionID: string, callback?: Function) { var apiURL = this.client._uploadBaseURL + urlPath(BASE_PATH, UPLOAD_SESSION_SUBRESOURCE, sessionID); return this.client.wrapWithDefaultHandler(this.client.del)( apiURL, null, callback ); } /** * Get a list of all parts that have been uploaded to an upload session * * API Endpoint: '/files/upload_sessions/:sessionID/parts' * Method: GET * * @param {string} sessionID - The ID of the session to get a list of parts from * @param {Object} [options] - Optional parameters, can be left null * @param {string} [options.offset] - Paging offset for the list of parts * @param {int} [options.limit] - Maximum number of parts to return * @param {Function} [callback] - Passed the list of parts if successful * @returns {Promise<Object>} A promise resolving to the collection of uploaded parts */ getUploadSessionParts( sessionID: string, options?: { offset?: string; limit?: number; }, callback?: Function ) { var apiURL = this.client._uploadBaseURL + urlPath(BASE_PATH, UPLOAD_SESSION_SUBRESOURCE, sessionID, 'parts'), params = { qs: options, }; return this.client.wrapWithDefaultHandler(this.client.get)( apiURL, params, callback ); } /** * Get the status of an upload session, e.g. whether or not is has started or * finished committing * * API Endpoint: '/files/upload_sessions/:sessionID' * Method: GET * * @param {string} sessionID - The ID of the upload session to get the status of * @param {Function} [callback] - Passed the session status if successful * @returns {Promise<Object>} A promise resolving to the upload session object */ getUploadSession(sessionID: string, callback?: Function) { var apiURL = this.client._uploadBaseURL + urlPath(BASE_PATH, UPLOAD_SESSION_SUBRESOURCE, sessionID); return this.client.wrapWithDefaultHandler(this.client.get)( apiURL, null, callback ); } /** * Upload a file in chunks, which is generally faster and more reliable for * large files. * * API Endpoint: '/files/upload_sessions' * Method: POST * * @param {string} folderID - The ID of the folder to upload the file to * @param {int} size - The size of the file that will be uploaded * @param {string} name - The name of the file to be created * @param {Buffer|string|Readable} file - The file to upload * @param {Object} [options] - Optional parameters for the upload * @param {int} [options.parallelism] The number of chunks to upload concurrently * @param {int} [options.retryInterval] The amount of time to wait before retrying a failed chunk upload, in ms * @param {Object} [options.fileAttributes] Attributes to set on the newly-uploaded file * @param {Function} [callback] - Passed the uploader if successful * @returns {Promise<ChunkedUploader>} A promise resolving to the chunked uploader */ getChunkedUploader( folderID: string, size: number, name: string, file: Buffer | string | Readable, options?: { parallelism?: number; retryInterval?: number; fileAttributes?: Record<string, any>; }, callback?: Function ) { if (file instanceof Readable) { // Need to pause the stream immediately to prevent certain libraries, // e.g. request from placing the stream into flowing mode and consuming bytes file.pause(); } return this.createUploadSession(folderID, size, name) .then( (sessionInfo: any /* FIXME */) => new ChunkedUploader(this.client, sessionInfo, file, size, options) ) .asCallback(callback); } /** * Upload a new file version in chunks, which is generally faster and more * reliable for large files. * * API Endpoint: '/files/:fileID/upload_sessions' * Method: POST * * @param {string} fileID - The ID of the file to upload a new version of * @param {int} size - The size of the file that will be uploaded * @param {Buffer|string|Readable} file - The file to upload * @param {Object} [options] - Optional parameters for the upload * @param {int} [options.parallelism] The number of chunks to upload concurrently * @param {int} [options.retryInterval] The amount of time to wait before retrying a failed chunk upload, in ms * @param {Object} [options.fileAttributes] Attributes to set on the updated file object * @param {Function} [callback] - Passed the uploader if successful * @returns {Promise<ChunkedUploader>} A promise resolving to the chunked uploader */ getNewVersionChunkedUploader( fileID: string, size: number, file: Buffer | string | Readable, options?: { parallelism?: number; retryInterval?: number; fileAttributes?: Record<string, any>; }, callback?: Function ) { if (file instanceof Readable) { // Need to pause the stream immediately to prevent certain libraries, // e.g. request from placing the stream into flowing mode and consuming bytes file.pause(); } return this.createNewVersionUploadSession(fileID, size) .then( (sessionInfo: any /* FIXME */) => new ChunkedUploader(this.client, sessionInfo, file, size, options) ) .asCallback(callback); } /** * Requests collaborations on a given file. * * API Endpoint: '/files/:fileID/collaborations' * Method: GET * * @param {string} fileID - Box ID of the file being requested * @param {Object} [options] - Additional options. Can be left null in most cases. * @param {int} [options.limit] - The maximum number of collaborations to return * @param {int} [options.offset] - Paging parameter for the collaborations collection * @param {string} [options.fields] - Comma-separated list of fields to return on the collaboration objects * @param {Function} [callback] - Passed the collaborations if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the collection of collaborations on the file */ getCollaborations( fileID: string, options?: { limit?: number; offset?: number; fields?: string; }, callback?: Function ) { var params = { qs: options, }; var apiPath = urlPath(BASE_PATH, fileID, '/collaborations'); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Requests information for all representation objects generated for a specific Box file * * API Endpoint: '/files/:fileID?fields=representations' * Method : GET * * @param {string} fileID - Box ID of the file being requested * @param {client.files.representation} representationType - The x-rep-hints value the application should create a * representation for. This value can either come from FileRepresentationType enum or manually created * @param {Object} [options] - Additional options. Can be left empty * @param {boolean} [options.generateRepresentations = false] - Set to true to return representation info where all states resolve to success. * @param {Function} [callback] - Passed an array of representaton objects if successful * @returns {Promise<Object>} A promise resolving to the representation response objects */ getRepresentationInfo( fileID: string, representationType: FileRepresentationType, options?: | { generateRepresentations?: boolean; } | Function, callback?: Function ) { if (typeof options === 'function') { callback = options; options = {}; } if (!representationType && options && options.generateRepresentations) { throw new Error( 'Must provide a valid X-Rep-Hints string to get representations with a success status' ); } var params = { qs: { fields: 'representations', }, headers: { 'x-rep-hints': representationType, }, }; var apiPath = urlPath(BASE_PATH, fileID); return this.client .get(apiPath, params) .then((response: any /* FIXME */) => { switch (response.statusCode) { // 202 - A Box file representation will be generated, but is not ready yet case httpStatusCodes.ACCEPTED: throw errors.buildResponseError( response, 'Representation not ready at this time' ); // 200 - A Boxfile representation generated successfully // return the representation object case httpStatusCodes.OK: if (options && (options as any).generateRepresentations) { var data = response.body.representations.entries; var promiseArray = data.map((entry: any /* FIXME */) => { switch (entry.status.state) { case 'success': case 'viewable': case 'error': return Promise.resolve(entry); default: return pollRepresentationInfo(this.client, entry.info.url); } }); return Promise.all(promiseArray).then((entries) => ({ entries })); } return response.body.representations; // Unexpected Response default: throw errors.buildUnexpectedResponseError(response); } }) .asCallback(callback); } /** * Get the contents of a representation of a file, e.g, the binary content of an image or pdf. * * API Endpoint: '/files/:fileID?fields=representations' * Method : GET * * @param {string} fileID The file ID to get the representation of * @param {string} representationType The X-Rep-Hints type to request * @param {Object} [options] Optional parameters * @param {string} [options.assetPath] Asset path for representations with multiple files * @param {Function} [callback] Passed a stream over the representation contents if successful * @returns {Promise<Readable>} A promise resolving to a stream over the representation contents */ getRepresentationContent( fileID: string, representationType: FileRepresentationType, options?: { assetPath?: string; }, callback?: Function ) { if (!representationType) { throw new Error('Must provide a valid X-Rep-Hints string'); } options = Object.assign({ assetPath: '' }, options); return this.getRepresentationInfo(fileID, representationType) .then((reps: any /* FIXME */) => { var repInfo = reps.entries.pop(); if (!repInfo) { throw new Error( 'Could not get information for requested representation' ); } switch (repInfo.status.state) { case 'success': case 'viewable': return repInfo.content.url_template; case 'error': throw new Error('Representation had error status'); case 'none': case 'pending': return pollRepresentationInfo(this.client, repInfo.info.url).then(( info: any /* FIXME */ ) => { if (info.status.state === 'error') { throw new Error('Representation had error status'); } return info.content.url_template; }); default: throw new Error( `Unknown representation status: ${repInfo.status.state}` ); } }) .then((assetURLTemplate: string) => { var url = urlTemplate .parse(assetURLTemplate) .expand({ asset_path: options!.assetPath }); return this.client.get(url, { streaming: true }); }) .asCallback(callback); } /** * Creates a zip of multiple files and folders. * * API Endpoint: '/zip_downloads' * Method: POST * * @param {name} name - The name of the zip file to be created * @param {Array} items - Array of files or folders to be part of the created zip * @param {Function} [callback] Passed a zip information object * @returns {Promise<string>} A promise resolving to a zip information object */ createZip(name: string, items: any[] /* FIXME */, callback?: Function) { var params = { body: { download_file_name: name, items, }, }; return this.client.wrapWithDefaultHandler(this.client.post)( ZIP_DOWNLOAD_PATH, params, callback ); } /** * Creates a zip of multiple files and folders and downloads it. * * API Endpoint: '/zip_downloads' * Method: GET * * @param {name} name - The name of the zip file to be created * @param {Array} items - Array of files or folders to be part of the created zip * @param {Stream} stream - Stream to pipe the readable stream of the zip file * @param {Function} [callback] - Passed a zip download status object * @returns {Promise<Readable>} A promise resolving to a zip download status object */ downloadZip( name: string, items: any[] /* FIXME */, stream: Writable, callback?: Function ) { var downloadStreamOptions = { streaming: true, headers: {}, }; var params = { body: { download_file_name: name, items, }, }; return this.client .post(ZIP_DOWNLOAD_PATH, params) .then((response: any /* FIXME */) => this.client .get(response.body.download_url, downloadStreamOptions) .then((responseStream: Readable) => { responseStream.pipe(stream); // eslint-disable-next-line promise/avoid-new return new Promise((resolve, reject) => { responseStream.on('end', () => resolve('Done downloading')); responseStream.on('error', (error) => reject(error)); }).then(() => this.client .get(response.body.status_url) .then((responseStatus: any /* FIXME */) => responseStatus.body) ); }) ) .asCallback(callback); } } /** * Enum of valid x-rep- hint values for generating representation info * * @readonly * @enum {FileRepresentationType} */ Files.prototype.representation = FileRepresentationType; /** * @module box-node-sdk/lib/managers/files * @see {@Link Files} */ export = Files;
the_stack
import { Module, GetterTree, MutationTree, ActionTree } from 'vuex'; import md5 from 'md5'; import axios from 'axios'; import { RootState } from '@/types/store/RootState'; import { C3State, C3Relay, C3Interface, C3Gateway, GatewayHeader, NodeKlass, C3Node, C3Edge, FetchData, C3Command, C3Route, C3RelayTime } from '@/types/c3types'; const namespaced: boolean = true; // State export const state: C3State = { gateways: [], gateway: null, nodes: [], edges: [], relayTimestamps: [], mustRefresh: false, lastGetHash: '' }; // Getters export type GetGatewayFn = () => C3Node | undefined; export type GetRelayFn = (id: string) => C3Node | undefined; export type GetInterfaceFn = (uid: string) => C3Node | undefined; export type GetInterfacesFn = (nodeKlass?: NodeKlass[]) => C3Node[]; export type GetInterfacesForFn = ( nodeKlass: NodeKlass | NodeKlass[], parentId: string | null ) => C3Node[]; export type GetNodeKlassFn = (uid: string) => NodeKlass; export type GetCommandFn = (id: string) => C3Command | undefined; export type GetRelayRoutesFn = (id: string) => C3Route[]; export const getters: GetterTree<C3State, RootState> = { getNodes(c3State): C3Node[] { return c3State.nodes; }, getEdges(c3State): C3Edge[] { return c3State.edges; }, // return gateways agentIds getGateways(c3State): GatewayHeader[] { return c3State.gateways; }, // return the selected gateway getGateway(c3State): C3Node | undefined { return c3State.nodes.find(node => { return node.klass === NodeKlass.Gateway; }); }, hasGatewaySelected(c3State): boolean { if (c3State.gateway) { return true; } return false; }, // return all relays from the selected gateway getRelays(c3State): C3Node[] { return c3State.nodes.filter(node => { return node.klass === NodeKlass.Relay; }); }, getRelay: c3State => (id: string): C3Node | undefined => { return c3State.nodes.find(node => { return node.id === id && node.klass === NodeKlass.Relay; }); }, getGatewayRoutes(c3State): C3Route[] { if (c3State.gateway) { return c3State.gateway.routes; } return []; }, getRelayRoutes: c3State => (id: string): C3Route[] => { if (!!c3State.gateway) { const relay = c3State.gateway.relays.find(target => { return target.agentId === id; }); if (!!relay) { return relay.routes; } } return []; }, getInterface: c3State => (uid: string): C3Node | undefined => { if (uid === 'new') { return { uid: 'new', klass: NodeKlass.Relay, id: 'new', buildId: '', name: 'new', pending: true, isActive: false, type: -1, error: null, parentId: null, parentKlass: NodeKlass.Gateway, initialCommand: {}, timestamp: Math.floor(Date.now() / 1000) }; } const c = c3State.nodes.find(node => { return node.uid === uid; }); return c3State.nodes.find(node => { return node.uid === uid; }); }, getInterfaces: c3State => ( nodeKlass: NodeKlass[] = [ NodeKlass.Channel, NodeKlass.Connector, NodeKlass.Peripheral ] ): C3Node[] => { return c3State.nodes.filter(node => { return nodeKlass.includes(node.klass); }); }, getInterfacesFor: c3State => ( nodeKlass: NodeKlass | NodeKlass[] = [ NodeKlass.Channel, NodeKlass.Connector, NodeKlass.Peripheral ], parentId: string | null ): C3Node[] => { if ((parentId === '' || parentId === null) && c3State.gateway) { parentId = c3State.gateway.agentId; } return c3State.nodes.filter(node => { return nodeKlass.includes(node.klass) && node.parentId === parentId; }); }, getNodeKlass: c3State => (uid: string): NodeKlass => { const n = c3State.nodes.find(node => { return node.uid === uid; }); if (n) { return n.klass; } return NodeKlass.Undefined; } }; // Mutations export type UpdateGatewaysFn = (relays: GatewayHeader[]) => void; export type UpdateGatewayFn = (relays: C3Gateway) => void; export const mutations: MutationTree<C3State> = { updateGateways(c3State, g: GatewayHeader[]) { c3State.gateways = g; }, updateGateway(c3State, g: C3Gateway) { c3State.gateway = g; }, populateNodes(c3State, data: C3Gateway) { const uuid = (...args: string[]): string => { return args.join('-'); }; const isRelayActive = (relay: C3Relay): boolean => { let active = relay.isActive; // If gateway down the relays are not managable either. if (data.isActive === false) { active = false; } return active; }; c3State.nodes = []; c3State.mustRefresh = false; if (c3State.relayTimestamps === undefined) { c3State.relayTimestamps = []; } let gatewayTimestamp = 0; let relayTimestamp = 0; const relayTimestamps: C3RelayTime[] = []; if (!!data.timestamp) { gatewayTimestamp = data.timestamp; } c3State.nodes.push({ uid: data.agentId, klass: NodeKlass.Gateway, id: data.agentId, buildId: data.buildId, name: data.name, pending: data.pending || false, isActive: data.isActive, type: -1, error: data.error || null, parentId: null, parentKlass: null, timestamp: gatewayTimestamp }); data.channels.forEach((i: C3Interface) => { c3State.nodes.push({ uid: uuid(i.iid, data.agentId), klass: NodeKlass.Channel, id: i.iid, pending: i.pending || false, type: i.type, error: i.error || null, parentId: data.agentId, isReturnChannel: i.isReturnChannel || false, isNegotiationChannel: i.isNegotiationChannel || false, parentKlass: NodeKlass.Gateway, propertiesText: i.propertiesText || '' }); }); data.peripherals.forEach((i: C3Interface) => { c3State.nodes.push({ uid: uuid(i.iid, data.agentId), klass: NodeKlass.Peripheral, id: i.iid, pending: i.pending || false, type: i.type, error: i.error || null, parentId: data.agentId, parentKlass: NodeKlass.Gateway, propertiesText: i.propertiesText || '' }); }); data.connectors.forEach((i: C3Interface) => { c3State.nodes.push({ uid: uuid(i.iid, data.agentId), klass: NodeKlass.Connector, id: i.iid, pending: i.pending || false, type: i.type, error: i.error || null, parentId: data.agentId, parentKlass: NodeKlass.Gateway, propertiesText: i.propertiesText || '' }); }); data.relays.forEach((relay: C3Relay) => { if (!!relay.timestamp) { relayTimestamp = relay.timestamp; if (relayTimestamp < gatewayTimestamp) { relayTimestamps!.push({ id: relay.agentId, time: relayTimestamp }); } else { const newTime = c3State.relayTimestamps!.find(t => { return t.id === relay.agentId; }); if (newTime !== undefined) { c3State.mustRefresh = true; } } } c3State.nodes.push({ uid: relay.agentId, klass: NodeKlass.Relay, id: relay.agentId, buildId: relay.buildId, name: relay.name, pending: relay.pending || false, isActive: isRelayActive(relay), type: -1, error: relay.error || null, parentId: data.agentId, parentKlass: NodeKlass.Gateway, initialCommand: relay.initialCommand || {}, timestamp: relayTimestamp, hostInfo: relay.hostInfo }); relay.channels.forEach((i: C3Interface) => { c3State.nodes.push({ uid: uuid(i.iid, relay.agentId), klass: NodeKlass.Channel, id: i.iid, pending: i.pending || false, type: i.type, error: i.error || null, parentId: relay.agentId, isReturnChannel: i.isReturnChannel || false, isNegotiationChannel: i.isNegotiationChannel || false, parentKlass: NodeKlass.Relay, propertiesText: i.propertiesText || '' }); }); relay.peripherals.forEach((i: C3Interface) => { c3State.nodes.push({ uid: uuid(i.iid, relay.agentId), klass: NodeKlass.Peripheral, id: i.iid, pending: i.pending || false, type: i.type, error: i.error || null, parentId: relay.agentId, parentKlass: NodeKlass.Relay, propertiesText: i.propertiesText || '' }); }); }); c3State.relayTimestamps = relayTimestamps; }, populateEdges(c3State, data: C3Gateway) { const uuid = (...args: string[]): string => { return args.join('-'); }; const guid = () => { return Math.random() .toString(36) .substring(2); }; const interfaceIsExist = (agentId: string, iid: string) => { const relay = data.relays.find((r: C3Relay) => { return r.agentId === agentId; }); if (relay !== undefined) { const c = relay.channels.find((i: C3Interface) => { return i.iid === iid; }); if (c !== undefined) { return true; } } return false; }; c3State.edges = []; data.channels.forEach((i: C3Interface) => { c3State.edges.push({ id: guid(), klass: NodeKlass.Interface, isNegotiationChannel: !!i.isNegotiationChannel, length: 0, dashes: false, from: data.agentId, to: uuid(i.iid, data.agentId) }); }); data.peripherals.forEach((i: C3Interface) => { c3State.edges.push({ id: guid(), klass: NodeKlass.Interface, length: 0, dashes: false, from: data.agentId, to: uuid(i.iid, data.agentId) }); }); data.connectors.forEach((i: C3Interface) => { c3State.edges.push({ id: guid(), klass: NodeKlass.Interface, length: 0, dashes: true, from: data.agentId, to: uuid(i.iid, data.agentId) }); }); data.routes.forEach(route => { if (route.isNeighbour === true) { c3State.edges.push({ id: guid(), klass: NodeKlass.Relay, length: 100, dashes: false, from: data.agentId, to: route.destinationAgent }); c3State.edges.push({ id: guid(), klass: NodeKlass.Interface, length: 0, dashes: false, from: uuid(route.outgoingInterface, data.agentId), to: uuid(route.receivingInterface, route.destinationAgent) }); } }); data.relays.forEach((relay: C3Relay) => { relay.channels.forEach((i: C3Interface) => { c3State.edges.push({ id: guid(), klass: NodeKlass.Interface, isNegotiationChannel: !!i.isNegotiationChannel, length: 0, dashes: false, from: relay.agentId, to: uuid(i.iid, relay.agentId) }); }); relay.peripherals.forEach((i: C3Interface) => { c3State.edges.push({ id: guid(), klass: NodeKlass.Interface, length: 0, dashes: false, from: relay.agentId, to: uuid(i.iid, relay.agentId) }); }); relay.routes.forEach(route => { if (route.isNeighbour === true) { let isDashed = true; if ( interfaceIsExist( route.destinationAgent, route.receivingInterface ) && interfaceIsExist(relay.agentId, route.outgoingInterface) ) { isDashed = false; } c3State.edges.push({ id: guid(), klass: NodeKlass.Relay, length: 100, dashes: isDashed, from: relay.agentId, to: route.destinationAgent }); c3State.edges.push({ id: guid(), klass: NodeKlass.Interface, length: 0, dashes: false, from: uuid(route.outgoingInterface, relay.agentId), to: uuid(route.receivingInterface, route.destinationAgent) }); } }); }); } }; // Actions export type FetchC3DataFn = (data: FetchData) => void; const actions: ActionTree<C3State, RootState> = { fetchCapability(context, nodeIds: FetchData) { context.dispatch('c3Capability/fetchCapability', nodeIds, { root: true }); }, fetchGateways(context): void { const baseURL = `${context.rootGetters['optionsModule/getAPIUrl']}:${context.rootGetters['optionsModule/getAPIPort']}`; axios .get('/api/gateway', { baseURL }) .then(response => { context.commit('updateGateways', response.data); }) .catch(error => { context.dispatch( 'notifyModule/insertNotify', { type: 'error', message: error.message }, { root: true } ); // tslint:disable-next-line:no-console console.error(error.message); }); }, fetchGateway(context, nodeIds: FetchData) { if (nodeIds.gatewayId) { const url = `/api/gateway/${nodeIds.gatewayId}`; const baseURL = `${context.rootGetters['optionsModule/getAPIUrl']}:${context.rootGetters['optionsModule/getAPIPort']}`; axios .get(url, { baseURL }) .then(response => { let hash: string = ''; if (context.state.mustRefresh !== true) { hash = md5( JSON.stringify(response.data).replace( /"timestamp":[0-9]*[,]{0,1}/g, '' ) ); } // store the gateway context.commit('updateGateway', response.data); context.commit('populateNodes', response.data); context.commit('populateEdges', response.data); if (context.state.mustRefresh || hash !== context.state.lastGetHash) { // generate the data structure to vis library context.dispatch('visModule/generateNodes', {}, { root: true }); context.dispatch('visModule/generateEdges', {}, { root: true }); context.commit('visModule/setGraphData', {}, { root: true }); context.state.lastGetHash = hash; } }) .catch(error => { context.dispatch( 'notifyModule/insertNotify', { type: 'error', message: error.message }, { root: true } ); // tslint:disable-next-line:no-console console.error(error.message); }); } else { context.dispatch( 'notifyModule/insertNotify', { type: 'error', message: 'missing: gatewayId' }, { root: true } ); // tslint:disable-next-line:no-console console.error('missing: gatewayId'); } } }; export const c3Module: Module<C3State, RootState> = { namespaced, state, getters, mutations, actions };
the_stack
import { PetColor, PetSize, PetSpeed, PetType } from "../common/types"; import { ISequenceTree } from "./sequences"; import { IState, States, resolveState, HorizontalDirection, ChaseState, BallState, FrameResult, PetInstanceState, isStateAboveGround } from "./states"; import { CAT_NAMES, DOG_NAMES, CRAB_NAMES, SNAKE_NAMES, CLIPPY_NAMES, TOTORO_NAMES, DUCK_NAMES, ZAPPY_NAMES, ROCKY_NAMES } from "../common/names"; export class InvalidStateException { } export class PetElement { el: HTMLImageElement; collision: HTMLDivElement; pet: IPetType; color: PetColor; type: PetType; constructor(el: HTMLImageElement, collision: HTMLDivElement, pet: IPetType, color: PetColor, type: PetType){ this.el = el; this.collision = collision; this.pet = pet; this.color = color; this.type = type; } } export interface IPetCollection { pets(): Array<PetElement>; push(pet: PetElement): void; reset(): void; seekNewFriends(): string[]; locate(name: string): PetElement | undefined; } export class PetCollection implements IPetCollection { _pets: Array<PetElement>; constructor(){ this._pets = new Array(0); } pets() { return this._pets; } push(pet: PetElement){ this._pets.push(pet); } reset(){ this._pets = []; } locate(name: string): PetElement | undefined { return this._pets.find((collection, value, obj) => { return collection.pet.name() === name; }); } seekNewFriends() : string[] { if (this._pets.length <= 1) {return [];} // You can't be friends with yourself. var messages = new Array<string>(0); this._pets.forEach(petInCollection => { if (petInCollection.pet.hasFriend()) {return;} // I already have a friend! this._pets.forEach(potentialFriend => { if (potentialFriend.pet.hasFriend()) {return;} // Already has a friend. sorry. if (!potentialFriend.pet.canChase()) {return;} // Pet is busy doing something else. if (potentialFriend.pet.left() > petInCollection.pet.left() && potentialFriend.pet.left() < petInCollection.pet.left() + petInCollection.pet.width()) { // We found a possible new friend.. console.log(petInCollection.pet.name(), " wants to be friends with ", potentialFriend.pet.name(), "."); if (petInCollection.pet.makeFriendsWith(potentialFriend.pet)) { messages.push(`${petInCollection.pet.name()} (${petInCollection.pet.emoji()}): I'm now friends ❤️ with ${potentialFriend.pet.name()} (${potentialFriend.pet.emoji()})`); } } }); }); return messages; } } export interface IPetType { nextFrame(): void // Special methods for actions canSwipe(): boolean canChase(): boolean swipe(): void chase(ballState: BallState, canvas: HTMLCanvasElement): void speed(): number isMoving(): boolean // State API getState(): PetInstanceState recoverState(state: PetInstanceState): void recoverFriend(friend: IPetType): void // Positioning bottom(): number; left(): number; positionBottom(bottom: number): void; positionLeft(left: number): void; width(): number; floor(): number; // Friends API name(): string; emoji(): string; hasFriend(): boolean; friend(): IPetType; makeFriendsWith(friend: IPetType): boolean; isPlaying(): boolean; } function calculateSpriteWidth(size: PetSize): number{ if (size === PetSize.nano){ return 30; } else if (size === PetSize.medium){ return 55; } else if (size === PetSize.large){ return 110; } else { return 30; // Shrug } } abstract class BasePetType implements IPetType { label: string = "base"; static count: number = 0; sequence: ISequenceTree = { startingState: States.sitIdle, sequenceStates: []}; currentState: IState; currentStateEnum: States; holdState: IState | undefined; holdStateEnum: States | undefined; private el: HTMLImageElement; private collision: HTMLDivElement; private _left: number; private _bottom: number; petRoot: string; _floor: number; _friend: IPetType | undefined; private _name: string; private _speed: number; constructor(spriteElement: HTMLImageElement, collisionElement: HTMLDivElement, size: PetSize, left: number, bottom: number, petRoot: string, floor: number, name: string, speed: number){ this.el = spriteElement; this.collision = collisionElement; this.petRoot = petRoot; this._floor = floor; this._left = left; this._bottom = bottom; this.initSprite(size, left, bottom); this.currentStateEnum = this.sequence.startingState; this.currentState = resolveState(this.currentStateEnum, this); this._name = name; this._speed = speed; // Increment the static count of the Pet class that the constructor belongs to (this.constructor as any).count += 1; } initSprite(petSize: PetSize, left: number, bottom: number) { this.el.style.left = `${left}px`; this.el.style.bottom = `${bottom}px`; this.el.style.width = "auto"; this.el.style.height = "auto"; this.el.style.maxWidth = `${calculateSpriteWidth(petSize)}px`; this.el.style.maxHeight = `${calculateSpriteWidth(petSize)}px`; this.collision.style.left = `${left}px`; this.collision.style.bottom = `${bottom}px`; this.collision.style.width = `${calculateSpriteWidth(petSize)}px`; this.collision.style.height = `${calculateSpriteWidth(petSize)}px`; } left(): number { return this._left; } bottom(): number { return this._bottom; } positionBottom(bottom: number): void { this._bottom = bottom; this.el.style.bottom = `${this._bottom}px`; this.el.style.bottom = `${this._bottom}px`; this.collision.style.left = `${this._left}px`; this.collision.style.bottom = `${this._bottom}px`; }; positionLeft(left: number): void { this._left = left; this.el.style.left = `${this._left}px`; this.el.style.left = `${this._left}px`; this.collision.style.left = `${this._left}px`; this.collision.style.bottom = `${this._bottom}px`; } width(): number { return this.el.width; } floor(): number { return this._floor; } getState(): PetInstanceState { return {currentStateEnum: this.currentStateEnum}; } speed(): number { return this._speed; } isMoving(): boolean { return this._speed !== PetSpeed.still; } recoverFriend(friend: IPetType){ // Recover friends.. this._friend = friend; } recoverState(state: PetInstanceState){ // TODO : Resolve a bug where if it was swiping before, it would fail // because holdState is no longer valid. this.currentStateEnum = state.currentStateEnum!; this.currentState = resolveState(this.currentStateEnum, this); if (!isStateAboveGround(this.currentStateEnum)){ // Reset the bottom of the sprite to the floor as the theme // has likely changed. this.positionBottom(this.floor()); } } canSwipe(){ return !isStateAboveGround(this.currentStateEnum); } canChase(){ return !isStateAboveGround(this.currentStateEnum) && this.currentStateEnum !== States.chase && this.isMoving(); } swipe() { if (this.currentStateEnum === States.swipe) { return; } this.holdState = this.currentState; this.holdStateEnum = this.currentStateEnum; this.currentStateEnum = States.swipe; this.currentState = resolveState(this.currentStateEnum, this); } chase(ballState: BallState, canvas: HTMLCanvasElement) { this.currentStateEnum = States.chase; this.currentState = new ChaseState(this, ballState, canvas); } faceLeft() { this.el.style.transform = "scaleX(-1)"; } faceRight() { this.el.style.transform = "scaleX(1)"; } setAnimation(face: string) { if (this.el.src.endsWith(`_${face}_8fps.gif`)) { return; } this.el.src = `${this.petRoot}_${face}_8fps.gif`; } chooseNextState(fromState: States): States { // Work out next state var possibleNextStates: States[] | undefined = undefined; for (var i = 0 ; i < this.sequence.sequenceStates.length; i++) { if (this.sequence.sequenceStates[i].state === fromState) { possibleNextStates = this.sequence.sequenceStates[i].possibleNextStates; } } if (!possibleNextStates){ throw new InvalidStateException(); } // randomly choose the next state const idx = Math.floor(Math.random() * possibleNextStates.length); return possibleNextStates[idx]; } nextFrame() { if (this.currentState.horizontalDirection === HorizontalDirection.left) { this.faceLeft(); } else if (this.currentState.horizontalDirection === HorizontalDirection.right) { this.faceRight(); } this.setAnimation(this.currentState.spriteLabel); // What's my buddy doing? if (this.hasFriend() && this.currentStateEnum !== States.chaseFriend && this.isMoving()) { if (this.friend().isPlaying() && !isStateAboveGround(this.currentStateEnum)) { this.currentState = resolveState(States.chaseFriend, this); this.currentStateEnum = States.chaseFriend; return; } } var frameResult = this.currentState.nextFrame(); if (frameResult === FrameResult.stateComplete) { // If recovering from swipe.. if (this.holdState && this.holdStateEnum){ this.currentState = this.holdState; this.currentStateEnum = this.holdStateEnum; this.holdState = undefined; this.holdStateEnum = undefined; return; } var nextState = this.chooseNextState(this.currentStateEnum); this.currentState = resolveState(nextState, this); this.currentStateEnum = nextState; } else if (frameResult === FrameResult.stateCancel){ if (this.currentStateEnum === States.chase) { var nextState = this.chooseNextState(States.idleWithBall); this.currentState = resolveState(nextState, this); this.currentStateEnum = nextState; } else if (this.currentStateEnum === States.chaseFriend) { var nextState = this.chooseNextState(States.idleWithBall); this.currentState = resolveState(nextState, this); this.currentStateEnum = nextState; } } } hasFriend() : boolean { return this._friend !== undefined; } friend() : IPetType { return this._friend!; } name(): string { return this._name; } makeFriendsWith(friend: IPetType): boolean { this._friend = friend; console.log(this.name(), ": I'm now friends ❤️ with ", friend.name()); return true; } isPlaying(): boolean { return this.isMoving() && (this.currentStateEnum === States.runRight || this.currentStateEnum === States.runLeft); } emoji(): string { return "🐶"; } } export class Totoro extends BasePetType { label = "totoro"; sequence = { startingState: States.sitIdle, sequenceStates: [ { state: States.sitIdle, possibleNextStates: [States.walkRight, States.lie] }, { state: States.lie, possibleNextStates: [States.walkRight, States.walkLeft] }, { state: States.walkRight, possibleNextStates: [States.walkLeft, States.sitIdle] }, { state: States.walkLeft, possibleNextStates: [States.sitIdle, States.climbWallLeft, States.sitIdle] }, { state: States.climbWallLeft, possibleNextStates: [States.wallHangLeft] }, { state: States.wallHangLeft, possibleNextStates: [States.jumpDownLeft] }, { state: States.jumpDownLeft, possibleNextStates: [States.land] }, { state: States.land, possibleNextStates: [States.sitIdle, States.walkRight, States.lie] }, { state: States.chase, possibleNextStates: [States.idleWithBall] }, { state: States.idleWithBall, possibleNextStates: [States.walkRight, States.walkLeft] }, ] }; emoji(): string { return "🐾"; } } export class Cat extends BasePetType { label = "cat"; sequence = { startingState: States.sitIdle, sequenceStates: [ { state: States.sitIdle, possibleNextStates: [States.walkRight, States.runRight] }, { state: States.walkRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.runRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.walkLeft, possibleNextStates: [States.sitIdle, States.climbWallLeft, States.walkRight, States.runRight] }, { state: States.runLeft, possibleNextStates: [States.sitIdle, States.climbWallLeft, States.walkRight, States.runRight] }, { state: States.climbWallLeft, possibleNextStates: [States.wallHangLeft] }, { state: States.wallHangLeft, possibleNextStates: [States.jumpDownLeft] }, { state: States.jumpDownLeft, possibleNextStates: [States.land] }, { state: States.land, possibleNextStates: [States.sitIdle, States.walkRight, States.runRight] }, { state: States.chase, possibleNextStates: [States.idleWithBall] }, { state: States.idleWithBall, possibleNextStates: [States.walkRight, States.walkLeft, States.runLeft, States.runRight] }, ] }; emoji(): string { return "🐱"; } } export class Dog extends BasePetType { label = "dog"; sequence = { startingState: States.sitIdle, sequenceStates: [ { state: States.sitIdle, possibleNextStates: [States.walkRight, States.runRight, States.lie] }, { state: States.lie, possibleNextStates: [States.walkRight, States.runRight] }, { state: States.walkRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.runRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.walkLeft, possibleNextStates: [States.sitIdle, States.lie, States.walkRight, States.runRight] }, { state: States.runLeft, possibleNextStates: [States.sitIdle, States.lie, States.walkRight, States.runRight] }, { state: States.chase, possibleNextStates: [States.idleWithBall] }, { state: States.idleWithBall, possibleNextStates: [States.walkRight, States.walkLeft, States.runLeft, States.runRight] }, ] }; emoji(): string { return "🐶"; } } export class Snake extends BasePetType { label = "snake"; sequence = { startingState: States.sitIdle, sequenceStates: [ { state: States.sitIdle, possibleNextStates: [States.walkRight, States.runRight] }, { state: States.walkRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.runRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.walkLeft, possibleNextStates: [States.sitIdle, States.walkRight, States.runRight] }, { state: States.runLeft, possibleNextStates: [States.sitIdle, States.walkRight, States.runRight] }, { state: States.chase, possibleNextStates: [States.idleWithBall] }, { state: States.idleWithBall, possibleNextStates: [States.walkRight, States.walkLeft, States.runLeft, States.runRight] }, ] }; emoji(): string { return "🐍"; } } export class Clippy extends BasePetType { label = "clippy"; sequence = { startingState: States.sitIdle, sequenceStates: [ { state: States.sitIdle, possibleNextStates: [States.walkRight, States.runRight] }, { state: States.walkRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.runRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.walkLeft, possibleNextStates: [States.sitIdle] }, { state: States.runLeft, possibleNextStates: [States.sitIdle] }, { state: States.chase, possibleNextStates: [States.idleWithBall] }, { state: States.idleWithBall, possibleNextStates: [States.walkRight, States.walkLeft, States.runLeft, States.runRight] }, ] }; emoji(): string { return "📎"; } } export class RubberDuck extends BasePetType { label = "rubber-duck"; sequence = { startingState: States.sitIdle, sequenceStates: [ { state: States.sitIdle, possibleNextStates: [States.walkRight, States.runRight] }, { state: States.walkRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.runRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.walkLeft, possibleNextStates: [States.sitIdle] }, { state: States.runLeft, possibleNextStates: [States.sitIdle] }, { state: States.chase, possibleNextStates: [States.idleWithBall] }, { state: States.idleWithBall, possibleNextStates: [States.walkRight, States.walkLeft, States.runLeft, States.runRight] }, ] }; emoji(): string { return "🐥"; } } export class Crab extends BasePetType { label = "crab"; sequence = { startingState: States.sitIdle, sequenceStates: [ { state: States.sitIdle, possibleNextStates: [States.walkRight, States.runRight] }, { state: States.walkRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.runRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.walkLeft, possibleNextStates: [States.sitIdle] }, { state: States.runLeft, possibleNextStates: [States.sitIdle] }, { state: States.chase, possibleNextStates: [States.idleWithBall] }, { state: States.idleWithBall, possibleNextStates: [States.walkRight, States.walkLeft, States.runLeft, States.runRight] }, ] }; emoji(): string { return "🦀"; } } export class Zappy extends BasePetType { label = "zappy"; sequence = { startingState: States.sitIdle, sequenceStates: [ { state: States.sitIdle, possibleNextStates: [States.walkRight, States.runRight] }, { state: States.walkRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.runRight, possibleNextStates: [States.walkLeft, States.runLeft] }, { state: States.walkLeft, possibleNextStates: [States.sitIdle] }, { state: States.runLeft, possibleNextStates: [States.sitIdle] }, { state: States.chase, possibleNextStates: [States.idleWithBall] }, { state: States.idleWithBall, possibleNextStates: [States.walkRight, States.walkLeft, States.runLeft, States.runRight] }, ] }; emoji(): string { return "⚡"; } } export class Rocky extends BasePetType { label = "rocky"; sequence = { startingState: States.sitIdle, sequenceStates: [ { state: States.sitIdle, possibleNextStates: [States.walkRight, States.runRight] }, { state: States.walkRight, possibleNextStates: [States.sitIdle, States.runRight] }, { state: States.runRight, possibleNextStates: [States.sitIdle, States.walkRight] } ] }; emoji(): string { return "💎"; } canChase(): boolean { return false; } } export class InvalidPetException { } function getPetName(collection: Map<number, string>, label: string, count: number) : string { if (collection.has(count)){ return collection.get(count)!; } else { return label + count; } } export function createPet(petType: string, el: HTMLImageElement, collision: HTMLDivElement, size: PetSize, left: number, bottom: number, petRoot: string, floor: number, name: string | undefined) : IPetType { if (petType === "totoro"){ if (name === undefined) {name = getPetName(TOTORO_NAMES, PetType.totoro, Totoro.count + 1);} return new Totoro(el, collision, size, left, bottom, petRoot, floor, name, PetSpeed.normal); } if (petType === "cat"){ if (name === undefined) {name = getPetName(CAT_NAMES, PetType.cat, Cat.count + Dog.count + 1);} // Cat and dog share the same name list return new Cat(el, collision, size, left, bottom, petRoot, floor, name, PetSpeed.normal); } else if (petType === "dog") { if (name === undefined) {name = getPetName(DOG_NAMES, PetType.dog, Dog.count + Cat.count + 1);} // Cat and dog share the same name list return new Dog(el, collision, size, left, bottom, petRoot, floor, name, PetSpeed.normal); } else if (petType === "snake") { if (name === undefined) {name = getPetName(SNAKE_NAMES, PetType.snake, Snake.count + 1);} return new Snake(el, collision, size, left, bottom, petRoot, floor, name, PetSpeed.verySlow); } else if (petType === "clippy") { if (name === undefined) {name = getPetName(CLIPPY_NAMES, PetType.clippy, Clippy.count + 1);} return new Clippy(el, collision, size, left, bottom, petRoot, floor, name, PetSpeed.slow); } else if (petType === "crab") { if (name === undefined) {name = getPetName(CRAB_NAMES, PetType.crab, Crab.count + 1);} return new Crab(el, collision, size, left, bottom, petRoot, floor, name, PetSpeed.slow); } else if (petType === "rubber-duck") { if (name === undefined) {name = getPetName(DUCK_NAMES, PetType.rubberduck, RubberDuck.count + 1);} return new RubberDuck(el, collision, size, left, bottom, petRoot, floor, name, PetSpeed.fast); } else if (petType === "zappy") { if (name === undefined) {name = getPetName(ZAPPY_NAMES, PetType.zappy, Zappy.count + 1);} return new Zappy(el, collision, size, left, bottom, petRoot, floor, name, PetSpeed.veryFast); } else if (petType === "rocky") { if (name === undefined) {name = getPetName(ROCKY_NAMES, PetType.rocky, Rocky.count + 1);} return new Rocky(el, collision, size, left, bottom, petRoot, floor, name, PetSpeed.still); } throw new InvalidPetException(); }
the_stack
import { VehicleInformation } from './samgongustofa.model' import { Injectable, HttpService, Inject } from '@nestjs/common' import * as xml2js from 'xml2js' import { environment } from '../../../../environments' import type { Logger } from '@island.is/logging' import { LOGGER_PROVIDER } from '@island.is/logging' import { RecyclingRequestService } from '../../recycling.request/recycling.request.service' @Injectable() export class SamgongustofaService { vehicleInformationList: VehicleInformation[] constructor( @Inject(LOGGER_PROVIDER) private logger: Logger, private httpService: HttpService, @Inject(RecyclingRequestService) private recyclingRequestService: RecyclingRequestService, ) {} async getVehicleInformation(nationalId: string) { try { this.logger.info('Starting getVehicleInformation call on ${nationalId}') const { soapUrl, soapUsername, soapPassword } = environment.samgongustofa const parser = new xml2js.Parser() // First soap call to get all vehicles own by person with nationalId in input const xmlAllCarsBodyStr = `<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:usx="https://xml.samgongustofa.is/scripts/WebObjects.dll/XML.woa/1/ws/.USXMLWS"> <soapenv:Header/> <soapenv:Body> <usx:allVehiclesForPersidno soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <username xsi:type="xsd:string">${soapUsername}</username> <password xsi:type="xsd:string">${soapPassword}</password> <xmlVersion xsi:type="xsd:string">2</xmlVersion> <clientPersidno xsi:type="xsd:string">${nationalId}</clientPersidno> <lawyerPersidno xsi:type="xsd:string">${nationalId}</lawyerPersidno> <requestedPersidno xsi:type="xsd:string">${nationalId}</requestedPersidno> <showDeregistered xsi:type="xsd:boolean">true</showeregistered> <showHistory xsi:type="xsd:boolean">false</showHistory> </usx:allVehiclesForPersidno> </soapenv:Body> </soapenv:Envelope>` const headersRequest = { 'Content-Type': 'application/xml', } this.logger.info('Start allVehiclesForPersidno Soap request.') const allCarsResponse = await this.httpService .post(soapUrl, xmlAllCarsBodyStr, { headers: headersRequest }) .toPromise() if (allCarsResponse.status != 200) { this.logger.error(allCarsResponse.statusText) throw new Error(allCarsResponse.statusText) } this.logger.info( 'allVehiclesForPersidno Soap request successed and start parsing xml to json', ) const loggerReplacement = this.logger // Parse xml to Json all Soap and added all vehicles and their information to vehicleInformationList this.vehicleInformationList = await parser .parseStringPromise(allCarsResponse.data.replace(/(\t\n|\t|\n)/gm, '')) .then(function (allCarsResult) { // check if SOAP returns 200 status code but with Fault message if ( Object.prototype.hasOwnProperty.call( allCarsResult['soapenv:Envelope']['soapenv:Body'][0], 'soapenv:Fault', ) ) { loggerReplacement.error( allCarsResult['soapenv:Envelope']['soapenv:Body'][0][ 'soapenv:Fault' ][0]['faultstring'][0], ) throw new Error( allCarsResult['soapenv:Envelope']['soapenv:Body'][0][ 'soapenv:Fault' ][0]['faultstring'][0], ) } // parse xml to Json Result return parser .parseStringPromise( allCarsResult['soapenv:Envelope']['soapenv:Body'][0][ 'ns1:allVehiclesForPersidnoResponse' ][0]['allVehiclesForPersidnoReturn'][0]['_'], ) .then(function (allCars) { if (allCars['persidnolookup']['vehicleList'][0] == '') { return [] } let vehicleArr: VehicleInformation[] vehicleArr = [] // TODO: will be fixed vehicleArr.push( new VehicleInformation( 'HX111', 'black', 'vinNumber', 'Nissan', '01.01.2020', true, true, 'inUse', ), ) vehicleArr = [] allCars['persidnolookup']['vehicleList'][0]['vehicle'].forEach( (car) => { loggerReplacement.info( `getting information for ${car['permno'][0]}`, ) let carIsRecyclable = true let carStatus = 'inUse' // If vehicle status is 'Afskráð' then the vehicle is 'deregistered' // otherwise is 'inUse' if (car['vehiclestatus'][0] == 'Afskráð') { carStatus = 'deregistered' carIsRecyclable = false } let carHasCoOwner = true if (car['otherowners'][0] == '0') { carHasCoOwner = false } else { carIsRecyclable = false } // Create new Vehicle information object on each vehicle const vehicleObj = new VehicleInformation( car['permno'][0], car['type'][0], car['color'][0], car['vin'][0], car['firstregdate'][0], carIsRecyclable, carHasCoOwner, carStatus, ) vehicleArr.push(vehicleObj) }, ) return vehicleArr }) .catch(function (err) { loggerReplacement.error( `Getting error while parsing second xml to json on allVehiclesForPersidno request: ${err}`, ) throw new Error('Getting Error while parsing xml to json...') }) }) .catch(function (err) { loggerReplacement.error( `Getting error while parsing first xml to json on allVehiclesForPersidno request: ${err}`, ) throw new Error('Getting Error while parsing xml to json...') }) this.logger.info('Finished extracting all vehicles') const newVehicleArr = this.vehicleInformationList // ForEach vehicle in vehicleInformationList, check and update vehicle's status for (let i = 0; i < newVehicleArr.length; i++) { const carObj = newVehicleArr[i] this.logger.info( `Starting extracting details information on ${carObj['permno']}`, ) if (carObj['status'] == 'inUse' && carObj['isRecyclable']) { // Vehicle information's Soap body const xmlBasicInfoBodyStr = `<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:usx="https://xml.samgongustofa.is/scripts/WebObjects.dll/XML.woa/1/ws/.USXMLWS"> <soapenv:Header/> <soapenv:Body> <usx:basicVehicleInformation soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <username xsi:type="xsd:string">${soapUsername}</username> <password xsi:type="xsd:string">${soapPassword}</password> <xmlVersion xsi:type="xsd:string">8</xmlVersion> <clientPersidno xsi:type="xsd:string">${nationalId}</clientPersidno> <permno xsi:type="xsd:string">${carObj['permno']}</permno> <regno xsi:type="xsd:string">null</regno> <vin xsi:type="xsd:string">null</vin> </usx:basicVehicleInformation> </soapenv:Body> </soapenv:Envelope>` const basicInforesponse = await this.httpService .post(soapUrl, xmlBasicInfoBodyStr, { headers: headersRequest }) .toPromise() if (basicInforesponse.status != 200) { this.logger.error(basicInforesponse.statusText) throw new Error(basicInforesponse.statusText) } // parse xml to Json all Soap this.logger.info( `Finished basicVehicleInformation Soap request and starting parsing xml to json on ${carObj['permno']}`, ) this.vehicleInformationList[i] = await parser .parseStringPromise( basicInforesponse.data.replace(/(\t\n|\t|\n)/gm, ''), ) .then(function (basicResult) { // check if SOAP returns 200 status code but with Fault message if ( Object.prototype.hasOwnProperty.call( basicResult['soapenv:Envelope']['soapenv:Body'][0], 'soapenv:Fault', ) ) { loggerReplacement.error( basicResult['soapenv:Envelope']['soapenv:Body'][0][ 'soapenv:Fault' ][0]['faultstring'][0], ) throw new Error( basicResult['soapenv:Envelope']['soapenv:Body'][0][ 'soapenv:Fault' ][0]['faultstring'][0], ) } // parse xml to Json Result return parser .parseStringPromise( basicResult['soapenv:Envelope']['soapenv:Body'][0][ 'ns1:basicVehicleInformationResponse' ][0]['basicVehicleInformationReturn'][0]['_'], ) .then(function (basicInfo) { // If there is any information in updatelocks, stolens, ownerregistrationerrors then we may not deregister it if ( typeof basicInfo.vehicle.ownerregistrationerrors[0] .ownerregistrationerror != 'undefined' ) { //Handle registrationerror loggerReplacement.info( 'vehicle has ownerregistrationerrors', ) newVehicleArr[i].isRecyclable = false } if ( //Handle stolen typeof basicInfo.vehicle.stolens[0].stolen != 'undefined' ) { for (const stolenEndDate of basicInfo.vehicle.stolens[0] .stolen) { if (!stolenEndDate.enddate[0].trim()) { loggerReplacement.info('vehicle is stolen') newVehicleArr[i].isRecyclable = false break } } } if ( typeof basicInfo.vehicle.updatelocks[0].updatelock != 'undefined' ) { //Handle lock for (const lockEndDate of basicInfo.vehicle.updatelocks[0] .updatelock) { if (!lockEndDate.enddate[0].trim()) { loggerReplacement.info('vehicle is locked') newVehicleArr[i].isRecyclable = false break } } } if (newVehicleArr[i].isRecyclable) { loggerReplacement.info( 'vehicle is clean. not stolen, not locked, no registrationerror', ) } loggerReplacement.info( 'isRecycleble=' + newVehicleArr[i].isRecyclable, ) return newVehicleArr[i] }) .catch(function (err) { loggerReplacement.error( `Getting error while parsing second xml to json on basicVehicleInformation request: ${err}`, ) throw new Error('Getting Error while parsing xml to json...') }) }) .catch(function (err) { loggerReplacement.error( `Getting error while parsing first xml to json on basicVehicleInformation request: ${err}`, ) throw new Error('Getting Error while parsing xml to json...') }) } } for (let i = 0; i < this.vehicleInformationList.length; i++) { const vehicle = this.vehicleInformationList[i] try { if (vehicle.isRecyclable) { this.logger.info( `Start getting requestType from DB for vehicle ${vehicle['permno']}`, ) const resRequestType = await this.recyclingRequestService.findAllWithPermno( vehicle['permno'], ) if (resRequestType.length > 0) { const requestType = resRequestType[0]['dataValues']['requestType'] this.vehicleInformationList[i]['status'] = requestType this.logger.info( `Got ${requestType} for vehicle ${vehicle['permno']}`, ) } } } catch (err) { this.logger.error( `Error while checking requestType in DB for vehicle ${vehicle['permno']} with error: ${err}`, ) } } this.logger.info( `---- Finished getVehicleInformation call on ${nationalId} ----`, ) return this.vehicleInformationList } catch (err) { this.logger.error( `Failed on getting vehicles information from Samgongustofa: ${err}`, ) throw new Error('Failed on getting vehicles information...') } } /* test */ static test(): any { return 'test' } }
the_stack
import * as React from 'react' import { unpack } from './tools' export interface XType { __xpath__?: string, __store__?: XStore<any> } export class XBoolean extends Boolean implements XType { __xpath__: string __store__: XStore<any> } export class XNumber extends Number implements XType { __xpath__: string __store__: XStore<any> } export class XString extends String implements XType { __xpath__: string __store__: XStore<any> } export class XArray extends Array<any> implements XType { __xpath__: string __store__: XStore<any> } export interface XOperation { operation: 'set' | 'merge' | 'update' | 'mark', path?: string, payload?: any, description?: string } export class XObject extends Object implements XType { __xpath__: string __store__: XStore<any> } export type MiddlewareContext = { name: string, agrs?: IArguments, return: any, store: XStore } export type ActionMiddleware = (context: MiddlewareContext, next: Function) => any export type Middleware = Array<{ type: "action" | "mutation", middleWare: ActionMiddleware // 可拓展 | OptionMiddleware }> export class XStore<State = {}, Actions = {}, Mutations = {}> { public __PASTATE_STORE__ = true; /** * 制定当前 store 的名称,可选 */ public name: string = ''; /** * immutable state 对象 */ public imState: State; /** * 响应式 state */ public state: State; /** * 执行 operation 操作前暂存的 imState 值 */ public preState: State; /** * 当前执行的 actions/ mutations 的名称 */ public currentActionName: string = ''; /** * dispatch 函数,待注入 * 当 state 发生改变后,会出发这个函数通知视图进行更新 * 目前该函数用于与 redux 配合使用: pastate-redux-react * 下一步:脱离 redux, 直接实现连接 react: pastate-react */ public dispatch: (action: any) => State; /** * 表示是否正在累积操作 */ public isQueuingOperations = false; /** * 待执行的 operation 列表. * 把 operation 累积起来再一起执行,可以实现一些基于多 operation 的中间件,具有较多的可操作性 */ public pendingOperationQueue: Array<XOperation> = [] // 配置项和默认值 // TODO 尝试支持 react 16.2 的 Fragment 包围语法,而不是 span public config = { useSpanNumber: true } // dispatch 把持器,如果下一次 disaptch 后还有 operation, 则不 dispatch // public holdDispatching: boolean = false // 兼容原始 reducer 的功能暂不实现 // private reducer: Function // setRawReducer(reducer: (state: State, action: Object) => State): void /** * 构造state * @param initState * @param createElement 可选,如果注入,数字可以直接渲染 */ constructor(initState: State, config?: { useSpanNumber?: boolean }) { config && ((Object as any).assign(this.config, config)); this.imState = this.toXType(initState, '') as State; // TODO: 处理新建对象的情况(数组函数, 把null设为对象值) this.state = this.makeRState([]); this.preState = this.imState; } // MARK: 响应式 state 的处理相关函数 private makeRState(path: string[], newValue?: any): any { let node: any; if (newValue) { let newValueTypeName: string = (Object.prototype.toString.call(node) as string).slice(8, -1); switch (newValueTypeName) { case 'Object': node = { ...newValue }; break; case 'Array': node = [...newValue]; break; default: node = newValue; } } else { node = XStore.getValueByPath(this.imState, path); } let typeName: string = (Object.prototype.toString.call(node) as string).slice(8, -1); let rnode: any; if (typeName == 'Object') { rnode = {} } else if (typeName == 'Array') { // 待往外封装(需要把 set 操作改为非 this.xx 模式才可以封装) rnode = []; let context = this; // NOTICE: 数组操作都是同步进行的函数 // TODO: 实现数组函数的半同步功能(数据同步更改,但是在下一个 tick 再 dispatch ) // 做一个 toDispatch 识别器,需要时 toDispatch = true, dispatch 后 false, 防止异步 dispatch 进行无畏的dispatch // 这种实现模式看起来比较耗资源, 考虑使用对象原因的模式 // 目前只支持 push 单一元素 Object.defineProperty(rnode, 'push', { enumerable: false, get: function () { // 目前只支持插入一个元素,新版本将支持插入多个元素 return function (element: any) { context.update(XStore.getValueByPath(context.imState, path), arr => [...arr, element]); let rValue = context.makeRState([...path, rnode.length], element) Object.defineProperty(rnode, rnode.length, { enumerable: true, configurable: true, get: () => { return rValue; }, set: (_newValue: any) => { context.set(XStore.getValueByPath(context.imState, path)[rnode.length], _newValue) } }) context.sync() } } }) Object.defineProperty(rnode, 'pop', { enumerable: false, get: function () { return function () { if (rnode.length <= 0) { return null } let lastOneIndex = rnode.length - 1; context.update(XStore.getValueByPath(context.imState, path), arr => arr.slice(0, -1)); let lastOne = XStore.getValueByPath(context.imState, path)[lastOneIndex] delete rnode[lastOneIndex] rnode.length -= 1 context.sync() return unpack(lastOne); } } }) // 目前只支持 unshift 单一元素 Object.defineProperty(rnode, 'unshift', { enumerable: false, get: function () { // 目前只支持插入一个元素,新版本将支持插入多个元素 return function (element: any) { context.update(XStore.getValueByPath(context.imState, path), arr => [element, ...arr]); let rValue = context.makeRState([...path, rnode.length], element) Object.defineProperty(rnode, rnode.length, { enumerable: true, configurable: true, get: () => { return rValue; }, set: (_newValue: any) => { context.set(XStore.getValueByPath(context.imState, path)[rnode.length], _newValue) } }) context.sync() } } }) // TODO: 面对数组结构,元素不一样的情况( 元素里面有数组结构 ) // 性能与通用性问题 // 方案一:计划推出一个 store.refreshState(state.xxx.xxx) 来实现手动更新响应式节点 // 方案二: 这种模式不要用响应式模式,而是直接用 imState 方法 // DELAY: 这个方法兼容push的新值结构不一致的情况 // 基于 pathstate 的模式在数组对象的需要变化时,会导致所有需要重新遍历所有子树的 pathstate 值, 此处有优化空间 // Object.defineProperty(rnode, '_unshift', { // enumerable: false, // get: function () { // return function (element: any) { // // 基于 pathstate 的模式在数组对象的需要变化时,会导致所有需要重新遍历所有子树的 pathstate 值, 此处有优化空间 // element = {...element} // context.update(XStore.getValueByPath(context.imState, path), arr => [element, ...arr]); // let newRNode = context.makeRState(path, [element, ...XStore.getValueByPath(context.imState, path)]); // // TODO: 更新挂载点, 获取数组节点的父级,重新 define // } // } // }) Object.defineProperty(rnode, 'shift', { enumerable: false, get: function () { return function () { if (rnode.length <= 0) { return null } let lastOneIndex = rnode.length - 1; context.update(XStore.getValueByPath(context.imState, path), arr => arr.slice(1)); delete rnode[lastOneIndex] rnode.length -= 1 let targetArray = XStore.getValueByPath(context.imState, path); let returnValue = targetArray[targetArray.length - rnode.length - 1]; context.sync(); return unpack(returnValue); } } }) Object.defineProperty(rnode, 'splice', { enumerable: false, get: function () { // 目前只支持插入一个元素,新版本将支持插入多个元素 return function (start: number, deleteCount: number, newElement: any) { context.update(XStore.getValueByPath(context.imState, path), arr => { if(newElement){ arr.splice(start, deleteCount, newElement) }else{ arr.splice(start, deleteCount) } return arr }); let lastOneIndex = rnode.length - 1; if ( deleteCount == 0 && newElement !== undefined){ // 加元素 let rValue = context.makeRState([...path, rnode.length], newElement) Object.defineProperty(rnode, rnode.length, { enumerable: true, configurable: true, get: () => { return rValue; }, set: (_newValue: any) => { context.set(XStore.getValueByPath(context.imState, path)[rnode.length], _newValue) } }) // 已经自动加长度了 }else{ // 减元素 for (let i = 0; i < deleteCount - (newElement !== undefined ? 1 : 0); i++) { delete rnode[lastOneIndex - i] } // 修改响应式长度 rnode.length -= (deleteCount - (newElement !== undefined ? 1 : 0)) } let targetArray = XStore.getValueByPath(context.imState, path); // let rValue = context.makeRState([...path], XStore.getValueByPath(context.imState, path)) let popValues = targetArray.slice(start, start + deleteCount) context.sync(); return unpack(popValues) } } }) Object.defineProperty(rnode, 'sort', { enumerable: false, get: function () { return function (compareFunction: any) { context.update(XStore.getValueByPath(context.imState, path), arr => arr.sort(compareFunction)); context.sync(); // 没有 unpack return XStore.getValueByPath(context.imState, path) } } }) Object.defineProperty(rnode, 'reverse', { enumerable: false, get: function () { return function () { context.update(XStore.getValueByPath(context.imState, path), arr => arr.reverse()); context.sync(); // 没有 unpack return XStore.getValueByPath(context.imState, path) } } }) } else { throw new Error('updateRState meet not object value, this is an error of pastate, typeName: ' + typeName) } for (let prop in node) { if (node.hasOwnProperty(prop) && prop != '__xpath__') { let valueTypeName: string = (Object.prototype.toString.call(node[prop]) as string).slice(8, -1); // 对象嵌套响应式建立 if (valueTypeName == 'Object' || valueTypeName == 'Array') { // 对象或数组,建立新的响应式节点 let rValue = this.makeRState([...path, prop], node[prop]) Object.defineProperty(rnode, prop, { enumerable: true, configurable: true, get: () => { let valueToGet = XStore.getValueByPath(this.imState, path)[prop]; if (valueToGet === null || valueToGet === undefined) { return valueToGet; } else { return rValue; } }, set: (_newValue: any) => { // 把对象节点设置为 null 的情况 if (_newValue === null || _newValue === undefined) { console.warn(`[pastate] You are setting an ${valueTypeName} node to be '${_newValue}', which is deprecated.`) } let valueToSet = XStore.getValueByPath(this.imState, path)[prop]; if (valueToSet === null || valueToSet === undefined) { this.merge({ __xpath__: path.map(p => '.' + p).join('') }, { [prop]: _newValue } as any) } else { this.set(valueToSet, _newValue) } // 设置新对象类节点的问题 if (valueTypeName == 'Array' || valueTypeName == 'Object') { // 重新建立响应式节点 rValue = this.makeRState([...path, prop], _newValue) // TODO 待测试嵌套对象 } } }) } else { // 基本类型 let getValue; Object.defineProperty(rnode, prop, { enumerable: true, configurable: true, get: () => { getValue = XStore.getValueByPath(this.imState, path)[prop]; if (getValue === null || getValue === undefined) { return getValue } switch (valueTypeName) { // 返回非对象类型的 plain 数据 case 'Number': return +getValue; case 'Boolean': return getValue == true; // 文字保留对象类型也可以,此处不一定要转化 case 'String': return getValue + ''; default: return getValue } }, set: (_newValue: any) => { // DALAY: 下版本考虑支持把叶子转化为节点 (开发者水平容错性) let newValueTypeName: string = (Object.prototype.toString.call(_newValue) as string).slice(8, -1); let valueToSet = XStore.getValueByPath(this.imState, path)[prop]; if (valueToSet === null || valueToSet === undefined) { this.merge({ __xpath__: path.map(p => '.' + p).join('') }, { [prop]: _newValue } as any) } else { // TODO:看看原始值是否为null, 如果是,则需要建立响应式 this.set(valueToSet, _newValue) } if (newValueTypeName == 'Array' || newValueTypeName == 'Object') { console.info('[pastate] You are setting a node with the string | number | boolean | null | undefined value to be Array or Object.') console.error('[pastate]This is a test feature! Not done yet!') getValue = this.makeRState([...path, prop], node[prop]) // TODO TEST } } }) } } } return rnode; } // 通过获取 public getResponsiveState(imState: XType): any { let pathArr: Array<string>; if (imState.__xpath__ === undefined) { throw new Error('[pastate] getResponsiveState: you shuold give an imState node') } else if (imState.__xpath__ == '') { pathArr = [] } else { pathArr = imState.__xpath__.split('.'); pathArr.shift(); } return XStore.getValueByPath(this.state, pathArr); } /** * 通过 path 获取 imState */ public getByPath(path: string | Array<string>): any { let pathArr: Array<string>; if (typeof path == 'string') { pathArr = path.split('.'); if (path == '' || path[0] == '.') pathArr.shift() } else if (Array.isArray(path)) { pathArr = path; } else { throw new Error('[store.setByPath] literalPath can only be string or Array<string>') } return XStore.getValueByPath(this.imState, pathArr) } // MARK: operation 输入相关方法 ----------------------------------------------------------- /** * ### 对 state 进行 set 操作 * @param stateToOperate * @param newValue : T | null , FIXME: 引入 Xtype 的 null 对象后, 可把 null 取消掉 * @param description * @return this 以支持链式调用 */ public set<T>(stateToOperate: T, newValue: T, description?: string): XStore<State> { this.submitOperation({ operate: 'set', stateToOperate: stateToOperate, payload: newValue, description: description }) return this } /** * set 设置新属性的版本 * 当前值为 null 或 undefined 时需要用此方法 */ public setByPath(path: string | Array<string>, newValue: any, description?: string): XStore<State> { let literalPath; if (typeof path == 'string') { literalPath = path } else if (Array.isArray(path)) { literalPath = path.join('.'); } else { throw new Error('[store.setByPath] literalPath can only be string or Array<string>') } if (literalPath[0] != '.') literalPath = '.' + literalPath this.submitOperation({ operate: 'set', stateToOperate: { __xpath__: literalPath }, payload: newValue, description: description }) return this } /** * ### 对 state 进行 merge 操作 * 进行的是浅层 merge * // TODO: 待研究 deep merge 的必要性 * @param stateToOperate * @param newValue * @param description */ public merge<T>(stateToOperate: T, newValue: Partial<T>, description?: string): XStore<State> { this.submitOperation({ operate: 'merge', stateToOperate: stateToOperate, payload: newValue, description: description }) return this } /** * ### 对 state 进行 update 操作 * // TODO 待写使用说明 * - 如果 `state` 是 `boolean | number | string`, ... * - 如果 `state` 是 `array`, ... * - 如果 `state` 是 `object`, ... * @param stateToOperate * @param updater * @param description */ public update<T>(stateToOperate: T, updater: (value: T) => T, description?: string): XStore<State> { this.submitOperation({ operate: 'update', stateToOperate: stateToOperate, payload: updater, description: description }) return this } /** * 底层operation提交函数 * 检查提交参数,如果合法,把操作提交到待执行操作列表 */ private submitOperation(rawParams: { operate: 'set' | 'merge' | 'update', stateToOperate: any, payload: any, description?: any }) { // stateToOperate 合法性处理 if (rawParams.stateToOperate === undefined || rawParams.stateToOperate === null) { console.warn('Opertion can only perform operation using `path inferrence` when the state is not undefined or null state.') console.warn('`stateToOperate` is given ', rawParams.stateToOperate, ', please checkout are there some errors in `stateToOperate`. If not, try below:') console.warn('There are some ways to go, choose one as you like:') console.warn('- Use `setByPath` instead: for example, this.setByPath(\'this.imState.propThatIsNull\', ...)') console.warn('- If you want to use operation with path inferrence from, you should use {}, \'\', NaN to be the initial value, and do not set any state value to be undefined or null') if (rawParams.operate == 'set') { console.warn('- You also can use `merge` operation to set the new value into the state that is having undefined or null value.') } if (rawParams.operate == 'update') { console.warn('- If you want to update a state without using present it`s value, it is no need to use `update` operation, please use `set` or `merge` instead.') } throw new Error(`[Error store.${rawParams.operate}] \`stateToOperate\` is undefined or null.`) } // 路径提取 let path = ''; if (typeof (rawParams.stateToOperate as XType).__xpath__ == 'string') { path = (rawParams.stateToOperate as XType).__xpath__ as string } else { throw new Error(`[Error store.${rawParams.operate}] \`stateToOperate\` has no string __xpath__`) } // payload 合法性处理 let payloadType: string = (Object.prototype.toString.call(rawParams.payload) as string).slice(8, -1); if (payloadType == 'Undefined' || payloadType == 'Null') { console.warn(`[pastate] You are making ${path} to be \`undefined\` or \`null\`, which is deprecated.`) } // 执行 operation 队列插入操作 this.tryPushOperation({ operation: rawParams.operate, path: path, payload: rawParams.payload, description: rawParams.description }) } /** * 设置 operation 描述型分割线,可以再执行 operation 时输出 */ public setOperationMarker(description: string): void { this.tryPushOperation({ operation: 'mark', description: description }) } /** * 尝试把 operation 加入到 pendding 队列 */ private tryPushOperation(operation: XOperation) { if (this.stateWillAddOperation(operation)) { // 设置异步 operation 启动器 if (!this.isQueuingOperations) { this.isQueuingOperations = true; setTimeout(() => { if (this.isQueuingOperations == true) { this.isQueuingOperations = false; this.beginReduceOpertions(); } }, 0); } this.pendingOperationQueue.push(operation) } else { console.info('[Error store.tryPushOperation] Operation pushing is canceled.') } } // MARK: operation 处理相关方法 ------------------------------------------------------ /** * operations 队列处理启动函数 * // TO TEST */ public beginReduceOpertions() { if(this.pendingOperationQueue.length == 0){ return } // 本函数主要负责流程控制和生命周期函数的调用 if (!this.stateWillReduceOperations()) { console.info('Operations reducing has been canceled at beginning!') return; } let loadingOperationQueue = this.pendingOperationQueue; this.pendingOperationQueue = []; this.preState = this.imState; let hadRan = 0; let tookEffect = 0; let isDone = false; // 按顺序 reduce operation try { isDone = loadingOperationQueue.every((operation: XOperation, index: number) => { if (!this.stateWillApplyOperation(index)) { console.info(`Operations reducing has been canceled at ${index}!`, operation) return false } let result = this.applyOperation(operation) if (!result.isMarker) hadRan += 1; if (result.tookEffect) tookEffect += 1; if (!this.stateDidAppliedOperation({ index, tookEffect: result.tookEffect, oldValue: result.oldValue })) { console.info(`Operations reducing has been stop after ${index}!`, operation) return false } return true }) } catch (e) { console.error('[XStore] Operation reduction is terminated: ' + (e as Error).message); } if (this.dispatch) { this.dispatch({ type: '@@PASTATE: ' + (this.name || '(anonymous store)') + ' ' + this.currentActionName }) this.currentActionName && (this.currentActionName = '') // 消费一次后清空 } else { // console.error('[XStore] dispatch method is not injected'); } this.stateDidReducedOperations({ isDone, // 表明是否全部成功执行 all: loadingOperationQueue.length, // 待执行的 operation 总数 realOperation: loadingOperationQueue.filter(v => v.operation != 'mark').length, // 非 marker 的 operation 总数 hadRan, // 已成功运行的 operation 总数 tookEffect, // 使 state 改变的 operation 总数 }) } public forceUpdate() { if (this.imState == this.preState) { console.info('[Pastate] The imState is no changed, skip force update') return } this.preState = this.imState; if (this.dispatch ) { this.dispatch({ type: '@@PASTATE: [forceUpdate] ' + (this.name || '(anonymous store)') + ' ' + this.currentActionName }) this.currentActionName && (this.currentActionName = '') // 消费一次后清空 } else { // console.error('[XStore] dispatch method is not injected') } } /** * 手动地对应用state进行更新 */ public sync() { this.beginReduceOpertions(); } /** * 手动地对应用state进行更新(sync_array_method 专用) */ // public sync_array_method() { // this.holdDispatching = true // this.beginReduceOpertions(); // } /** * operation 项处理器,负责 imState = imState + operation 的逻辑 * @throws 但执行失败时直接抛出异常 * @returns object */ private applyOperation(operation: XOperation): { isMarker: boolean, oldValue: any, tookEffect: boolean } { if (operation.operation == 'mark') { // 如果要在其他地方实现 log 逻辑,那么需要在实现处把这个 operation “消化掉”(reduce) console.log(`[Operation Marker] ----------- ${operation.description} ----------- `) return { isMarker: true, oldValue: this.imState, tookEffect: false } } // 实现笔记 // 阶段一:(1)路径更新 -> (2)值的赋值 【这样一来,tookEffect 的值都是 true】 // 阶段二:实现 tookEffect 的逻辑 // 目前为阶段一的实现 // 采用 方向溯回更新期的逻辑进行更新 // A. 如果要设置的值是 基础类型,则需更新其父亲的引用 // B. 如果要更新的值是 数组或对象,则虚更新本身及其父亲的引用 let pathArr: Array<any> = operation.path!.split('.'); pathArr.shift(); let endPath; let fatherNode; let newValue; let payload = operation.payload; let preValue = XStore.getValueByPath(this.preState, pathArr); let valueType = (Object.prototype.toString.call(preValue) as string).slice(8, -1); // set 作用于任何值 if (operation.operation == 'set') { // “相同” 值情况的处理 // "相同" 的基本值不进行更新处理;"相同"的引用值进行更新引用处理 if (payload == preValue) { if (valueType == 'Array') { payload = [...payload] } else if (valueType == 'Object') { payload = { ...payload } } else { return { isMarker: false, oldValue: this.preState, tookEffect: false } } } // 更新根值的情况 if (pathArr.length == 0) { this.imState = this.toXType(payload, operation.path!) as State; console.info('[set] You are setting the entire state, please check if you really want to do it.') } else { endPath = pathArr.pop(); fatherNode = this.getNewReference(pathArr); fatherNode[Array.isArray(fatherNode) ? [endPath - 0] : endPath] = this.toXType(payload, operation.path!) } return { isMarker: false, oldValue: this.preState, tookEffect: true } } // merge 仅是作用于对象 else if (operation.operation == 'merge') { // 仅支持对对象进行处理 if (valueType != 'Object') { throw new Error('[merge] You can only apply `merge` operation on an object') } if ((Object.prototype.toString.call(payload) as string).slice(8, -1) != 'Object') { throw new Error('[merge] You can only apply `merge` operation with an object payload') } fatherNode = this.getNewReference(pathArr); for (let key in payload) { // payload 一般是字面值给出的,无需检查 hasOwnProperty if (key != '__xpath__') { // NOTE: 此处暂不实现 takeEffect 逻辑 fatherNode[key] = this.toXType(payload[key], operation.path + '.' + key) } } return { isMarker: false, oldValue: this.preState, tookEffect: true // 这里暂时均为生效 } } // update 作用于任何值 else if (operation.operation == 'update') { let oldValue = XStore.getValueByPath(this.imState, pathArr); if (oldValue === preValue) { if (valueType == 'Array') { oldValue = [...oldValue] } else if (valueType == 'Object') { oldValue = { ...oldValue } } } newValue = operation.payload(oldValue) let newXTypeValue = this.toXType(newValue, operation.path!); if (pathArr.length == 0) { this.imState = newXTypeValue as State; } else { endPath = pathArr.pop(); fatherNode = this.getNewReference(pathArr); fatherNode[Array.isArray(fatherNode) ? [endPath - 0] : endPath] = newXTypeValue; } return { isMarker: false, oldValue: this.preState, tookEffect: true // 这里暂时均为生效 } } else { throw new Error('[XStore] operation invalid!') } } /** * 通过路径获取 state 中的值 * @param path */ public static getValueByPath(rootObj: any, pathArr: Array<string>) { return pathArr.reduce((preValue, curPath: any) => preValue[Array.isArray(preValue) ? (curPath - 0) : curPath], rootObj) } /** * 溯源性地更新节点的引用对象并返回 * @param pathArr * @return 更新后的节点的值 */ public getNewReference(pathArr: Array<string>): XType { pathArr = [...pathArr]; let curValue: XType = XStore.getValueByPath(this.imState, pathArr); let preValue: XType = XStore.getValueByPath(this.preState, pathArr); // 该函数只(需)支持对象或数组的情况 // 测试时请勿传入指向基本值的 path , 实际情况中无需实现 if (curValue == preValue) { curValue = Array.isArray(preValue) ? [...preValue] as XType : { ...preValue } as XType; Object.defineProperty(curValue, "__xpath__", { enumerable: false, value: preValue.__xpath__, writable: true }); Object.defineProperty(curValue, "__store__", { value: this, enumerable: false, writable: false }); // 溯源更新 后 挂载新值(此处不可逆序,否则会导致 preState 被改动) if (pathArr.length == 0) { this.imState = curValue as State; } else { let endPath: any = pathArr.pop(); let fatherValue = this.getNewReference([...pathArr]); // 此处特别注意要 “按值传参” fatherValue[Array.isArray(fatherValue) ? (endPath - 0) : endPath] = curValue; } } return curValue; } /** * 实现普通类型到 XType 类型的转化 */ public toXType(rawData: any, path: string): XType | undefined | null { // NOTE: 如果根据自实现 immuateble 转化逻辑,此处有性能优化空间 if (rawData === undefined) { return undefined; } if (rawData === null) { return null; } let xNewData: XType; let typeName: string = (Object.prototype.toString.call(rawData) as string).slice(8, -1); // 处理 raw 类型 if (rawData.__xpath__ === undefined) { switch (typeName) { case 'Boolean': xNewData = new Boolean(rawData) as XBoolean; break; case 'Number': xNewData = new Number(rawData) as XNumber; this.config.useSpanNumber && (Object as any).assign(xNewData, React.createElement('span', undefined, +rawData)); break; case 'String': xNewData = new String(rawData) as XString; break; case 'Array': xNewData = new Array(rawData) as XArray; // recursive call toXType(...) to transform the inner data xNewData = (rawData as Array<any>).map((value: any, index: number) => { return this.toXType(value, path + '.' + index) }) as XType; break; case 'Object': xNewData = {...rawData} as XObject; // recursive call toXType(...) to transform the inner data for (let prop in xNewData) { if (xNewData.hasOwnProperty(prop) && prop != '__xpath__') { xNewData[prop] = this.toXType(rawData[prop], path + '.' + prop); } } break; default: console.error('[XStore] XType transform error:', typeName); xNewData = new XObject(undefined); } Object.defineProperty(xNewData, "__xpath__", { value: path, enumerable: false, writable: true }); if (xNewData.__store__ === undefined) { Object.defineProperty(xNewData, "__store__", { value: this, enumerable: false, writable: false }); } } // 处理 xtype 类型 else { xNewData = rawData; // NOTE: 根据 im 特性,对于 array 和 object 类型,如果内部数据改变, // 则溯源节点的引用都会更新,此时该节点会变成 plain 类型,会走上面的转化过程。 // 如果是数组的变化的情况,会使得操作值包含 _xtype_, 此时需要嵌套更新 if (xNewData.__xpath__ != path) { xNewData.__xpath__ = path switch (typeName) { case 'Array': // recursive call toXType(...) to transform the inner data xNewData = (rawData as Array<any>).map((value: any, index: number) => { return this.toXType(value, path + '.' + index) }) as XType; break; case 'Object': // recursive call toXType(...) to transform the inner data for (let prop in xNewData) { if (xNewData.hasOwnProperty(prop) && prop != '__xpath__') { rawData[prop] = this.toXType(rawData[prop], path + '.' + prop); } } break; default: break; } } } return xNewData; } // MARK: 生命周期函数 ---------------------------------------------------------------- /** * 生命周期函数:将要增加 operation 时会被调用 * @param operate * @returns boolean 表示是否继续执行后续操作 */ public stateWillAddOperation(operation: XOperation): boolean { // TODO // 可以实现 logger,chrome 调试器等功能 // 建议实现检查 payload 类型合法性的功能 return true; } /** * 生命周期函数:将要执行 operations 时会被调用 * @returns boolean 表示是否继续执行后续操作 */ public stateWillReduceOperations(): boolean { // TODO 可以实现 operation 序列检查器功能,提醒一些不建议的操作等 // 在开发本类库时,还可以检查是否产生空序列执行等问题 return true; } /** * 生命周期函数:将要执行一个 operation 时会被调用 * @param operationIndex operations 中的索引号 * @returns boolean 表示是否继续执行后续操作 */ public stateWillApplyOperation(operationIndex: number): boolean { // 可以实现某些中间件 return true } /** * 生命周期函数:执行完一个 operation 后会被调用 * @param info object * - index 表示 operations 中的索引号 * - tookEffect 表示这个 operation 是否对 state 产生修改作用 * - oldValue 执行这个操作前的 state * @returns boolean 表示是否继续执行后续操作 */ public stateDidAppliedOperation(info: { index: number, tookEffect: boolean, oldValue: any }): boolean { // 可以实现 operation细节logger 等功能 return true } /** * 生命周期函数:执行完 operations 时执行 * @returns boolean 表示是否继续执行后续操作 */ public stateDidReducedOperations(stats: { isDone: boolean, // 表明 operation reduce 过程是否终止 all: number, // 执行的 operation 总数 realOperation: number, // 非 marker 的 operation 总数 hadRan: number, // 成功运行的 operation 总数 tookEffect: number, // 使 state 改变的 operation 总数 }): boolean { // TODO 可以输出操作到调试器等,此时 this.operations 数组还没重置;可以用于本类库测试,也可以用于消费者的调试 // 可以对 preState 进行 log, 压栈(以支持撤销)等操作 return true } // -------------------------- redux 对接函数 ------------------------------ public getReduxReducer() { // 只需传回 state 即可 return () => this.imState; } // ----------------------------- 中间件相关 ----------------------------- /** * 改为 seeter, 分出 _actions middlesware 和 mutations middleware 和 生命周期函数 middleware ? */ // private _middleWares: Middleware // public set middleWares(value: Middleware) { // if (this._middleWares) { // throw new Error('') // } // this._middleWares = value // this._actionMiddlewares = null // this.linkActionMiddleWare() // } private _actions: { [key in keyof Actions]: any } public get actions(): Actions{ return this._actions } public set actions(rawActions: Actions) { this._actions = rawActions this._actionMiddlewares && this.linkActionMiddleWare() } private _actionMiddlewares: Array<ActionMiddleware>; public get actionMiddlewares(): Array<ActionMiddleware> { return this._actionMiddlewares } public set actionMiddlewares(actionMiddlewares: Array<ActionMiddleware>) { if (this._actionMiddlewares) { console.error('[pastate] You has set actionMiddlewares agian! It is not supported now') } this._actionMiddlewares = actionMiddlewares; this.actions && this.linkActionMiddleWare() } private linkActionMiddleWare(actions?: { [x: string]: ActionMiddleware }, path?: string) { if( !actions){ actions = this._actions } let middlewares = this._actionMiddlewares let thisContext = this for (const key in actions) { if (actions.hasOwnProperty(key)) { const element = actions[key]; let elementTypeName: string = (Object.prototype.toString.call(element) as string).slice(8, -1); if (elementTypeName == 'Object') { // 迭代 this.linkActionMiddleWare(element as any, key) as any } else { // 连接中间件 let context: MiddlewareContext = { name: path ? path + '.' + key : key, agrs: undefined, return: undefined, store: thisContext } let lastMiddleware = function (_context: MiddlewareContext) { _context.return = element.apply(null, _context.agrs) } let allMiddlewares = [...middlewares!, lastMiddleware] allMiddlewares.reverse(); let runner = allMiddlewares.reduce(function (preValue: any, middleware: ActionMiddleware) { return middleware.bind(null, context, preValue) }, null) actions[key] = function () { context.agrs = arguments context.return = undefined runner() return context.return } } } } } // 考虑用多级 actions 来划分 不同类型的操作 // 基于 option 生命周期中间件系统, 计划开发中 // 中间件: // log 中间件:用于开发调试,或者用户行为跟踪 // 调用计数中间件:用于用户行为统计 }
the_stack
import { Match, Template } from '@aws-cdk/assertions'; import * as iam from '@aws-cdk/aws-iam'; import * as cdk from '@aws-cdk/core'; import * as cpactions from '../../lib'; import { TestFixture } from './test-fixture'; /* eslint-disable quote-props */ let stack: TestFixture; let importedAdminRole: iam.IRole; beforeEach(() => { stack = new TestFixture({ env: { account: '111111111111', region: 'us-east-1', }, }); importedAdminRole = iam.Role.fromRoleArn(stack, 'ChangeSetRole', 'arn:aws:iam::1234:role/ImportedAdminRole'); }); describe('StackSetAction', () => { function defaultOpts() { return { actionName: 'StackSetUpdate', description: 'desc', stackSetName: 'MyStack', cfnCapabilities: [cdk.CfnCapabilities.NAMED_IAM], failureTolerancePercentage: 50, maxAccountConcurrencyPercentage: 25, template: cpactions.StackSetTemplate.fromArtifactPath(stack.sourceOutput.atPath('template.yaml')), parameters: cpactions.StackSetParameters.fromArtifactPath(stack.sourceOutput.atPath('parameters.json')), }; }; describe('self-managed mode', () => { test('creates admin role if not specified', () => { stack.deployStage.addAction(new cpactions.CloudFormationDeployStackSetAction({ ...defaultOpts(), stackInstances: cpactions.StackInstances.fromArtifactPath( stack.sourceOutput.atPath('accounts.json'), ['us-east-1', 'us-west-1', 'ca-central-1'], ), deploymentModel: cpactions.StackSetDeploymentModel.selfManaged({ executionRoleName: 'Exec', }), })); const template = Template.fromStack(stack); template.hasResourceProperties('AWS::IAM::Policy', { 'PolicyDocument': { 'Statement': Match.arrayWith([ { 'Action': [ 'cloudformation:CreateStackInstances', 'cloudformation:CreateStackSet', 'cloudformation:DescribeStackSet', 'cloudformation:DescribeStackSetOperation', 'cloudformation:ListStackInstances', 'cloudformation:UpdateStackSet', ], 'Effect': 'Allow', 'Resource': { 'Fn::Join': ['', [ 'arn:', { 'Ref': 'AWS::Partition' }, ':cloudformation:us-east-1:111111111111:stackset/MyStack:*', ]], }, }, { 'Action': 'iam:PassRole', 'Effect': 'Allow', 'Resource': { 'Fn::GetAtt': ['PipelineDeployStackSetUpdateStackSetAdministrationRole183434B0', 'Arn'] }, }, ]), }, 'Roles': [ { 'Ref': 'PipelineDeployStackSetUpdateCodePipelineActionRole3EDBB32C' }, ], }); template.hasResourceProperties('AWS::CodePipeline::Pipeline', { 'Stages': [ { 'Name': 'Source' /* don't care about the rest */ }, { 'Name': 'Deploy', 'Actions': [ { 'Configuration': { 'StackSetName': 'MyStack', 'Description': 'desc', 'TemplatePath': 'SourceArtifact::template.yaml', 'Parameters': 'SourceArtifact::parameters.json', 'PermissionModel': 'SELF_MANAGED', 'AdministrationRoleArn': { 'Fn::GetAtt': ['PipelineDeployStackSetUpdateStackSetAdministrationRole183434B0', 'Arn'] }, 'ExecutionRoleName': 'Exec', 'Capabilities': 'CAPABILITY_NAMED_IAM', 'DeploymentTargets': 'SourceArtifact::accounts.json', 'FailureTolerancePercentage': 50, 'MaxConcurrentPercentage': 25, 'Regions': 'us-east-1,us-west-1,ca-central-1', }, 'Name': 'StackSetUpdate', }, ], }, ], }); template.hasResourceProperties('AWS::IAM::Policy', { 'PolicyDocument': { 'Statement': [ { 'Effect': 'Allow', 'Action': 'sts:AssumeRole', 'Resource': { 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':iam::*:role/Exec']] }, }, ], }, }); }); test('passes admin role if specified', () => { stack.deployStage.addAction(new cpactions.CloudFormationDeployStackSetAction({ ...defaultOpts(), stackInstances: cpactions.StackInstances.fromArtifactPath( stack.sourceOutput.atPath('accounts.json'), ['us-east-1', 'us-west-1', 'ca-central-1'], ), deploymentModel: cpactions.StackSetDeploymentModel.selfManaged({ executionRoleName: 'Exec', administrationRole: importedAdminRole, }), })); const template = Template.fromStack(stack); template.hasResourceProperties('AWS::IAM::Policy', { 'PolicyDocument': { 'Statement': [ { 'Action': [ 'cloudformation:CreateStackInstances', 'cloudformation:CreateStackSet', 'cloudformation:DescribeStackSet', 'cloudformation:DescribeStackSetOperation', 'cloudformation:ListStackInstances', 'cloudformation:UpdateStackSet', ], 'Effect': 'Allow', 'Resource': { 'Fn::Join': [ '', [ 'arn:', { 'Ref': 'AWS::Partition' }, ':cloudformation:us-east-1:111111111111:stackset/MyStack:*', ], ], }, }, { 'Action': 'iam:PassRole', 'Effect': 'Allow', 'Resource': 'arn:aws:iam::1234:role/ImportedAdminRole', }, { 'Action': [ 's3:GetObject*', 's3:GetBucket*', 's3:List*', ], 'Effect': 'Allow', 'Resource': [ { 'Fn::GetAtt': ['PipelineArtifactsBucket22248F97', 'Arn'] }, { 'Fn::Join': ['', [ { 'Fn::GetAtt': ['PipelineArtifactsBucket22248F97', 'Arn'] }, '/*', ]], }, ], }, { 'Action': [ 'kms:Decrypt', 'kms:DescribeKey', ], 'Effect': 'Allow', 'Resource': { 'Fn::GetAtt': ['PipelineArtifactsBucketEncryptionKey01D58D69', 'Arn'] }, }, ], }, 'Roles': [{ 'Ref': 'PipelineDeployStackSetUpdateCodePipelineActionRole3EDBB32C' }], }); }); }); test('creates correct resources in organizations mode', () => { stack.deployStage.addAction(new cpactions.CloudFormationDeployStackSetAction({ ...defaultOpts(), deploymentModel: cpactions.StackSetDeploymentModel.organizations(), stackInstances: cpactions.StackInstances.fromArtifactPath( stack.sourceOutput.atPath('accounts.json'), ['us-east-1', 'us-west-1', 'ca-central-1'], ), })); const template = Template.fromStack(stack); template.hasResourceProperties('AWS::IAM::Policy', { 'PolicyDocument': { 'Statement': Match.arrayWith([ { 'Action': [ 'cloudformation:CreateStackInstances', 'cloudformation:CreateStackSet', 'cloudformation:DescribeStackSet', 'cloudformation:DescribeStackSetOperation', 'cloudformation:ListStackInstances', 'cloudformation:UpdateStackSet', ], 'Effect': 'Allow', 'Resource': { 'Fn::Join': [ '', [ 'arn:', { 'Ref': 'AWS::Partition' }, ':cloudformation:us-east-1:111111111111:stackset/MyStack:*', ], ], }, }, ]), }, 'Roles': [ { 'Ref': 'PipelineDeployStackSetUpdateCodePipelineActionRole3EDBB32C' }, ], }); }); test('creates correct pipeline resource with target list', () => { stack.deployStage.addAction(new cpactions.CloudFormationDeployStackSetAction({ ...defaultOpts(), stackInstances: cpactions.StackInstances.inAccounts( ['11111111111', '22222222222'], ['us-east-1', 'us-west-1', 'ca-central-1'], ), deploymentModel: cpactions.StackSetDeploymentModel.selfManaged({ administrationRole: importedAdminRole, executionRoleName: 'Exec', }), })); const template = Template.fromStack(stack); template.hasResourceProperties('AWS::CodePipeline::Pipeline', { 'Stages': [ { 'Name': 'Source' /* don't care about the rest */ }, { 'Name': 'Deploy', 'Actions': [ { 'Configuration': { 'StackSetName': 'MyStack', 'Description': 'desc', 'TemplatePath': 'SourceArtifact::template.yaml', 'Parameters': 'SourceArtifact::parameters.json', 'Capabilities': 'CAPABILITY_NAMED_IAM', 'DeploymentTargets': '11111111111,22222222222', 'FailureTolerancePercentage': 50, 'MaxConcurrentPercentage': 25, 'Regions': 'us-east-1,us-west-1,ca-central-1', }, 'InputArtifacts': [{ 'Name': 'SourceArtifact' }], 'Name': 'StackSetUpdate', }, ], }, ], }); }); test('creates correct pipeline resource with parameter list', () => { stack.deployStage.addAction(new cpactions.CloudFormationDeployStackSetAction({ ...defaultOpts(), parameters: cpactions.StackSetParameters.fromLiteral({ key0: 'val0', key1: 'val1', }, ['key2', 'key3']), stackInstances: cpactions.StackInstances.fromArtifactPath( stack.sourceOutput.atPath('accounts.json'), ['us-east-1', 'us-west-1', 'ca-central-1'], ), deploymentModel: cpactions.StackSetDeploymentModel.selfManaged({ administrationRole: importedAdminRole, executionRoleName: 'Exec', }), })); const template = Template.fromStack(stack); template.hasResourceProperties('AWS::CodePipeline::Pipeline', { 'Stages': [ { 'Name': 'Source' /* don't care about the rest */ }, { 'Name': 'Deploy', 'Actions': [ { 'Configuration': { 'StackSetName': 'MyStack', 'Description': 'desc', 'TemplatePath': 'SourceArtifact::template.yaml', 'Parameters': 'ParameterKey=key0,ParameterValue=val0 ParameterKey=key1,ParameterValue=val1 ParameterKey=key2,UsePreviousValue=true ParameterKey=key3,UsePreviousValue=true', 'Capabilities': 'CAPABILITY_NAMED_IAM', 'DeploymentTargets': 'SourceArtifact::accounts.json', 'FailureTolerancePercentage': 50, 'MaxConcurrentPercentage': 25, 'Regions': 'us-east-1,us-west-1,ca-central-1', }, 'InputArtifacts': [{ 'Name': 'SourceArtifact' }], 'Name': 'StackSetUpdate', }, ], }, ], }); }); test('correctly passes region', () => { stack.deployStage.addAction(new cpactions.CloudFormationDeployStackSetAction({ ...defaultOpts(), stackSetRegion: 'us-banana-2', })); const template = Template.fromStack(stack); template.hasResourceProperties('AWS::CodePipeline::Pipeline', { 'Stages': [ { 'Name': 'Source' /* don't care about the rest */ }, { 'Name': 'Deploy', 'Actions': [ { 'Region': 'us-banana-2', }, ], }, ], }); }); }); describe('StackInstancesAction', () => { function defaultOpts() { return { actionName: 'StackInstances', stackSetName: 'MyStack', failureTolerancePercentage: 50, maxAccountConcurrencyPercentage: 25, }; }; test('simple', () => { stack.deployStage.addAction(new cpactions.CloudFormationDeployStackInstancesAction({ ...defaultOpts(), stackInstances: cpactions.StackInstances.inAccounts( ['1234', '5678'], ['us-east-1', 'us-west-1'], ), })); const template = Template.fromStack(stack); template.hasResourceProperties('AWS::CodePipeline::Pipeline', { 'Stages': [ { 'Name': 'Source' /* don't care about the rest */ }, { 'Name': 'Deploy', 'Actions': [ { 'ActionTypeId': { 'Category': 'Deploy', 'Owner': 'AWS', 'Provider': 'CloudFormationStackInstances', 'Version': '1', }, 'Configuration': { 'StackSetName': 'MyStack', 'FailureTolerancePercentage': 50, 'MaxConcurrentPercentage': 25, 'DeploymentTargets': '1234,5678', 'Regions': 'us-east-1,us-west-1', }, 'Name': 'StackInstances', }, ], }, ], }); }); test('correctly passes region', () => { stack.deployStage.addAction(new cpactions.CloudFormationDeployStackInstancesAction({ ...defaultOpts(), stackSetRegion: 'us-banana-2', stackInstances: cpactions.StackInstances.inAccounts(['1'], ['us-east-1']), })); const template = Template.fromStack(stack); template.hasResourceProperties('AWS::CodePipeline::Pipeline', { 'Stages': [ { 'Name': 'Source' /* don't care about the rest */ }, { 'Name': 'Deploy', 'Actions': [ { 'Region': 'us-banana-2', }, ], }, ], }); }); });
the_stack
import { AsyncHierarchyIterable } from '@esfx/async-iter-hierarchy'; import { HashMap } from "@esfx/collections-hashmap"; import { HashSet } from "@esfx/collections-hashset"; import { Equaler } from "@esfx/equatable"; import { identity, isDefined } from '@esfx/fn'; import * as assert from "@esfx/internal-assert"; import { isPrimitive } from "@esfx/internal-guards"; import { HierarchyIterable } from '@esfx/iter-hierarchy'; import { flowHierarchy } from './internal/utils'; import { toArrayAsync, toHashSetAsync } from './scalars'; class AsyncAppendIterable<T> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _value: PromiseLike<T> | T; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, value: PromiseLike<T> | T) { this._source = source; this._value = value; } async *[Symbol.asyncIterator](): AsyncIterator<T> { yield* this._source; yield this._value; } } /** * Creates an `AsyncIterable` for the elements of `source` with the provided `value` appended to the * end. * * @param source The `AsyncIterable` or `Iterable` object to append to. * @param value The value to append. * @category Subquery */ export function appendAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, value: PromiseLike<T> | T): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the elements of `source` with the provided `value` appended to the * end. * * @param source The `AsyncIterable` or `Iterable` object to append to. * @param value The value to append. * @category Subquery */ export function appendAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, value: PromiseLike<T> | T): AsyncIterable<T>; export function appendAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, value: PromiseLike<T> | T): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); return flowHierarchy(new AsyncAppendIterable(source, value), source); } class AsyncPrependIterable<T> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _value: PromiseLike<T> | T; constructor(value: PromiseLike<T> | T, source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>) { this._value = value; this._source = source; } async *[Symbol.asyncIterator](): AsyncIterator<T> { yield this._value; yield* this._source; } } /** * Creates an `AsyncIterable` for the elements of `source` with the provided `value` prepended to the * beginning. * * @param source An `AsyncIterable` or `Iterable` object value. * @param value The value to prepend. * @category Subquery */ export function prependAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, value: T): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the elements of `source` with the provided `value` prepended to the * beginning. * * @param source An `AsyncIterable` or `Iterable` object value. * @param value The value to prepend. * @category Subquery */ export function prependAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, value: PromiseLike<T> | T): AsyncIterable<T>; export function prependAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, value: PromiseLike<T> | T): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); return flowHierarchy(new AsyncPrependIterable(value, source), source); } class AsyncConcatIterable<T> implements AsyncIterable<T> { private _left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; constructor(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>) { this._left = left; this._right = right; } async *[Symbol.asyncIterator](): AsyncIterator<T> { yield* this._left; yield* this._right; } } /** * Creates an `AsyncIterable` that concatenates a `AsyncIterable` or `Iterable` * object with an `AsyncIterable` or `Iterable` object. * * @param left A `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @category Subquery */ export function concatAsync<TNode, T extends TNode>(left: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` that concatenates an `AsyncIterable` or `Iterable` object with * a `AsyncIterable` or `Iterable` object. * * @param left An `AsyncIterable` or `Iterable` object. * @param right A `AsyncIterable` or `Iterable` object. * @category Subquery */ export function concatAsync<TNode, T extends TNode>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` that concatenates two `AsyncIterable` or `Iterable` objects. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @category Subquery */ export function concatAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncIterable<T>; export function concatAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); return flowHierarchy(new AsyncConcatIterable(left, right), left, right); } class AsyncFilterByIterable<T, K> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _keySelector: (element: T) => K; private _predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean; private _invert: boolean; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean, invert: boolean) { this._source = source; this._keySelector = keySelector; this._predicate = predicate; this._invert = invert; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const keySelector = this._keySelector; const predicate = this._predicate; const inverted = this._invert; let offset = 0; for await (const element of this._source) { let result = predicate(keySelector(element), offset++); if (!isPrimitive(result)) result = await result; if (inverted) result = !result; if (result) { yield element; } } } } /** * Creates an `AsyncIterable` where the selected key for each element matches the supplied predicate. * * @param source A `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param predicate A callback used to match each key. * @category Subquery */ export function filterByAsync<TNode, T extends TNode, K>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` where the selected key for each element matches the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param predicate A callback used to match each key. * @category Subquery */ export function filterByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean): AsyncIterable<T>; export function filterByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeFunction(predicate, "predicate"); return flowHierarchy(new AsyncFilterByIterable(source, keySelector, predicate, /*invert*/ false), source); } export { filterByAsync as whereByAsync }; export { filterAsync as whereAsync }; export { filterDefinedAsync as whereDefinedAsync }; export { filterDefinedByAsync as whereDefinedByAsync }; export { filterNotByAsync as whereNotByAsync }; export { filterNotAsync as whereNotAsync }; export { filterNotDefinedByAsync as whereNotDefinedByAsync }; export { mapAsync as selectAsync }; export { flatMapAsync as selectManyAsync }; export { dropAsync as skipAsync }; export { dropRightAsync as skipRightAsync }; export { dropWhileAsync as skipWhileAsync }; export { dropUntilAsync as skipUntilAsync, dropUntilAsync as dropWhileNotAsync, dropUntilAsync as skipWhileNotAsync }; export { exceptByAsync as relativeComplementByAsync }; export { exceptAsync as relativeComplementAsync }; /** * Creates an `AsyncIterable` whose elements match the supplied predicate. * * @param source A `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function filterAsync<TNode, T extends TNode, U extends T>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T, offset: number) => element is U): AsyncHierarchyIterable<TNode, U>; /** * Creates an `AsyncIterable` whose elements match the supplied predicate. * * @param source A `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function filterAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` whose elements match the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function filterAsync<T, U extends T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T, offset: number) => element is U): AsyncIterable<U>; /** * Creates an `AsyncIterable` whose elements match the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function filterAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncIterable<T>; export function filterAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return filterByAsync(source, identity, predicate); } /** * Creates an `AsyncIterable` whose elements are neither `null` nor `undefined`. * * @param source A `AsyncIterable` or `Iterable` object. * @category Subquery */ export function filterDefinedAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>): AsyncHierarchyIterable<TNode, NonNullable<T>>; /** * Creates an `AsyncIterable` whose elements are neither `null` nor `undefined`. * * @param source An `AsyncIterable` or `Iterable` object. * @category Subquery */ export function filterDefinedAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncIterable<NonNullable<T>>; export function filterDefinedAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>) { return filterByAsync(source, identity, isDefined); } /** * Creates an `AsyncIterable` where the selected key for each element is neither `null` nor `undefined`. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @category Subquery */ export function filterDefinedByAsync<TNode, T extends TNode, K>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (value: T) => K): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` where the selected key for each element is neither `null` nor `undefined`. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @category Subquery */ export function filterDefinedByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (value: T) => K): AsyncIterable<T>; export function filterDefinedByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (value: T) => K) { return filterByAsync(source, keySelector, isDefined); } /** * Creates an `AsyncIterable` where the selected key for each element does not match the supplied predicate. * * @param source A `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param predicate A callback used to match each key. * @category Subquery */ export function filterNotByAsync<TNode, T extends TNode, K>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` where the selected key for each element does not match the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param predicate A callback used to match each key. * @category Subquery */ export function filterNotByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean): AsyncIterable<T>; export function filterNotByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeFunction(predicate, "predicate"); return flowHierarchy(new AsyncFilterByIterable(source, keySelector, predicate, /*invert*/ false), source); } /** * Creates an `AsyncIterable` whose elements do not match the supplied predicate. * * @param source A `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function filterNotAsync<TNode, T extends TNode, U extends T>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T, offset: number) => element is U): AsyncHierarchyIterable<TNode, U>; /** * Creates an `AsyncIterable` whose elements do not match the supplied predicate. * * @param source A `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function filterNotAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` whose elements do not match the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function filterNotAsync<T, U extends T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T, offset: number) => element is U): AsyncIterable<U>; /** * Creates an `AsyncIterable` whose elements do not match the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function filterNotAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncIterable<T>; export function filterNotAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return filterNotByAsync(source, identity, predicate); } /** * Creates an `AsyncIterable` where the selected key for each element is either `null` or `undefined`. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @category Subquery */ export function filterNotDefinedByAsync<TNode, T extends TNode, K>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (value: T) => K): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` where the selected key for each element is either `null` or `undefined`. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @category Subquery */ export function filterNotDefinedByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (value: T) => K): AsyncIterable<T>; export function filterNotDefinedByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (value: T) => K) { return filterNotByAsync(source, keySelector, isDefined); } class AsyncMapIterable<T, U> implements AsyncIterable<U> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _selector: (element: T, offset: number) => PromiseLike<U> | U; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, selector: (element: T, offset: number) => PromiseLike<U> | U) { this._source = source; this._selector = selector; } async *[Symbol.asyncIterator](): AsyncIterator<U> { const selector = this._selector; let offset = 0; for await (const element of this._source) { yield selector(element, offset++); } } } /** * Creates an `AsyncIterable` by applying a callback to each element of an `AsyncIterable` or `Iterable` object. * * @param source An `AsyncIterable` or `Iterable` object. * @param selector A callback used to map each element. * @category Subquery */ export function mapAsync<T, U>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, selector: (element: T, offset: number) => PromiseLike<U> | U): AsyncIterable<U> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(selector, "selector"); return new AsyncMapIterable(source, selector); } class AsyncFlatMapIterable<T, U, R> implements AsyncIterable<U | R> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _projection: (element: T) => AsyncIterable<U> | Iterable<PromiseLike<U> | U>; private _resultSelector?: (element: T, innerElement: U) => PromiseLike<R> | R; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, projection: (element: T) => AsyncIterable<U> | Iterable<PromiseLike<U> | U>, resultSelector?: (element: T, innerElement: U) => PromiseLike<R> | R) { this._source = source; this._projection = projection; this._resultSelector = resultSelector; } async *[Symbol.asyncIterator](): AsyncIterator<U | R> { const projection = this._projection; const resultSelector = this._resultSelector; for await (const element of this._source) { const inner = projection(element); if (resultSelector) { for await (const innerElement of inner) { yield resultSelector(element, innerElement); } } else { yield* inner; } } } } /** * Creates an `AsyncIterable` that iterates the results of applying a callback to each element of `source`. * * @param source A [[Queryable]] object. * @param projection A callback used to map each element into an iterable. * @category Subquery */ export function flatMapAsync<T, U>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, projection: (element: T) => AsyncIterable<U> | Iterable<PromiseLike<U> | U>): AsyncIterable<U>; /** * Creates an `AsyncIterable` that iterates the results of applying a callback to each element of `source`. * * @param source A [[Queryable]] object. * @param projection A callback used to map each element into an iterable. * @category Subquery */ export function flatMapAsync<T, U, R>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, projection: (element: T) => AsyncIterable<U> | Iterable<PromiseLike<U> | U>, resultSelector: (element: T, innerElement: U) => PromiseLike<R> | R): AsyncIterable<R>; export function flatMapAsync<T, U, R>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, projection: (element: T) => AsyncIterable<U> | Iterable<PromiseLike<U> | U>, resultSelector?: (element: T, innerElement: U) => PromiseLike<R> | R): AsyncIterable<U | R> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(projection, "projection"); return new AsyncFlatMapIterable(source, projection, resultSelector); } class AsyncDropIterable<T> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _count: number; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, count: number) { this._source = source; this._count = count; } async *[Symbol.asyncIterator](): AsyncIterator<T> { let remaining = this._count; if (remaining <= 0) { yield* this._source; } else { for await (const element of this._source) { if (remaining > 0) { remaining--; } else { yield element; } } } } } /** * Creates an `AsyncIterable` containing all elements except the first elements up to the supplied * count. * * @param source An `AsyncIterable` or `Iterable` object. * @param count The number of elements to skip. * @category Subquery */ export function dropAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, count: number): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` containing all elements except the first elements up to the supplied * count. * * @param source An `AsyncIterable` or `Iterable` object. * @param count The number of elements to skip. * @category Subquery */ export function dropAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, count: number): AsyncIterable<T>; export function dropAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, count: number): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBePositiveFiniteNumber(count, "count"); return flowHierarchy(new AsyncDropIterable(source, count), source); } class AsyncDropRightIterable<T> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _count: number; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, count: number) { this._source = source; this._count = count; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const pending: T[] = []; const count = this._count; if (count <= 0) { yield* this._source; } else { for await (const element of this._source) { pending.push(element); if (pending.length > count) { yield pending.shift()!; } } } } } /** * Creates an `AsyncIterable` containing all elements except the first elements up to the supplied * count. * * @param source An `AsyncIterable` or `Iterable` object. * @param count The number of elements to skip. * @category Subquery */ export function dropRightAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, count: number): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` containing all elements except the first elements up to the supplied * count. * * @param source An `AsyncIterable` or `Iterable` object. * @param count The number of elements to skip. * @category Subquery */ export function dropRightAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, count: number): AsyncIterable<T>; export function dropRightAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, count: number): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBePositiveFiniteNumber(count, "count"); return flowHierarchy(new AsyncDropRightIterable(source, count), source); } class AsyncDropWhileIterable<T> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _predicate: (element: T) => PromiseLike<boolean> | boolean; private _invert: boolean; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean, invert: boolean) { this._source = source; this._predicate = predicate; this._invert = invert; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const predicate = this._predicate; const inverted = this._invert; let skipping = true; for await (const element of this._source) { if (skipping) { let result = predicate(element); if (!isPrimitive(result)) result = await result; if (inverted) result = !result; skipping = !!result; } if (!skipping) { yield element; } } } } /** * Creates an `AsyncIterable` containing all elements except the first elements that match * the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function dropWhileAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` containing all elements except the first elements that match * the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function dropWhileAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncIterable<T>; export function dropWhileAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return flowHierarchy(new AsyncDropWhileIterable(source, predicate, /*invert*/ false), source); } /** * Creates an `AsyncIterable` containing all elements except the first elements that do not match * the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function dropUntilAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` containing all elements except the first elements that do not match * the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function dropUntilAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncIterable<T>; export function dropUntilAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return flowHierarchy(new AsyncDropWhileIterable(source, predicate, /*invert*/ true), source); } class AsyncTakeIterable<T> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _count: number; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, count: number) { this._source = source; this._count = count; } async *[Symbol.asyncIterator](): AsyncIterator<T> { let remaining = this._count; if (remaining > 0) { for await (const element of this._source) { yield element; if (--remaining <= 0) { break; } } } } } /** * Creates an `AsyncIterable` containing the first elements up to the supplied count. * * @param source An `AsyncIterable` or `Iterable` object. * @param count The number of elements to take. * @category Subquery */ export function takeAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, count: number): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` containing the first elements up to the supplied count. * * @param source An `AsyncIterable` or `Iterable` object. * @param count The number of elements to take. * @category Subquery */ export function takeAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, count: number): AsyncIterable<T>; export function takeAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, count: number): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBePositiveFiniteNumber(count, "count"); return flowHierarchy(new AsyncTakeIterable(source, count), source); } class AsyncTakeRightIterable<T> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _count: number; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, count: number) { this._source = source; this._count = count; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const count = this._count; if (count <= 0) { return; } else { const pending: T[] = []; for await (const element of this._source) { pending.push(element); if (pending.length > count) { pending.shift(); } } yield* pending; } } } /** * Creates an `AsyncIterable` containing the last elements up to the supplied * count. * * @param source An `AsyncIterable` or `Iterable` object. * @param count The number of elements to take. * @category Subquery */ export function takeRightAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, count: number): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` containing the last elements up to the supplied * count. * * @param source An `AsyncIterable` or `Iterable` object. * @param count The number of elements to take. * @category Subquery */ export function takeRightAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, count: number): AsyncIterable<T>; export function takeRightAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, count: number): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBePositiveFiniteNumber(count, "count"); return flowHierarchy(new AsyncTakeRightIterable(source, count), source); } class AsyncTakeWhileIterable<T> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _predicate: (element: T) => PromiseLike<boolean> | boolean; private _invert: boolean; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean, invert: boolean) { this._source = source; this._predicate = predicate; this._invert = invert; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const predicate = this._predicate; const inverted = this._invert; for await (const element of this._source) { let result = predicate(element); if (!isPrimitive(result)) result = await result; if (inverted) result = !result; if (!result) { break; } yield element; } } } /** * Creates an `AsyncIterable` containing the first elements that match the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function takeWhileAsync<TNode, T extends TNode, U extends T>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T) => element is U): AsyncHierarchyIterable<TNode, U>; /** * Creates an `AsyncIterable` containing the first elements that match the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function takeWhileAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` containing the first elements that match the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function takeWhileAsync<T, U extends T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => element is U): AsyncIterable<U>; /** * Creates an `AsyncIterable` containing the first elements that match the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function takeWhileAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncIterable<T>; export function takeWhileAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return flowHierarchy(new AsyncTakeWhileIterable(source, predicate, /*invert*/ false), source); } /** * Creates an `AsyncIterable` containing the first elements that do not match the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function takeUntilAsync<TNode, T extends TNode, U extends T>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T) => element is U): AsyncHierarchyIterable<TNode, U>; /** * Creates an `AsyncIterable` containing the first elements that do not match the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function takeUntilAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` containing the first elements that do not match the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function takeUntilAsync<T, U extends T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => element is U): AsyncIterable<U>; /** * Creates an `AsyncIterable` containing the first elements that do not match the supplied predicate. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Subquery */ export function takeUntilAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncIterable<T>; export function takeUntilAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return flowHierarchy(new AsyncTakeWhileIterable(source, predicate, /*invert*/ true), source); } class AsyncIntersectByIterable<T, K> implements AsyncIterable<T> { private _left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _keySelector: (element: T) => K; private _keyEqualer?: Equaler<K>; constructor(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>) { this._left = left; this._right = right; this._keySelector = keySelector; this._keyEqualer = keyEqualer; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const keySelector = this._keySelector; const set = await toHashSetAsync(this._right, keySelector, this._keyEqualer); if (set.size <= 0) { return; } for await (const element of this._left) { if (set.delete(keySelector(element))) { yield element; } } } } /** * Creates an `AsyncIterable` for the set intersection of a `AsyncIterable` or `Iterable` object and another `AsyncIterable` or `Iterable` object, where set identity is determined by the selected key. * * @param left A `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function intersectByAsync<TNode, T extends TNode, K>(left: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the set intersection of two `AsyncIterable` or `Iterable` objects, where set identity is determined by the selected key. * * @param left An `AsyncIterable` or `Iterable` object. * @param right A `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function intersectByAsync<TNode, T extends TNode, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the set intersection of two `AsyncIterable` or `Iterable` objects, where set identity is determined by the selected key. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function intersectByAsync<T, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<T>; export function intersectByAsync<T, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return flowHierarchy(new AsyncIntersectByIterable(left, right, keySelector), left, right); } /** * Creates an `AsyncIterable` for the set intersection of a `AsyncIterable` or `Iterable` object and another `AsyncIterable` or `Iterable` object. * * @param left A `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ export function intersectAsync<TNode, T extends TNode>(left: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the set intersection of two `AsyncIterable` or `Iterable` objects. * * @param left An `AsyncIterable` or `Iterable` object. * @param right A `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ export function intersectAsync<TNode, T extends TNode>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, equaler?: Equaler<T>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the set intersection of two `AsyncIterable` or `Iterable` objects. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ export function intersectAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncIterable<T>; export function intersectAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, equaler, "equaler"); return intersectByAsync(left, right, identity, equaler); } class AsyncUnionByIterable<T, K> implements AsyncIterable<T> { private _left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _keySelector: (element: T) => K; private _keyEqualer?: Equaler<K>; constructor(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>) { this._left = left; this._right = right; this._keySelector = keySelector; this._keyEqualer = keyEqualer; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const keySelector = this._keySelector; const set = new HashSet(this._keyEqualer); for await (const element of this._left) { if (set.tryAdd(keySelector(element))) { yield element; } } for await (const element of this._right) { if (set.tryAdd(keySelector(element))) { yield element; } } } } /** * Creates an `AsyncIterable` for the set union of two `AsyncIterable` or `Iterable` objects, where set identity is determined by the selected key. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function unionByAsync<TNode, T extends TNode, K>(left: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the set union of two `AsyncIterable` or `Iterable` objects, where set identity is determined by the selected key. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function unionByAsync<TNode, T extends TNode, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the set union of two `AsyncIterable` or `Iterable` objects, where set identity is determined by the selected key. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function unionByAsync<T, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<T>; export function unionByAsync<T, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return flowHierarchy(new AsyncUnionByIterable(left, right, keySelector, keyEqualer), left, right); } /** * Creates an `AsyncIterable` for the set union of two `AsyncIterable` or `Iterable` objects. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ export function unionAsync<TNode, T extends TNode>(left: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the set union of two `AsyncIterable` or `Iterable` objects. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ export function unionAsync<TNode, T extends TNode>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, equaler?: Equaler<T>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the set union of two `AsyncIterable` or `Iterable` objects. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ export function unionAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncIterable<T>; export function unionAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, equaler, "equaler"); return unionByAsync(left, right, identity, equaler); } class AsyncExceptByIterable<T, K> implements AsyncIterable<T> { private _left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _keySelector: (element: T) => K; private _keyEqualer?: Equaler<K>; constructor(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>) { this._left = left; this._right = right; this._keySelector = keySelector; this._keyEqualer = keyEqualer; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const keySelector = this._keySelector; const set = await toHashSetAsync(this._right, keySelector, this._keyEqualer!); for await (const element of this._left) { if (set.tryAdd(keySelector(element))) { yield element; } } } } /** * Creates an `AsyncIterable` for the set difference between two `AsyncIterable` or `Iterable` objects, where set identity is determined by the selected key. * * @param left A `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function exceptByAsync<TNode, T extends TNode, K>(left: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the set difference between two `AsyncIterable` or `Iterable` objects, where set identity is determined by the selected key. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function exceptByAsync<T, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<T>; export function exceptByAsync<T, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return flowHierarchy(new AsyncExceptByIterable(left, right, keySelector, keyEqualer), left); } /** * Creates an `AsyncIterable` for the set difference between two `AsyncIterable` or `Iterable` objects. * * @param left A `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ export function exceptAsync<TNode, T extends TNode>(left: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the set difference between two `AsyncIterable` or `Iterable` objects. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ export function exceptAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncIterable<T>; export function exceptAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, equaler, "equaler"); return exceptByAsync(left, right, identity, equaler); } /** * Creates an `AsyncIterable` with every instance of the specified value removed. * * @param source A `AsyncIterable` or `Iterable` object. * @param values The values to exclude. * @category Subquery */ export function excludeAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, ...values: [PromiseLike<T> | T, ...(PromiseLike<T> | T)[]]): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` with every instance of the specified value removed. * * @param source An `AsyncIterable` or `Iterable` object. * @param values The values to exclude. * @category Subquery */ export function excludeAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, ...values: [PromiseLike<T> | T, ...(PromiseLike<T> | T)[]]): AsyncIterable<T>; export function excludeAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, ...values: [PromiseLike<T> | T, ...(PromiseLike<T> | T)[]]): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "left"); return exceptByAsync(source, values, identity); } class AsyncDistinctByIterable<T, K> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _keySelector: (value: T) => K; private _keyEqualer?: Equaler<K>; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (value: T) => K, keyEqualer?: Equaler<K>) { this._source = source; this._keySelector = keySelector; this._keyEqualer = keyEqualer; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const set = new HashSet<K>(this._keyEqualer); const selector = this._keySelector; for await (const element of this._source) { const key = selector(element); if (set.tryAdd(key)) { yield element; } } } } /** * Creates an `AsyncIterable` for the distinct elements of `source`. * * @param source A `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key to determine uniqueness. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function distinctByAsync<TNode, T extends TNode, K>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (value: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the distinct elements of `source`. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key to determine uniqueness. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function distinctByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (value: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<T>; export function distinctByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (value: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return flowHierarchy(new AsyncDistinctByIterable(source, keySelector, keyEqualer), source); } /** * Creates an `AsyncIterable` for the distinct elements of `source`. * * @param source A `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare element equality. * @category Subquery */ export function distinctAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, equaler?: Equaler<T>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the distinct elements of source. * * @param source An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare element equality. * @category Subquery */ export function distinctAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncIterable<T>; export function distinctAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, equaler, "equaler"); return distinctByAsync(source, identity, equaler); } class AsyncDefaultIfEmptyIterable<T> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _defaultValue: PromiseLike<T> | T; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, defaultValue: PromiseLike<T> | T) { this._source = source; this._defaultValue = defaultValue; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const source = this._source; const defaultValue = this._defaultValue; let hasElements = false; for await (const value of source) { hasElements = true; yield value; } if (!hasElements) { yield defaultValue; } } } /** * Creates an `AsyncIterable` that contains the provided default value if `source` * contains no elements. * * @param source A `AsyncIterable` or `Iterable` object. * @param defaultValue The default value. * @category Subquery */ export function defaultIfEmptyAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, defaultValue: PromiseLike<T> | T): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` that contains the provided default value if `source` * contains no elements. * * @param source An `AsyncIterable` or `Iterable` object. * @param defaultValue The default value. * @category Subquery */ export function defaultIfEmptyAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, defaultValue: PromiseLike<T> | T): AsyncIterable<T>; export function defaultIfEmptyAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, defaultValue: PromiseLike<T> | T): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); return flowHierarchy(new AsyncDefaultIfEmptyIterable(source, defaultValue), source); } class AsyncPatchIterable<T> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _start: number; private _skipCount: number; private _range: AsyncIterable<T> | Iterable<PromiseLike<T> | T> | undefined; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, start: number, skipCount: number, range: AsyncIterable<T> | Iterable<PromiseLike<T> | T> | undefined) { this._source = source; this._start = start; this._skipCount = skipCount; this._range = range; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const start = this._start; const skipCount = this._skipCount; let offset = 0; let hasYieldedRange = false; for await (const value of this._source) { if (offset < start) { yield value; offset++; } else if (offset < start + skipCount) { offset++; } else { if (!hasYieldedRange && this._range) { yield* this._range; hasYieldedRange = true; } yield value; } } if (!hasYieldedRange && this._range) { yield* this._range; } } } /** * Creates an `AsyncIterable` for the elements of the source with the provided range * patched into the results. * * @param source A `AsyncIterable` or `Iterable` object to patch. * @param start The offset at which to patch the range. * @param skipCount The number of elements to skip from start. * @param range The range to patch into the result. * @category Subquery */ export function patchAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, start: number, skipCount?: number, range?: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the elements of the source with the provided range * patched into the results. * * @param source An `AsyncIterable` or `Iterable` object to patch. * @param start The offset at which to patch the range. * @param skipCount The number of elements to skip from start. * @param range The range to patch into the result. * @category Subquery */ export function patchAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, start: number, skipCount?: number, range?: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncIterable<T>; export function patchAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, start: number, skipCount: number = 0, range?: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBePositiveFiniteNumber(start, "start"); assert.mustBePositiveFiniteNumber(skipCount, "skipCount"); assert.mustBeAsyncOrSyncIterableObjectOrUndefined(range, "range"); return flowHierarchy(new AsyncPatchIterable(source, start, skipCount, range), source); } class AsyncScanIterable<T, U> implements AsyncIterable<T | U> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _accumulator: (current: T | U, element: T, offset: number) => PromiseLike<T | U> | T | U; private _isSeeded: boolean; private _seed: T | U | undefined; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: T | U, element: T, offset: number) => PromiseLike<T | U> | T | U, isSeeded: boolean, seed: T | U | undefined) { this._source = source; this._accumulator = accumulator; this._isSeeded = isSeeded; this._seed = seed; } async *[Symbol.asyncIterator](): AsyncIterator<T | U> { const accumulator = this._accumulator; let hasCurrent = this._isSeeded; let current = this._seed; let offset = 0; for await (const value of this._source) { if (!hasCurrent) { current = value; hasCurrent = true; } else { current = await accumulator(current!, value, offset); yield current; } offset++; } } } /** * Creates an `AsyncIterable` containing the cumulative results of applying the provided callback to each element. * * @param source An `AsyncIterable` or `Iterable` object. * @param accumulator The callback used to compute each result. * @category Subquery */ export function scanAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T): AsyncIterable<T>; /** * Creates an `AsyncIterable` containing the cumulative results of applying the provided callback to each element. * * @param source An `AsyncIterable` or `Iterable` object. * @param accumulator The callback used to compute each result. * @param seed An optional seed value. * @category Subquery */ export function scanAsync<T, U>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: U, element: T, offset: number) => PromiseLike<U> | U, seed: U): AsyncIterable<U>; export function scanAsync<T, U>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: T | U, element: T, offset: number) => PromiseLike<T | U> | T | U, seed?: T | U): AsyncIterable<T | U> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(accumulator, "accumulator"); return new AsyncScanIterable<T, U>(source, accumulator, arguments.length > 2, seed!); } class AsyncScanRightIterable<T, U> implements AsyncIterable<T | U> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _accumulator: (current: T | U, element: T, offset: number) => PromiseLike<T | U> | T | U; private _isSeeded: boolean; private _seed: T | U | undefined; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: T | U, element: T, offset: number) => PromiseLike<T | U> | T | U, isSeeded: boolean, seed: T | U | undefined) { this._source = source; this._accumulator = accumulator; this._isSeeded = isSeeded; this._seed = seed; } async *[Symbol.asyncIterator](): AsyncIterator<T | U> { const source = await toArrayAsync(this._source); const accumulator = this._accumulator; let hasCurrent = this._isSeeded; let current = this._seed; for (let offset = source.length - 1; offset >= 0; offset--) { const value = source[offset]; if (!hasCurrent) { current = value; hasCurrent = true; continue; } current = await accumulator(current!, value, offset); yield current; } } } /** * Creates an `AsyncIterable` containing the cumulative results of applying the provided callback to each element in reverse. * * @param source An `AsyncIterable` or `Iterable` object. * @param accumulator The callback used to compute each result. * @category Subquery */ export function scanRightAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T): AsyncIterable<T>; /** * Creates an `AsyncIterable` containing the cumulative results of applying the provided callback to each element in reverse. * * @param source An `AsyncIterable` or `Iterable` object. * @param accumulator The callback used to compute each result. * @param seed An optional seed value. * @category Subquery */ export function scanRightAsync<T, U>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: U, element: T, offset: number) => PromiseLike<U> | U, seed: U): AsyncIterable<U>; export function scanRightAsync<T, U>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: T | U, element: T, offset: number) => PromiseLike<T | U> | T | U, seed?: T | U): AsyncIterable<T | U> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(accumulator, "accumulator"); return new AsyncScanRightIterable<T, U>(source, accumulator, arguments.length > 2, seed); } class AsyncSymmetricDifferenceByIterable<T, K> implements AsyncIterable<T> { private _left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _keySelector: (element: T) => K; private _keyEqualer?: Equaler<K>; constructor(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>) { this._left = left; this._right = right; this._keySelector = keySelector; this._keyEqualer = keyEqualer; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const keySelector = this._keySelector; const rightKeys = new HashSet<K>(this._keyEqualer); const right = new HashMap<K, T>(this._keyEqualer); for await (const element of this._right) { const key = keySelector(element); if (rightKeys.tryAdd(key)) { right.set(key, element); } } const set = new HashSet<K>(this._keyEqualer); for await (const element of this._left) { const key = keySelector(element); if (set.tryAdd(key) && !right.has(key)) { yield element; } } for (const [key, element] of right) { if (set.tryAdd(key)) { yield element; } } } } /** * Creates an `AsyncIterable` for the symmetric difference between two `AsyncIterable` or `Iterable` objects, where set identity is determined by the selected key. * The result is an `AsyncIterable` containings the elements that exist in only left or right, but not * in both. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function symmetricDifferenceByAsync<TNode, T extends TNode, K>(left: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the symmetric difference between two `AsyncIterable` or `Iterable` objects, where set identity is determined by the selected key. * The result is an `AsyncIterable` containings the elements that exist in only left or right, but not * in both. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function symmetricDifferenceByAsync<TNode, T extends TNode, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the symmetric difference between two `AsyncIterable` or `Iterable` objects, where set identity is determined by the selected key. * The result is an `AsyncIterable` containings the elements that exist in only left or right, but not * in both. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function symmetricDifferenceByAsync<T, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<T>; export function symmetricDifferenceByAsync<T, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return flowHierarchy(new AsyncSymmetricDifferenceByIterable(left, right, keySelector), left, right); } /** * Creates an `AsyncIterable` for the symmetric difference between two [[Queryable]] objects. * The result is an `AsyncIterable` containings the elements that exist in only left or right, but not * in both. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ export function symmetricDifferenceAsync<TNode, T extends TNode>(left: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the symmetric difference between two [[Queryable]] objects. * The result is an `AsyncIterable` containings the elements that exist in only left or right, but not * in both. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ export function symmetricDifferenceAsync<TNode, T extends TNode>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, equaler?: Equaler<T>): AsyncHierarchyIterable<TNode, T>; /** * Creates an `AsyncIterable` for the symmetric difference between two [[Queryable]] objects. * The result is an `AsyncIterable` containings the elements that exist in only left or right, but not * in both. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ export function symmetricDifferenceAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncIterable<T>; export function symmetricDifferenceAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, equaler, "equaler"); return symmetricDifferenceByAsync(left, right, identity, equaler); } class AsyncTapIterable<T> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _callback: (element: T, offset: number) => PromiseLike<void> | void; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, callback: (element: T, offset: number) => PromiseLike<void> | void) { this._source = source; this._callback = callback; } async *[Symbol.asyncIterator](): AsyncIterator<T> { const source = this._source; const callback = this._callback; let offset = 0; for await (const element of source) { const result = callback(element, offset++); if (result !== undefined) await result; yield element; } } } /** * Lazily invokes a callback as each element of the iterable is iterated. * * @param source An `AsyncIterable` or `Iterable` object. * @param callback The callback to invoke. * @category Subquery */ export function tapAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, callback: (element: T, offset: number) => PromiseLike<void> | void): AsyncHierarchyIterable<TNode, T>; /** * Lazily invokes a callback as each element of the iterable is iterated. * * @param source An `AsyncIterable` or `Iterable` object. * @param callback The callback to invoke. * @category Subquery */ export function tapAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, callback: (element: T, offset: number) => PromiseLike<void> | void): AsyncIterable<T>; export function tapAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, callback: (element: T, offset: number) => PromiseLike<void> | void): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(callback, "callback"); return flowHierarchy(new AsyncTapIterable(source, callback), source); } class AsyncMaterializeIterable<T> implements AsyncIterable<T> { private _source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>; private _sourceArray?: Promise<readonly T[]>; constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>) { this._source = source; } async *[Symbol.asyncIterator]() { if (!this._sourceArray) { this._sourceArray = toArrayAsync(this._source); } const sourceArray = await this._sourceArray; yield* sourceArray; } } /** * Eagerly evaluate an `AsyncIterable` or `Iterable` object, returning an `AsyncIterable` for the * resolved elements of the original sequence. * * @param source A `AsyncIterable` or `Iterable` object. * @category Scalar */ export function materializeAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>): AsyncHierarchyIterable<TNode, T>; /** * Eagerly evaluate an `AsyncIterable` or `Iterable` object, returning an `AsyncIterable` for the * resolved elements of the original sequence. * * @param source A `AsyncIterable` or `Iterable` object. * @category Scalar */ export function materializeAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncIterable<T>; export function materializeAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncIterable<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); return flowHierarchy(new AsyncMaterializeIterable(source), source); }
the_stack
import * as Clutter from 'clutter'; import * as Gio from 'gio'; import * as GObject from 'gobject'; import { MatPanelButton } from 'src/layout/verticalPanel/panelButton'; import { MsStatusArea } from 'src/layout/verticalPanel/statusArea'; import { WorkspaceList } from 'src/layout/verticalPanel/workspaceList'; import { VerticalPanelPositionEnum } from 'src/manager/msThemeManager'; import { assert } from 'src/utils/assert'; import { registerGObjectClass } from 'src/utils/gjs'; import { MatDivider } from 'src/widget/material/divider'; import * as St from 'st'; import { main as Main, panel } from 'ui'; import { SearchResultList } from './searchResultList'; const Util = imports.misc.util; const SearchController = imports.ui.searchController; /** Extension imports */ const Me = imports.misc.extensionUtils.getCurrentExtension(); @registerGObjectClass export class PanelContent extends St.BoxLayout { static metaInfo: GObject.MetaInfo = { GTypeName: 'PanelContent', Signals: { toggle: { param_types: [], accumulator: 0, }, }, }; topBox: St.BoxLayout; workspaceList: WorkspaceList; statusArea: MsStatusArea; searchButton: MatPanelButton; buttonIcon: St.Icon; constructor() { super({ vertical: true, y_expand: true, }); // Top part this.topBox = new St.BoxLayout({ vertical: true, y_expand: true, }); this.add_child(this.topBox); this.buttonIcon = new St.Icon({ style_class: 'mat-panel-button-icon', icon_size: Me.msThemeManager.getPanelSizeNotScaled() / 2, }); this.searchButton = new MatPanelButton({ child: this.buttonIcon, primary: true, height: Math.max( 48, Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex) ), }); this.searchButton.connect('clicked', () => { this.emit('toggle'); }); this.topBox.add_child(this.searchButton); this.workspaceList = new WorkspaceList(); this.topBox.add_child(this.workspaceList); //Bottom part this.statusArea = new MsStatusArea(); this.add_child(this.statusArea); Me.msThemeManager.connect('panel-size-changed', () => { this.buttonIcon.set_icon_size( Me.msThemeManager.getPanelSizeNotScaled() / 2 ); this.searchButton.height = Math.max( 48, Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex) ); this.queue_relayout(); }); this.setIcon('search'); } enable() { this.statusArea.enable(); } disable() { this.statusArea.disable(); } override vfunc_get_preferred_width(_forHeight: number): [number, number] { return [ Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex), Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex), ]; } setIcon(icon: 'search' | 'close') { if (icon === 'search') { this.buttonIcon.set_gicon( Gio.icon_new_for_string( `${Me.path}/assets/icons/magnify-symbolic.svg` ) ); } if (icon === 'close') { this.buttonIcon.set_gicon( Gio.icon_new_for_string( `${Me.path}/assets/icons/close-symbolic.svg` ) ); } } } @registerGObjectClass export class SearchContent extends St.BoxLayout { searchEntry: St.Entry; searchEntryBin: St.Bin; searchResultList: SearchResultList; scrollView = new St.ScrollView({ x_expand: true, hscrollbar_policy: St.PolicyType.NEVER, vscrollbar_policy: St.PolicyType.AUTOMATIC, }); constructor() { super({ vertical: true, y_expand: true, x_expand: true, x_align: Clutter.ActorAlign.FILL, }); this.searchEntry = new St.Entry({ style_class: 'search-entry margin', /* Translators: this is the text displayed in the search entry when no search is active; it should not exceed ~30 characters. */ hint_text: _('Type to search'), track_hover: true, can_focus: true, }); this.searchEntry.set_offscreen_redirect( Clutter.OffscreenRedirect.ALWAYS ); this.searchEntryBin = new St.Bin({ child: this.searchEntry, x_align: Clutter.ActorAlign.FILL, styleClass: 'background-primary', height: Math.max( 48, Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex) ), }); this.add_child(this.searchEntryBin); /* this.searchController = new SearchController.SearchController( this.searchEntry, Main.overview.dash.showAppsButton ); this.searchController.connect('notify::search-active', () => { Me.logFocus('search changed'); }); this.add_child(this.searchController); */ this.searchResultList = new SearchResultList(this.searchEntry); this.searchResultList.connect('result-selected-changed', (_, res) => { Me.logFocus('new result', res); Util.ensureActorVisibleInScrollView(this.scrollView, res); }); this.scrollView.add_actor(this.searchResultList); Me.msThemeManager.connect('panel-size-changed', () => { this.searchEntryBin.height = Math.max( 48, Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex) ); this.queue_relayout(); }); this.add_child(this.scrollView); } override vfunc_get_preferred_width(_forHeight: number): [number, number] { return [ 448 - Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex), 448 - Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex), ]; } } @registerGObjectClass export class MsPanel extends St.BoxLayout { static metaInfo: GObject.MetaInfo = { GTypeName: 'MsPanel', }; gnomeShellPanel: panel.Panel; panelContent: PanelContent; searchContent: SearchContent; divider: MatDivider; disableConnect: number; isExpanded = false; constructor() { super({ name: 'msPanel', reactive: true, }); this.gnomeShellPanel = Main.panel; this.gnomeShellPanel.hide(); // Top part this.panelContent = new PanelContent(); this.add_child(this.panelContent); this.searchContent = new SearchContent(); this.divider = new MatDivider(); this.disableConnect = Me.connect('extension-disable', () => { Me.logFocus('extension-disable'); Me.disconnect(this.disableConnect); this.disable(); }); Me.msThemeManager.connect('panel-size-changed', () => { this.queue_relayout(); }); this.panelContent.connect('toggle', () => { Me.layout.toggleOverview(); }); } enable() { this.gnomeShellPanel.hide(); this.panelContent.enable(); } disable() { this.gnomeShellPanel.show(); this.panelContent.disable(); } toggle() { if (!this.isExpanded) { if (!Me.layout.panelsVisible) { this.show(); } if (this.searchContent.get_parent() === null) { if ( Me.msThemeManager.verticalPanelPosition === VerticalPanelPositionEnum.LEFT ) { this.insert_child_below( this.searchContent, this.panelContent ); } else { this.insert_child_above( this.searchContent, this.panelContent ); } } if (this.divider.get_parent() === null) { if ( Me.msThemeManager.verticalPanelPosition === VerticalPanelPositionEnum.LEFT ) { this.insert_child_below(this.divider, this.panelContent); } else { this.insert_child_above(this.divider, this.panelContent); } } this.width = 448; this.translation_x = (448 - (Me.layout.panelsVisible ? Me.msThemeManager.getPanelSize( Main.layoutManager.primaryIndex ) : 0)) * (Me.msThemeManager.verticalPanelPosition === VerticalPanelPositionEnum.LEFT ? -1 : 1); this.ease({ translation_x: 0, duration: 200, mode: Clutter.AnimationMode.EASE_OUT_QUAD, }); this.searchContent.searchEntry.grab_key_focus(); this.panelContent.setIcon('close'); this.isExpanded = true; } else { this.isExpanded = false; this.panelContent.setIcon('search'); this.ease({ translation_x: (448 - (Me.layout.panelsVisible ? Me.msThemeManager.getPanelSize( Main.layoutManager.primaryIndex ) : 0)) * (Me.msThemeManager.verticalPanelPosition === VerticalPanelPositionEnum.LEFT ? -1 : 1), duration: 200, mode: Clutter.AnimationMode.EASE_OUT_QUAD, onComplete: () => { this.remove_child(this.searchContent); this.remove_child(this.divider); this.width = Me.msThemeManager.getPanelSize( Main.layoutManager.primaryIndex ); this.translation_x = 0; if (!Me.layout.panelsVisible) { this.hide(); } this.searchContent.searchResultList.reset(); }, }); } } override vfunc_get_preferred_height(_forWidth: number): [number, number] { const monitor = Main.layoutManager.primaryMonitor; assert(monitor !== null, 'found no primary monitor'); return [monitor.height, monitor.height]; } }
the_stack
import { Array } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { BodyArrayClient } from "../bodyArrayClient"; import { ArrayGetNullOptionalParams, ArrayGetNullResponse, ArrayGetInvalidOptionalParams, ArrayGetInvalidResponse, ArrayGetEmptyOptionalParams, ArrayGetEmptyResponse, ArrayPutEmptyOptionalParams, ArrayGetBooleanTfftOptionalParams, ArrayGetBooleanTfftResponse, ArrayPutBooleanTfftOptionalParams, ArrayGetBooleanInvalidNullOptionalParams, ArrayGetBooleanInvalidNullResponse, ArrayGetBooleanInvalidStringOptionalParams, ArrayGetBooleanInvalidStringResponse, ArrayGetIntegerValidOptionalParams, ArrayGetIntegerValidResponse, ArrayPutIntegerValidOptionalParams, ArrayGetIntInvalidNullOptionalParams, ArrayGetIntInvalidNullResponse, ArrayGetIntInvalidStringOptionalParams, ArrayGetIntInvalidStringResponse, ArrayGetLongValidOptionalParams, ArrayGetLongValidResponse, ArrayPutLongValidOptionalParams, ArrayGetLongInvalidNullOptionalParams, ArrayGetLongInvalidNullResponse, ArrayGetLongInvalidStringOptionalParams, ArrayGetLongInvalidStringResponse, ArrayGetFloatValidOptionalParams, ArrayGetFloatValidResponse, ArrayPutFloatValidOptionalParams, ArrayGetFloatInvalidNullOptionalParams, ArrayGetFloatInvalidNullResponse, ArrayGetFloatInvalidStringOptionalParams, ArrayGetFloatInvalidStringResponse, ArrayGetDoubleValidOptionalParams, ArrayGetDoubleValidResponse, ArrayPutDoubleValidOptionalParams, ArrayGetDoubleInvalidNullOptionalParams, ArrayGetDoubleInvalidNullResponse, ArrayGetDoubleInvalidStringOptionalParams, ArrayGetDoubleInvalidStringResponse, ArrayGetStringValidOptionalParams, ArrayGetStringValidResponse, ArrayPutStringValidOptionalParams, ArrayGetEnumValidOptionalParams, ArrayGetEnumValidResponse, FooEnum, ArrayPutEnumValidOptionalParams, ArrayGetStringEnumValidOptionalParams, ArrayGetStringEnumValidResponse, Enum1, ArrayPutStringEnumValidOptionalParams, ArrayGetStringWithNullOptionalParams, ArrayGetStringWithNullResponse, ArrayGetStringWithInvalidOptionalParams, ArrayGetStringWithInvalidResponse, ArrayGetUuidValidOptionalParams, ArrayGetUuidValidResponse, ArrayPutUuidValidOptionalParams, ArrayGetUuidInvalidCharsOptionalParams, ArrayGetUuidInvalidCharsResponse, ArrayGetDateValidOptionalParams, ArrayGetDateValidResponse, ArrayPutDateValidOptionalParams, ArrayGetDateInvalidNullOptionalParams, ArrayGetDateInvalidNullResponse, ArrayGetDateInvalidCharsOptionalParams, ArrayGetDateInvalidCharsResponse, ArrayGetDateTimeValidOptionalParams, ArrayGetDateTimeValidResponse, ArrayPutDateTimeValidOptionalParams, ArrayGetDateTimeInvalidNullOptionalParams, ArrayGetDateTimeInvalidNullResponse, ArrayGetDateTimeInvalidCharsOptionalParams, ArrayGetDateTimeInvalidCharsResponse, ArrayGetDateTimeRfc1123ValidOptionalParams, ArrayGetDateTimeRfc1123ValidResponse, ArrayPutDateTimeRfc1123ValidOptionalParams, ArrayGetDurationValidOptionalParams, ArrayGetDurationValidResponse, ArrayPutDurationValidOptionalParams, ArrayGetByteValidOptionalParams, ArrayGetByteValidResponse, ArrayPutByteValidOptionalParams, ArrayGetByteInvalidNullOptionalParams, ArrayGetByteInvalidNullResponse, ArrayGetBase64UrlOptionalParams, ArrayGetBase64UrlResponse, ArrayGetComplexNullOptionalParams, ArrayGetComplexNullResponse, ArrayGetComplexEmptyOptionalParams, ArrayGetComplexEmptyResponse, ArrayGetComplexItemNullOptionalParams, ArrayGetComplexItemNullResponse, ArrayGetComplexItemEmptyOptionalParams, ArrayGetComplexItemEmptyResponse, ArrayGetComplexValidOptionalParams, ArrayGetComplexValidResponse, Product, ArrayPutComplexValidOptionalParams, ArrayGetArrayNullOptionalParams, ArrayGetArrayNullResponse, ArrayGetArrayEmptyOptionalParams, ArrayGetArrayEmptyResponse, ArrayGetArrayItemNullOptionalParams, ArrayGetArrayItemNullResponse, ArrayGetArrayItemEmptyOptionalParams, ArrayGetArrayItemEmptyResponse, ArrayGetArrayValidOptionalParams, ArrayGetArrayValidResponse, ArrayPutArrayValidOptionalParams, ArrayGetDictionaryNullOptionalParams, ArrayGetDictionaryNullResponse, ArrayGetDictionaryEmptyOptionalParams, ArrayGetDictionaryEmptyResponse, ArrayGetDictionaryItemNullOptionalParams, ArrayGetDictionaryItemNullResponse, ArrayGetDictionaryItemEmptyOptionalParams, ArrayGetDictionaryItemEmptyResponse, ArrayGetDictionaryValidOptionalParams, ArrayGetDictionaryValidResponse, ArrayPutDictionaryValidOptionalParams } from "../models"; /** Class containing Array operations. */ export class ArrayImpl implements Array { private readonly client: BodyArrayClient; /** * Initialize a new instance of the class Array class. * @param client Reference to the service client */ constructor(client: BodyArrayClient) { this.client = client; } /** * Get null array value * @param options The options parameters. */ getNull(options?: ArrayGetNullOptionalParams): Promise<ArrayGetNullResponse> { return this.client.sendOperationRequest({ options }, getNullOperationSpec); } /** * Get invalid array [1, 2, 3 * @param options The options parameters. */ getInvalid( options?: ArrayGetInvalidOptionalParams ): Promise<ArrayGetInvalidResponse> { return this.client.sendOperationRequest( { options }, getInvalidOperationSpec ); } /** * Get empty array value [] * @param options The options parameters. */ getEmpty( options?: ArrayGetEmptyOptionalParams ): Promise<ArrayGetEmptyResponse> { return this.client.sendOperationRequest({ options }, getEmptyOperationSpec); } /** * Set array value empty [] * @param arrayBody The empty array value [] * @param options The options parameters. */ putEmpty( arrayBody: string[], options?: ArrayPutEmptyOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putEmptyOperationSpec ); } /** * Get boolean array value [true, false, false, true] * @param options The options parameters. */ getBooleanTfft( options?: ArrayGetBooleanTfftOptionalParams ): Promise<ArrayGetBooleanTfftResponse> { return this.client.sendOperationRequest( { options }, getBooleanTfftOperationSpec ); } /** * Set array value empty [true, false, false, true] * @param arrayBody The array value [true, false, false, true] * @param options The options parameters. */ putBooleanTfft( arrayBody: boolean[], options?: ArrayPutBooleanTfftOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putBooleanTfftOperationSpec ); } /** * Get boolean array value [true, null, false] * @param options The options parameters. */ getBooleanInvalidNull( options?: ArrayGetBooleanInvalidNullOptionalParams ): Promise<ArrayGetBooleanInvalidNullResponse> { return this.client.sendOperationRequest( { options }, getBooleanInvalidNullOperationSpec ); } /** * Get boolean array value [true, 'boolean', false] * @param options The options parameters. */ getBooleanInvalidString( options?: ArrayGetBooleanInvalidStringOptionalParams ): Promise<ArrayGetBooleanInvalidStringResponse> { return this.client.sendOperationRequest( { options }, getBooleanInvalidStringOperationSpec ); } /** * Get integer array value [1, -1, 3, 300] * @param options The options parameters. */ getIntegerValid( options?: ArrayGetIntegerValidOptionalParams ): Promise<ArrayGetIntegerValidResponse> { return this.client.sendOperationRequest( { options }, getIntegerValidOperationSpec ); } /** * Set array value empty [1, -1, 3, 300] * @param arrayBody The array value [1, -1, 3, 300] * @param options The options parameters. */ putIntegerValid( arrayBody: number[], options?: ArrayPutIntegerValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putIntegerValidOperationSpec ); } /** * Get integer array value [1, null, 0] * @param options The options parameters. */ getIntInvalidNull( options?: ArrayGetIntInvalidNullOptionalParams ): Promise<ArrayGetIntInvalidNullResponse> { return this.client.sendOperationRequest( { options }, getIntInvalidNullOperationSpec ); } /** * Get integer array value [1, 'integer', 0] * @param options The options parameters. */ getIntInvalidString( options?: ArrayGetIntInvalidStringOptionalParams ): Promise<ArrayGetIntInvalidStringResponse> { return this.client.sendOperationRequest( { options }, getIntInvalidStringOperationSpec ); } /** * Get integer array value [1, -1, 3, 300] * @param options The options parameters. */ getLongValid( options?: ArrayGetLongValidOptionalParams ): Promise<ArrayGetLongValidResponse> { return this.client.sendOperationRequest( { options }, getLongValidOperationSpec ); } /** * Set array value empty [1, -1, 3, 300] * @param arrayBody The array value [1, -1, 3, 300] * @param options The options parameters. */ putLongValid( arrayBody: number[], options?: ArrayPutLongValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putLongValidOperationSpec ); } /** * Get long array value [1, null, 0] * @param options The options parameters. */ getLongInvalidNull( options?: ArrayGetLongInvalidNullOptionalParams ): Promise<ArrayGetLongInvalidNullResponse> { return this.client.sendOperationRequest( { options }, getLongInvalidNullOperationSpec ); } /** * Get long array value [1, 'integer', 0] * @param options The options parameters. */ getLongInvalidString( options?: ArrayGetLongInvalidStringOptionalParams ): Promise<ArrayGetLongInvalidStringResponse> { return this.client.sendOperationRequest( { options }, getLongInvalidStringOperationSpec ); } /** * Get float array value [0, -0.01, 1.2e20] * @param options The options parameters. */ getFloatValid( options?: ArrayGetFloatValidOptionalParams ): Promise<ArrayGetFloatValidResponse> { return this.client.sendOperationRequest( { options }, getFloatValidOperationSpec ); } /** * Set array value [0, -0.01, 1.2e20] * @param arrayBody The array value [0, -0.01, 1.2e20] * @param options The options parameters. */ putFloatValid( arrayBody: number[], options?: ArrayPutFloatValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putFloatValidOperationSpec ); } /** * Get float array value [0.0, null, -1.2e20] * @param options The options parameters. */ getFloatInvalidNull( options?: ArrayGetFloatInvalidNullOptionalParams ): Promise<ArrayGetFloatInvalidNullResponse> { return this.client.sendOperationRequest( { options }, getFloatInvalidNullOperationSpec ); } /** * Get boolean array value [1.0, 'number', 0.0] * @param options The options parameters. */ getFloatInvalidString( options?: ArrayGetFloatInvalidStringOptionalParams ): Promise<ArrayGetFloatInvalidStringResponse> { return this.client.sendOperationRequest( { options }, getFloatInvalidStringOperationSpec ); } /** * Get float array value [0, -0.01, 1.2e20] * @param options The options parameters. */ getDoubleValid( options?: ArrayGetDoubleValidOptionalParams ): Promise<ArrayGetDoubleValidResponse> { return this.client.sendOperationRequest( { options }, getDoubleValidOperationSpec ); } /** * Set array value [0, -0.01, 1.2e20] * @param arrayBody The array value [0, -0.01, 1.2e20] * @param options The options parameters. */ putDoubleValid( arrayBody: number[], options?: ArrayPutDoubleValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putDoubleValidOperationSpec ); } /** * Get float array value [0.0, null, -1.2e20] * @param options The options parameters. */ getDoubleInvalidNull( options?: ArrayGetDoubleInvalidNullOptionalParams ): Promise<ArrayGetDoubleInvalidNullResponse> { return this.client.sendOperationRequest( { options }, getDoubleInvalidNullOperationSpec ); } /** * Get boolean array value [1.0, 'number', 0.0] * @param options The options parameters. */ getDoubleInvalidString( options?: ArrayGetDoubleInvalidStringOptionalParams ): Promise<ArrayGetDoubleInvalidStringResponse> { return this.client.sendOperationRequest( { options }, getDoubleInvalidStringOperationSpec ); } /** * Get string array value ['foo1', 'foo2', 'foo3'] * @param options The options parameters. */ getStringValid( options?: ArrayGetStringValidOptionalParams ): Promise<ArrayGetStringValidResponse> { return this.client.sendOperationRequest( { options }, getStringValidOperationSpec ); } /** * Set array value ['foo1', 'foo2', 'foo3'] * @param arrayBody The array value ['foo1', 'foo2', 'foo3'] * @param options The options parameters. */ putStringValid( arrayBody: string[], options?: ArrayPutStringValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putStringValidOperationSpec ); } /** * Get enum array value ['foo1', 'foo2', 'foo3'] * @param options The options parameters. */ getEnumValid( options?: ArrayGetEnumValidOptionalParams ): Promise<ArrayGetEnumValidResponse> { return this.client.sendOperationRequest( { options }, getEnumValidOperationSpec ); } /** * Set array value ['foo1', 'foo2', 'foo3'] * @param arrayBody The array value ['foo1', 'foo2', 'foo3'] * @param options The options parameters. */ putEnumValid( arrayBody: FooEnum[], options?: ArrayPutEnumValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putEnumValidOperationSpec ); } /** * Get enum array value ['foo1', 'foo2', 'foo3'] * @param options The options parameters. */ getStringEnumValid( options?: ArrayGetStringEnumValidOptionalParams ): Promise<ArrayGetStringEnumValidResponse> { return this.client.sendOperationRequest( { options }, getStringEnumValidOperationSpec ); } /** * Set array value ['foo1', 'foo2', 'foo3'] * @param arrayBody The array value ['foo1', 'foo2', 'foo3'] * @param options The options parameters. */ putStringEnumValid( arrayBody: Enum1[], options?: ArrayPutStringEnumValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putStringEnumValidOperationSpec ); } /** * Get string array value ['foo', null, 'foo2'] * @param options The options parameters. */ getStringWithNull( options?: ArrayGetStringWithNullOptionalParams ): Promise<ArrayGetStringWithNullResponse> { return this.client.sendOperationRequest( { options }, getStringWithNullOperationSpec ); } /** * Get string array value ['foo', 123, 'foo2'] * @param options The options parameters. */ getStringWithInvalid( options?: ArrayGetStringWithInvalidOptionalParams ): Promise<ArrayGetStringWithInvalidResponse> { return this.client.sendOperationRequest( { options }, getStringWithInvalidOperationSpec ); } /** * Get uuid array value ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652', * 'd1399005-30f7-40d6-8da6-dd7c89ad34db', 'f42f6aa1-a5bc-4ddf-907e-5f915de43205'] * @param options The options parameters. */ getUuidValid( options?: ArrayGetUuidValidOptionalParams ): Promise<ArrayGetUuidValidResponse> { return this.client.sendOperationRequest( { options }, getUuidValidOperationSpec ); } /** * Set array value ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652', 'd1399005-30f7-40d6-8da6-dd7c89ad34db', * 'f42f6aa1-a5bc-4ddf-907e-5f915de43205'] * @param arrayBody The array value ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652', * 'd1399005-30f7-40d6-8da6-dd7c89ad34db', 'f42f6aa1-a5bc-4ddf-907e-5f915de43205'] * @param options The options parameters. */ putUuidValid( arrayBody: string[], options?: ArrayPutUuidValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putUuidValidOperationSpec ); } /** * Get uuid array value ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652', 'foo'] * @param options The options parameters. */ getUuidInvalidChars( options?: ArrayGetUuidInvalidCharsOptionalParams ): Promise<ArrayGetUuidInvalidCharsResponse> { return this.client.sendOperationRequest( { options }, getUuidInvalidCharsOperationSpec ); } /** * Get integer array value ['2000-12-01', '1980-01-02', '1492-10-12'] * @param options The options parameters. */ getDateValid( options?: ArrayGetDateValidOptionalParams ): Promise<ArrayGetDateValidResponse> { return this.client.sendOperationRequest( { options }, getDateValidOperationSpec ); } /** * Set array value ['2000-12-01', '1980-01-02', '1492-10-12'] * @param arrayBody The array value ['2000-12-01', '1980-01-02', '1492-10-12'] * @param options The options parameters. */ putDateValid( arrayBody: Date[], options?: ArrayPutDateValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putDateValidOperationSpec ); } /** * Get date array value ['2012-01-01', null, '1776-07-04'] * @param options The options parameters. */ getDateInvalidNull( options?: ArrayGetDateInvalidNullOptionalParams ): Promise<ArrayGetDateInvalidNullResponse> { return this.client.sendOperationRequest( { options }, getDateInvalidNullOperationSpec ); } /** * Get date array value ['2011-03-22', 'date'] * @param options The options parameters. */ getDateInvalidChars( options?: ArrayGetDateInvalidCharsOptionalParams ): Promise<ArrayGetDateInvalidCharsResponse> { return this.client.sendOperationRequest( { options }, getDateInvalidCharsOperationSpec ); } /** * Get date-time array value ['2000-12-01t00:00:01z', '1980-01-02T00:11:35+01:00', * '1492-10-12T10:15:01-08:00'] * @param options The options parameters. */ getDateTimeValid( options?: ArrayGetDateTimeValidOptionalParams ): Promise<ArrayGetDateTimeValidResponse> { return this.client.sendOperationRequest( { options }, getDateTimeValidOperationSpec ); } /** * Set array value ['2000-12-01t00:00:01z', '1980-01-02T00:11:35+01:00', '1492-10-12T10:15:01-08:00'] * @param arrayBody The array value ['2000-12-01t00:00:01z', '1980-01-02T00:11:35+01:00', * '1492-10-12T10:15:01-08:00'] * @param options The options parameters. */ putDateTimeValid( arrayBody: Date[], options?: ArrayPutDateTimeValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putDateTimeValidOperationSpec ); } /** * Get date array value ['2000-12-01t00:00:01z', null] * @param options The options parameters. */ getDateTimeInvalidNull( options?: ArrayGetDateTimeInvalidNullOptionalParams ): Promise<ArrayGetDateTimeInvalidNullResponse> { return this.client.sendOperationRequest( { options }, getDateTimeInvalidNullOperationSpec ); } /** * Get date array value ['2000-12-01t00:00:01z', 'date-time'] * @param options The options parameters. */ getDateTimeInvalidChars( options?: ArrayGetDateTimeInvalidCharsOptionalParams ): Promise<ArrayGetDateTimeInvalidCharsResponse> { return this.client.sendOperationRequest( { options }, getDateTimeInvalidCharsOperationSpec ); } /** * Get date-time array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', 'Wed, * 12 Oct 1492 10:15:01 GMT'] * @param options The options parameters. */ getDateTimeRfc1123Valid( options?: ArrayGetDateTimeRfc1123ValidOptionalParams ): Promise<ArrayGetDateTimeRfc1123ValidResponse> { return this.client.sendOperationRequest( { options }, getDateTimeRfc1123ValidOperationSpec ); } /** * Set array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', 'Wed, 12 Oct * 1492 10:15:01 GMT'] * @param arrayBody The array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', * 'Wed, 12 Oct 1492 10:15:01 GMT'] * @param options The options parameters. */ putDateTimeRfc1123Valid( arrayBody: Date[], options?: ArrayPutDateTimeRfc1123ValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putDateTimeRfc1123ValidOperationSpec ); } /** * Get duration array value ['P123DT22H14M12.011S', 'P5DT1H0M0S'] * @param options The options parameters. */ getDurationValid( options?: ArrayGetDurationValidOptionalParams ): Promise<ArrayGetDurationValidResponse> { return this.client.sendOperationRequest( { options }, getDurationValidOperationSpec ); } /** * Set array value ['P123DT22H14M12.011S', 'P5DT1H0M0S'] * @param arrayBody The array value ['P123DT22H14M12.011S', 'P5DT1H0M0S'] * @param options The options parameters. */ putDurationValid( arrayBody: string[], options?: ArrayPutDurationValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putDurationValidOperationSpec ); } /** * Get byte array value [hex(FF FF FF FA), hex(01 02 03), hex (25, 29, 43)] with each item encoded in * base64 * @param options The options parameters. */ getByteValid( options?: ArrayGetByteValidOptionalParams ): Promise<ArrayGetByteValidResponse> { return this.client.sendOperationRequest( { options }, getByteValidOperationSpec ); } /** * Put the array value [hex(FF FF FF FA), hex(01 02 03), hex (25, 29, 43)] with each elementencoded in * base 64 * @param arrayBody The array value [hex(FF FF FF FA), hex(01 02 03), hex (25, 29, 43)] with each * elementencoded in base 64 * @param options The options parameters. */ putByteValid( arrayBody: Uint8Array[], options?: ArrayPutByteValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putByteValidOperationSpec ); } /** * Get byte array value [hex(AB, AC, AD), null] with the first item base64 encoded * @param options The options parameters. */ getByteInvalidNull( options?: ArrayGetByteInvalidNullOptionalParams ): Promise<ArrayGetByteInvalidNullResponse> { return this.client.sendOperationRequest( { options }, getByteInvalidNullOperationSpec ); } /** * Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the * items base64url encoded * @param options The options parameters. */ getBase64Url( options?: ArrayGetBase64UrlOptionalParams ): Promise<ArrayGetBase64UrlResponse> { return this.client.sendOperationRequest( { options }, getBase64UrlOperationSpec ); } /** * Get array of complex type null value * @param options The options parameters. */ getComplexNull( options?: ArrayGetComplexNullOptionalParams ): Promise<ArrayGetComplexNullResponse> { return this.client.sendOperationRequest( { options }, getComplexNullOperationSpec ); } /** * Get empty array of complex type [] * @param options The options parameters. */ getComplexEmpty( options?: ArrayGetComplexEmptyOptionalParams ): Promise<ArrayGetComplexEmptyResponse> { return this.client.sendOperationRequest( { options }, getComplexEmptyOperationSpec ); } /** * Get array of complex type with null item [{'integer': 1 'string': '2'}, null, {'integer': 5, * 'string': '6'}] * @param options The options parameters. */ getComplexItemNull( options?: ArrayGetComplexItemNullOptionalParams ): Promise<ArrayGetComplexItemNullResponse> { return this.client.sendOperationRequest( { options }, getComplexItemNullOperationSpec ); } /** * Get array of complex type with empty item [{'integer': 1 'string': '2'}, {}, {'integer': 5, * 'string': '6'}] * @param options The options parameters. */ getComplexItemEmpty( options?: ArrayGetComplexItemEmptyOptionalParams ): Promise<ArrayGetComplexItemEmptyResponse> { return this.client.sendOperationRequest( { options }, getComplexItemEmptyOperationSpec ); } /** * Get array of complex type with [{'integer': 1 'string': '2'}, {'integer': 3, 'string': '4'}, * {'integer': 5, 'string': '6'}] * @param options The options parameters. */ getComplexValid( options?: ArrayGetComplexValidOptionalParams ): Promise<ArrayGetComplexValidResponse> { return this.client.sendOperationRequest( { options }, getComplexValidOperationSpec ); } /** * Put an array of complex type with values [{'integer': 1 'string': '2'}, {'integer': 3, 'string': * '4'}, {'integer': 5, 'string': '6'}] * @param arrayBody array of complex type with [{'integer': 1 'string': '2'}, {'integer': 3, 'string': * '4'}, {'integer': 5, 'string': '6'}] * @param options The options parameters. */ putComplexValid( arrayBody: Product[], options?: ArrayPutComplexValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putComplexValidOperationSpec ); } /** * Get a null array * @param options The options parameters. */ getArrayNull( options?: ArrayGetArrayNullOptionalParams ): Promise<ArrayGetArrayNullResponse> { return this.client.sendOperationRequest( { options }, getArrayNullOperationSpec ); } /** * Get an empty array [] * @param options The options parameters. */ getArrayEmpty( options?: ArrayGetArrayEmptyOptionalParams ): Promise<ArrayGetArrayEmptyResponse> { return this.client.sendOperationRequest( { options }, getArrayEmptyOperationSpec ); } /** * Get an array of array of strings [['1', '2', '3'], null, ['7', '8', '9']] * @param options The options parameters. */ getArrayItemNull( options?: ArrayGetArrayItemNullOptionalParams ): Promise<ArrayGetArrayItemNullResponse> { return this.client.sendOperationRequest( { options }, getArrayItemNullOperationSpec ); } /** * Get an array of array of strings [['1', '2', '3'], [], ['7', '8', '9']] * @param options The options parameters. */ getArrayItemEmpty( options?: ArrayGetArrayItemEmptyOptionalParams ): Promise<ArrayGetArrayItemEmptyResponse> { return this.client.sendOperationRequest( { options }, getArrayItemEmptyOperationSpec ); } /** * Get an array of array of strings [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] * @param options The options parameters. */ getArrayValid( options?: ArrayGetArrayValidOptionalParams ): Promise<ArrayGetArrayValidResponse> { return this.client.sendOperationRequest( { options }, getArrayValidOperationSpec ); } /** * Put An array of array of strings [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] * @param arrayBody An array of array of strings [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] * @param options The options parameters. */ putArrayValid( arrayBody: string[][], options?: ArrayPutArrayValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putArrayValidOperationSpec ); } /** * Get an array of Dictionaries with value null * @param options The options parameters. */ getDictionaryNull( options?: ArrayGetDictionaryNullOptionalParams ): Promise<ArrayGetDictionaryNullResponse> { return this.client.sendOperationRequest( { options }, getDictionaryNullOperationSpec ); } /** * Get an array of Dictionaries of type <string, string> with value [] * @param options The options parameters. */ getDictionaryEmpty( options?: ArrayGetDictionaryEmptyOptionalParams ): Promise<ArrayGetDictionaryEmptyResponse> { return this.client.sendOperationRequest( { options }, getDictionaryEmptyOperationSpec ); } /** * Get an array of Dictionaries of type <string, string> with value [{'1': 'one', '2': 'two', '3': * 'three'}, null, {'7': 'seven', '8': 'eight', '9': 'nine'}] * @param options The options parameters. */ getDictionaryItemNull( options?: ArrayGetDictionaryItemNullOptionalParams ): Promise<ArrayGetDictionaryItemNullResponse> { return this.client.sendOperationRequest( { options }, getDictionaryItemNullOperationSpec ); } /** * Get an array of Dictionaries of type <string, string> with value [{'1': 'one', '2': 'two', '3': * 'three'}, {}, {'7': 'seven', '8': 'eight', '9': 'nine'}] * @param options The options parameters. */ getDictionaryItemEmpty( options?: ArrayGetDictionaryItemEmptyOptionalParams ): Promise<ArrayGetDictionaryItemEmptyResponse> { return this.client.sendOperationRequest( { options }, getDictionaryItemEmptyOperationSpec ); } /** * Get an array of Dictionaries of type <string, string> with value [{'1': 'one', '2': 'two', '3': * 'three'}, {'4': 'four', '5': 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9': 'nine'}] * @param options The options parameters. */ getDictionaryValid( options?: ArrayGetDictionaryValidOptionalParams ): Promise<ArrayGetDictionaryValidResponse> { return this.client.sendOperationRequest( { options }, getDictionaryValidOperationSpec ); } /** * Get an array of Dictionaries of type <string, string> with value [{'1': 'one', '2': 'two', '3': * 'three'}, {'4': 'four', '5': 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9': 'nine'}] * @param arrayBody An array of Dictionaries of type <string, string> with value [{'1': 'one', '2': * 'two', '3': 'three'}, {'4': 'four', '5': 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9': * 'nine'}] * @param options The options parameters. */ putDictionaryValid( arrayBody: { [propertyName: string]: string }[], options?: ArrayPutDictionaryValidOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { arrayBody, options }, putDictionaryValidOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const getNullOperationSpec: coreClient.OperationSpec = { path: "/array/null", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getInvalidOperationSpec: coreClient.OperationSpec = { path: "/array/invalid", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getEmptyOperationSpec: coreClient.OperationSpec = { path: "/array/empty", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putEmptyOperationSpec: coreClient.OperationSpec = { path: "/array/empty", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getBooleanTfftOperationSpec: coreClient.OperationSpec = { path: "/array/prim/boolean/tfft", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Boolean" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putBooleanTfftOperationSpec: coreClient.OperationSpec = { path: "/array/prim/boolean/tfft", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody1, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getBooleanInvalidNullOperationSpec: coreClient.OperationSpec = { path: "/array/prim/boolean/true.null.false", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Boolean" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getBooleanInvalidStringOperationSpec: coreClient.OperationSpec = { path: "/array/prim/boolean/true.boolean.false", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Boolean" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getIntegerValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/integer/1.-1.3.300", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putIntegerValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/integer/1.-1.3.300", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody2, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getIntInvalidNullOperationSpec: coreClient.OperationSpec = { path: "/array/prim/integer/1.null.zero", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getIntInvalidStringOperationSpec: coreClient.OperationSpec = { path: "/array/prim/integer/1.integer.0", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getLongValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/long/1.-1.3.300", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putLongValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/long/1.-1.3.300", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody2, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getLongInvalidNullOperationSpec: coreClient.OperationSpec = { path: "/array/prim/long/1.null.zero", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getLongInvalidStringOperationSpec: coreClient.OperationSpec = { path: "/array/prim/long/1.integer.0", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getFloatValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/float/0--0.01-1.2e20", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putFloatValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/float/0--0.01-1.2e20", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody2, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getFloatInvalidNullOperationSpec: coreClient.OperationSpec = { path: "/array/prim/float/0.0-null-1.2e20", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getFloatInvalidStringOperationSpec: coreClient.OperationSpec = { path: "/array/prim/float/1.number.0", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getDoubleValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/double/0--0.01-1.2e20", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putDoubleValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/double/0--0.01-1.2e20", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody2, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getDoubleInvalidNullOperationSpec: coreClient.OperationSpec = { path: "/array/prim/double/0.0-null-1.2e20", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getDoubleInvalidStringOperationSpec: coreClient.OperationSpec = { path: "/array/prim/double/1.number.0", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Number" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getStringValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/string/foo1.foo2.foo3", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "String" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putStringValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/string/foo1.foo2.foo3", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getEnumValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/enum/foo1.foo2.foo3", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Enum", allowedValues: ["foo1", "foo2", "foo3"] } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putEnumValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/enum/foo1.foo2.foo3", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody3, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getStringEnumValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/string-enum/foo1.foo2.foo3", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "String" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putStringEnumValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/string-enum/foo1.foo2.foo3", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody4, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getStringWithNullOperationSpec: coreClient.OperationSpec = { path: "/array/prim/string/foo.null.foo2", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "String" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getStringWithInvalidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/string/foo.123.foo2", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "String" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getUuidValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/uuid/valid", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Uuid" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putUuidValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/uuid/valid", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody5, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getUuidInvalidCharsOperationSpec: coreClient.OperationSpec = { path: "/array/prim/uuid/invalidchars", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Uuid" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getDateValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/date/valid", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Date" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putDateValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/date/valid", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody6, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getDateInvalidNullOperationSpec: coreClient.OperationSpec = { path: "/array/prim/date/invalidnull", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Date" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getDateInvalidCharsOperationSpec: coreClient.OperationSpec = { path: "/array/prim/date/invalidchars", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Date" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getDateTimeValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/date-time/valid", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "DateTime" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putDateTimeValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/date-time/valid", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody7, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getDateTimeInvalidNullOperationSpec: coreClient.OperationSpec = { path: "/array/prim/date-time/invalidnull", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "DateTime" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getDateTimeInvalidCharsOperationSpec: coreClient.OperationSpec = { path: "/array/prim/date-time/invalidchars", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "DateTime" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getDateTimeRfc1123ValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/date-time-rfc1123/valid", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "DateTimeRfc1123" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putDateTimeRfc1123ValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/date-time-rfc1123/valid", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody8, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getDurationValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/duration/valid", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "TimeSpan" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putDurationValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/duration/valid", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody9, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getByteValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/byte/valid", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "ByteArray" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putByteValidOperationSpec: coreClient.OperationSpec = { path: "/array/prim/byte/valid", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody10, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getByteInvalidNullOperationSpec: coreClient.OperationSpec = { path: "/array/prim/byte/invalidnull", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "ByteArray" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getBase64UrlOperationSpec: coreClient.OperationSpec = { path: "/array/prim/base64url/valid", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Base64Url" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getComplexNullOperationSpec: coreClient.OperationSpec = { path: "/array/complex/null", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Composite", className: "Product" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getComplexEmptyOperationSpec: coreClient.OperationSpec = { path: "/array/complex/empty", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Composite", className: "Product" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getComplexItemNullOperationSpec: coreClient.OperationSpec = { path: "/array/complex/itemnull", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Composite", className: "Product" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getComplexItemEmptyOperationSpec: coreClient.OperationSpec = { path: "/array/complex/itemempty", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Composite", className: "Product" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getComplexValidOperationSpec: coreClient.OperationSpec = { path: "/array/complex/valid", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Composite", className: "Product" } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putComplexValidOperationSpec: coreClient.OperationSpec = { path: "/array/complex/valid", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody11, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getArrayNullOperationSpec: coreClient.OperationSpec = { path: "/array/array/null", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Sequence", element: { type: { name: "String" } } } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getArrayEmptyOperationSpec: coreClient.OperationSpec = { path: "/array/array/empty", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Sequence", element: { type: { name: "String" } } } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getArrayItemNullOperationSpec: coreClient.OperationSpec = { path: "/array/array/itemnull", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Sequence", element: { type: { name: "String" } } } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getArrayItemEmptyOperationSpec: coreClient.OperationSpec = { path: "/array/array/itemempty", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Sequence", element: { type: { name: "String" } } } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getArrayValidOperationSpec: coreClient.OperationSpec = { path: "/array/array/valid", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Sequence", element: { type: { name: "String" } } } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putArrayValidOperationSpec: coreClient.OperationSpec = { path: "/array/array/valid", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody12, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getDictionaryNullOperationSpec: coreClient.OperationSpec = { path: "/array/dictionary/null", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getDictionaryEmptyOperationSpec: coreClient.OperationSpec = { path: "/array/dictionary/empty", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getDictionaryItemNullOperationSpec: coreClient.OperationSpec = { path: "/array/dictionary/itemnull", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getDictionaryItemEmptyOperationSpec: coreClient.OperationSpec = { path: "/array/dictionary/itemempty", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getDictionaryValidOperationSpec: coreClient.OperationSpec = { path: "/array/dictionary/valid", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Sequence", element: { type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }, default: { bodyMapper: Mappers.ErrorModel } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const putDictionaryValidOperationSpec: coreClient.OperationSpec = { path: "/array/dictionary/valid", httpMethod: "PUT", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorModel } }, requestBody: Parameters.arrayBody13, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer };
the_stack
import { Vector3 } from 'three' import { PickerRegistry } from '../globals' import { calculateMeanVector3 } from '../math/vector-utils' import Selection from '../selection/selection' import { ArrowPrimitive, BoxPrimitive, ConePrimitive, CylinderPrimitive, EllipsoidPrimitive, OctahedronPrimitive, SpherePrimitive, TetrahedronPrimitive, TorusPrimitive, PointPrimitive, WidelinePrimitive } from '../geometry/primitive' import { contactTypeName, Contacts } from '../chemistry/interactions/contact' import { TypedArray } from '../types'; import Component from '../component/component'; import { Shape, Structure, Volume } from '../ngl'; import BondStore from '../store/bond-store'; import Validation from '../structure/validation'; import PrincipalAxes from '../math/principal-axes'; import Surface from '../surface/surface'; import Unitcell from '../symmetry/unitcell'; import BondProxy from '../proxy/bond-proxy'; import AtomProxy from '../proxy/atom-proxy'; /** * Picker class * @interface */ class Picker { array: number[]|TypedArray|undefined /** * @param {Array|TypedArray} [array] - mapping */ constructor (array?: number[]|TypedArray) { this.array = array } get type () { return '' } get data () { return {} } /** * Get the index for the given picking id * @param {Integer} pid - the picking id * @return {Integer} the index */ getIndex (pid: number) { return this.array ? this.array[ pid ] : pid } /** * Get object data * @abstract * @param {Integer} pid - the picking id * @return {Object} the object data */ getObject (pid: number) { return {} } _applyTransformations (vector: Vector3, instance: any, component: Component) { if (instance) { vector.applyMatrix4(instance.matrix) } if (component) { vector.applyMatrix4(component.matrix) } return vector } /** * Get object position * @abstract * @param {Integer} pid - the picking id * @return {Vector3} the object position */ _getPosition (pid: number) { return new Vector3() } /** * Get position for the given picking id * @param {Integer} pid - the picking id * @param {Object} instance - the instance that should be applied * @param {Component} component - the component of the picked object * @return {Vector3} the position */ getPosition (pid: number, instance: any, component: Component) { return this._applyTransformations( this._getPosition(pid), instance, component ) } } /** * Shape picker class * @interface */ class ShapePicker extends Picker { shape: Shape /** * @param {Shape} shape - shape object */ constructor (shape: Shape) { super() this.shape = shape } get primitive (): any { return } get data () { return this.shape } get type () { return this.primitive.type } getObject (pid: number) { return this.primitive.objectFromShape(this.shape, this.getIndex(pid)) } _getPosition (pid: number) { return this.primitive.positionFromShape(this.shape, this.getIndex(pid)) } } // class CylinderPicker extends ShapePicker { get primitive () { return CylinderPrimitive } } class ArrowPicker extends ShapePicker { get primitive () { return ArrowPrimitive } } class AtomPicker extends Picker { structure: Structure constructor (array: Float32Array, structure: Structure) { super(array) this.structure = structure } get type () { return 'atom' } get data () { return this.structure } getObject (pid: number): AtomProxy { return this.structure.getAtomProxy(this.getIndex(pid)) } _getPosition (pid: number) { return new Vector3().copy(this.getObject(pid) as any) } } class AxesPicker extends Picker { axes: PrincipalAxes constructor (axes: PrincipalAxes) { super() this.axes = axes } get type () { return 'axes' } get data () { return this.axes } getObject (/* pid */) { return { axes: this.axes } } _getPosition (/* pid */) { return this.axes.center.clone() } } class BondPicker extends Picker { structure: Structure bondStore: BondStore constructor (array: number[]|TypedArray|undefined, structure: Structure, bondStore: BondStore) { super(array) this.structure = structure this.bondStore = bondStore || structure.bondStore } get type () { return 'bond' } get data () { return this.structure } getObject (pid: number): BondProxy { const bp = this.structure.getBondProxy(this.getIndex(pid)) bp.bondStore = this.bondStore return bp } _getPosition (pid: number) { const b = this.getObject(pid) return new Vector3() .copy(b.atom1 as any) .add(b.atom2 as any) .multiplyScalar(0.5) } } class ContactPicker extends Picker { contacts: Contacts structure: Structure constructor (array: number[]|TypedArray|undefined, contacts: Contacts, structure: Structure) { super(array) this.contacts = contacts this.structure = structure } get type () { return 'contact' } get data () { return this.contacts } getObject (pid: number) { const idx = this.getIndex(pid) const { features, contactStore } = this.contacts const { centers, atomSets } = features const { x, y, z } = centers const { index1, index2, type } = contactStore const k = index1[idx] const l = index2[idx] return { center1: new Vector3(x[k], y[k], z[k]), center2: new Vector3(x[l], y[l], z[l]), atom1: this.structure.getAtomProxy(atomSets[k][0]), atom2: this.structure.getAtomProxy(atomSets[l][0]), type: contactTypeName(type[idx]) } } _getPosition (pid: number) { const { center1, center2 } = this.getObject(pid) return new Vector3().addVectors(center1, center2).multiplyScalar(0.5) } } class ConePicker extends ShapePicker { get primitive () { return ConePrimitive } } class ClashPicker extends Picker { validation: Validation structure: Structure constructor (array: number[]|TypedArray|undefined, validation: Validation, structure: Structure) { super(array) this.validation = validation this.structure = structure } get type () { return 'clash' } get data () { return this.validation } getObject (pid: number) { const val = this.validation const idx = this.getIndex(pid) return { validation: val, index: idx, clash: val.clashArray[ idx ] } } _getAtomProxyFromSele (sele: string) { const selection = new Selection(sele) const idx = this.structure.getAtomIndices(selection)![ 0 ] return this.structure.getAtomProxy(idx) } _getPosition (pid: number) { const clash = this.getObject(pid).clash const ap1 = this._getAtomProxyFromSele(clash.sele1) const ap2 = this._getAtomProxyFromSele(clash.sele2) return new Vector3().copy(ap1 as any).add(ap2 as any).multiplyScalar(0.5) } } class DistancePicker extends BondPicker { get type () { return 'distance' } } class EllipsoidPicker extends ShapePicker { get primitive () { return EllipsoidPrimitive } } class OctahedronPicker extends ShapePicker { get primitive () { return OctahedronPrimitive } } class BoxPicker extends ShapePicker { get primitive () { return BoxPrimitive } } class IgnorePicker extends Picker { get type () { return 'ignore' } } export interface MeshData { name: string|undefined serial: number index: Uint32Array|Uint16Array|number[] normal?: Float32Array|number[] position: Float32Array|number[] color: Float32Array|number[] } class MeshPicker extends ShapePicker { mesh: MeshData __position: Vector3 constructor (shape: Shape, mesh: MeshData) { super(shape) this.mesh = mesh } get type () { return 'mesh' } getObject (/* pid */) { const m = this.mesh return { shape: this.shape, name: m.name, serial: m.serial } } _getPosition (/* pid */) { if (!this.__position) { this.__position = calculateMeanVector3(this.mesh.position as any) } return this.__position } } class SpherePicker extends ShapePicker { get primitive () { return SpherePrimitive } } class SurfacePicker extends Picker { surface: Surface constructor (array: number[]|TypedArray|undefined, surface: Surface) { super(array) this.surface = surface } get type () { return 'surface' } get data () { return this.surface } getObject (pid: number) { return { surface: this.surface, index: this.getIndex(pid) } } _getPosition (/* pid */) { return this.surface.center.clone() } } class TetrahedronPicker extends ShapePicker { get primitive () { return TetrahedronPrimitive } } class TorusPicker extends ShapePicker { get primitive () { return TorusPrimitive } } class UnitcellPicker extends Picker { unitcell: Unitcell structure: Structure constructor (unitcell: Unitcell, structure: Structure) { super() this.unitcell = unitcell this.structure = structure } get type () { return 'unitcell' } get data () { return this.unitcell } getObject (/* pid */) { return { unitcell: this.unitcell, structure: this.structure } } _getPosition (/* pid */) { return this.unitcell.getCenter(this.structure) } } class UnknownPicker extends Picker { get type () { return 'unknown' } } class VolumePicker extends Picker { volume: Volume constructor (array: TypedArray, volume: Volume) { super(array) this.volume = volume } get type () { return 'volume' } get data () { return this.volume } getObject (pid: number) { const vol = this.volume const idx = this.getIndex(pid) return { volume: vol, index: idx, value: vol.data[ idx ] } } _getPosition (pid: number) { const dp = this.volume.position const idx = this.getIndex(pid) return new Vector3( dp[ idx * 3 ], dp[ idx * 3 + 1 ], dp[ idx * 3 + 2 ] ) } } class SlicePicker extends VolumePicker { get type () { return 'slice' } } class PointPicker extends ShapePicker { get primitive () { return PointPrimitive } } class WidelinePicker extends ShapePicker { get primitive () { return WidelinePrimitive } } PickerRegistry.add('arrow', ArrowPicker) PickerRegistry.add('box', BoxPicker) PickerRegistry.add('cone', ConePicker) PickerRegistry.add('cylinder', CylinderPicker) PickerRegistry.add('ellipsoid', EllipsoidPicker) PickerRegistry.add('octahedron', OctahedronPicker) PickerRegistry.add('sphere', SpherePicker) PickerRegistry.add('tetrahedron', TetrahedronPicker) PickerRegistry.add('torus', TorusPicker) PickerRegistry.add('point', PointPicker) PickerRegistry.add('wideline', WidelinePicker) export { Picker, ShapePicker, ArrowPicker, AtomPicker, AxesPicker, BondPicker, BoxPicker, ConePicker, ContactPicker, CylinderPicker, ClashPicker, DistancePicker, EllipsoidPicker, IgnorePicker, OctahedronPicker, MeshPicker, SlicePicker, SpherePicker, SurfacePicker, TetrahedronPicker, TorusPicker, UnitcellPicker, UnknownPicker, VolumePicker, PointPicker, WidelinePicker }
the_stack
"use strict"; import { MapLike } from "map-like"; import { Payload } from "../payload/Payload"; import { DispatcherPayloadMeta, DispatcherPayloadMetaImpl } from "../DispatcherPayloadMeta"; import { isWillExecutedPayload } from "../payload/WillExecutedPayload"; import { isCompletedPayload } from "../payload/CompletedPayload"; import { shallowEqual } from "shallow-equal-object"; import { Dispatcher } from "../Dispatcher"; import { StateMap, StoreMap } from "./StoreGroupTypes"; import { createStoreStateMap, StoreStateMap } from "./StoreStateMap"; import { Store } from "../Store"; import { StoreGroupEmitChangeChecker } from "./StoreGroupEmitChangeChecker"; import { shouldStateUpdate } from "./StoreGroupUtils"; import { Commitment } from "../UnitOfWork/UnitOfWork"; import { InitializedPayload } from "../payload/InitializedPayload"; import { StoreGroupChangingStoreStrictChecker } from "./StoreGroupChangingStoreStrictChecker"; import { StoreGroupLike, StoreGroupReasonForChange } from "./StoreGroupLike"; import { isDidExecutedPayload } from "../payload/DidExecutedPayload"; import { isErrorPayload } from "../payload/ErrorPayload"; import { isTransactionBeganPayload } from "../payload/TransactionBeganPayload"; import { isTransactionEndedPayload } from "../payload/TransactionEndedPayload"; import AlminInstruments from "../instrument/AlminInstruments"; import { DebugId } from "../instrument/AlminAbstractPerfMarker"; import { generateNewId } from "./StoreGroupIdGenerator"; import { assertOK } from "../util/assert"; import { Events } from "../Events"; // { stateName: state } export interface StoreGroupState { [key: string]: any; } /** * assert: check arguments of constructor. */ const assertConstructorArguments = (arg: any): void => { const message = `Should initialize this StoreGroup with a stateName-store mapping object. const aStore = new AStore(); const bStore = new BStore(); // A arguments is stateName-store mapping object like { stateName: store } const storeGroup = new StoreGroup({ a: aStore, b: bStore }); console.log(storeGroup.getState()); // { a: "a value", b: "b value" } `; assertOK(typeof arg === "object" && arg !== null && !Array.isArray(arg), message); const keys = Object.keys(arg); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = arg[key]; // Don't checking for accepting string or symbol. // assert.ok(typeof key === "string", `key should be string type: ${key}: ${value}` + "\n" + message); assertOK(Store.isStore(value), `value should be instance of Store: ${key}: ${value}` + "\n" + message); } }; type StoreGroupChangeEvent<T> = { stores: Array<Store<T>>; details: StoreGroupReasonForChange | undefined; }; /** * StoreGroup is a parts of read-model. * * StoreGroup has separated two phase in a life-cycle. * These are called Write phase and Read phase. * * StoreGroup often does write phase and, then read phase. * * ## Write phase * * StoreGroup notify update timing for each stores. * * It means that call each `Store#receivePayload()`. * * ### When * * - Initialize StoreGroup * - A parts of life-cycle during execute UseCase * - Force update StoreGroup * * ### What does store? * * - Store update own state if needed * * ### What does not store? * * - Store should not directly assign to state instead of using `Store#setState` * * ## Read phase * * StoreGroup read the state from each stores. * * It means that call each `Store#getState()`. * * ### When * * - Initialize StoreGroup * - A parts of life-cycle during execute UseCase * - Force update StoreGroup * - Some store call `Store#emitChange` * * ### What does store? * * - Store return own state * * ### What does not store? * * - Does not update own state * - Please update own state in write phase * * ### Notes * * #### Pull-based: Recompute every time value is needed * * Pull-based Store has only getState. * Just create the state and return it when `getState` is called. * * #### Push-based: Recompute when a source value changes * * Push-based Store have to create the state and save it. * Just return the state when `getState` is called. * It is similar with cache system. * */ export class StoreGroup<T> extends Dispatcher implements StoreGroupLike { // Set debuggable name if needed. static displayName?: string; // observing stores public stores: Array<Store<T>>; // current state public state: StateMap<T>; // StoreGroup name public name: string; // debug id public id: string; // stores that are changed compared by previous state. private _changingStores: Array<Store<T>> = []; // all functions to release handlers private _releaseHandlers: Array<Function> = []; // current working useCase private _workingUseCaseMap: MapLike<string, boolean>; // manage finished usecase private _finishedUseCaseMap: MapLike<string, boolean>; // store/state cache map private _stateCacheMap: MapLike<Store<T>, any>; // store/state map private _storeStateMap: StoreStateMap; // is strict mode private isStrictMode = false; // is transaction working private isTransactionWorking = false; // checker private storeGroupEmitChangeChecker = new StoreGroupEmitChangeChecker(); private storeGroupChangingStoreStrictChecker = new StoreGroupChangingStoreStrictChecker(); private storeGroupChangeEvent = new Events<StoreGroupChangeEvent<T>>(); /** * Initialize this StoreGroup with a stateName-store mapping object. * * The rule of initializing StoreGroup is that "define the state name of the store". * * ## Example * * Initialize with store-state mapping object. * * ```js * class AStore extends Store { * getState() { * return "a value"; * } * } * class BStore extends Store { * getState() { * return "b value"; * } * } * const aStore = new AStore(); * const bStore = new BStore(); * const storeGroup = new StoreGroup({ * a: aStore, // stateName: store * b: bStore * }); * console.log(storeGroup.getState()); * // { a: "a value", b: "b value" } * ``` */ constructor(public stateStoreMapping: StoreMap<T>) { super(); if (process.env.NODE_ENV !== "production") { assertConstructorArguments(stateStoreMapping); } const own = this.constructor as typeof StoreGroup; /** * @type {string} Store name */ this.name = own.displayName || own.name || "StoreGroup"; this.id = generateNewId(); this._storeStateMap = createStoreStateMap(stateStoreMapping); // pull stores from mapping if arguments is mapping. this.stores = this._storeStateMap.stores; this._workingUseCaseMap = new MapLike<string, boolean>(); this._finishedUseCaseMap = new MapLike<string, boolean>(); this._stateCacheMap = new MapLike<Store<T>, any>(); // Implementation Note: // Dispatch -> pipe -> Store#emitChange() if it is needed // -> this.onDispatch -> If anyone store is changed, this.emitChange() // each pipe to dispatching this.stores.forEach((store) => { // observe Store const unRegisterHandler = this._registerStore(store); this._releaseHandlers.push(unRegisterHandler); }); // default state this.state = this.initializeGroupState(this.stores); } /** * If exist working UseCase, return true */ private get existWorkingUseCase() { return this._workingUseCaseMap.size > 0; } /** * Return the state object that merge each stores's state */ getState(): StateMap<T> { return this.state; } private initializeGroupState(stores: Array<Store<T>>): StateMap<T> { // InitializedPayload for passing to Store if the state change is not related payload. const payload = new InitializedPayload(); const meta = new DispatcherPayloadMetaImpl({ isTrusted: true }); // 1. write in read this.writePhaseInRead(stores, payload, meta); // 2. read in read return this.readPhaseInRead(stores); } // write phase // Each store updates own state private writePhaseInRead( stores: Array<Store<T>>, payload: Payload, meta: DispatcherPayloadMetaImpl, debugId?: DebugId ): void { if (process.env.NODE_ENV !== "production" && AlminInstruments.debugTool) { if (debugId) { // Notes: writer's `debugId` is difference by source // It means that writer's `debugId` should not depended on StoreGroup-self. AlminInstruments.debugTool.beforeStoreGroupWritePhase(debugId, this); } } for (let i = 0; i < stores.length; i++) { const store = stores[i]; if (process.env.NODE_ENV !== "production") { this.storeGroupChangingStoreStrictChecker.mark(store); } const hasReceivePayload = typeof store.receivePayload === "function"; if (process.env.NODE_ENV !== "production" && AlminInstruments.debugTool) { if (hasReceivePayload && debugId) { AlminInstruments.debugTool.beforeStoreReceivePayload(debugId, store); } } // In almost case, A store should implement `receivePayload` insteadof of using `Store#onDispatch` // Warning(strict mode): Manually catch some event like Repository#onChange in a Store, // It would be broken in transaction mode // `Store#onDispatch` receive only dispatched the Payload by `UseCase#dispatch` that is not trusted data. if (!meta.isTrusted) { store.dispatch(payload, meta); } // reduce state by prevSate with payload if it is implemented if (hasReceivePayload) { store.receivePayload!(payload); } if (process.env.NODE_ENV !== "production" && AlminInstruments.debugTool) { if (hasReceivePayload && debugId) { AlminInstruments.debugTool.afterStoreReceivePayload(debugId, store); } } if (process.env.NODE_ENV !== "production") { this.storeGroupChangingStoreStrictChecker.unMark(store); } } if (process.env.NODE_ENV !== "production" && AlminInstruments.debugTool) { if (debugId) { AlminInstruments.debugTool.afterStoreGroupWritePhase(debugId, this); } } } // read phase // Get state from each store private readPhaseInRead(stores: Array<Store<T>>): StateMap<T> { const debugTool = AlminInstruments.debugTool; if (process.env.NODE_ENV !== "production" && debugTool) { // Notes: use StoreGroup#id as reader's `id` // Because reader is sync behavior and it nos called multiple at a time. debugTool.beforeStoreGroupReadPhase(this.id, this); } const groupState: StoreGroupState = {}; for (let i = 0; i < stores.length; i++) { const store = stores[i]; const prevState = this._stateCacheMap.get(store); if (process.env.NODE_ENV !== "production" && debugTool) { debugTool.beforeStoreGetState(this.id, this); } const nextState = store.getState(); if (process.env.NODE_ENV !== "production" && debugTool) { debugTool.afterStoreGetState(this.id, this); } // if the prev/next state is same, not update the state. const stateName = this._storeStateMap.get(store); if (process.env.NODE_ENV !== "production") { assertOK( stateName !== undefined, `Store:${store.name} is not registered in constructor. But, ${store.name}#getState() was called.` ); this.storeGroupEmitChangeChecker.warningIfStatePropertyIsModifiedDirectly(store, prevState, nextState); // nextState has confirmed and release the `store` from the checker this.storeGroupEmitChangeChecker.unMark(store); } // the state is not changed, set prevState as state of the store if (!shouldStateUpdate(store, prevState, nextState)) { groupState[stateName!] = prevState; continue; } // Update cache this._stateCacheMap.set(store, nextState); // Changing flag On this._addChangingStateOfStores(store); // Set state groupState[stateName!] = nextState; } if (process.env.NODE_ENV !== "production" && debugTool) { debugTool.afterStoreGroupReadPhase(this.id, this); } return groupState as StateMap<T>; } /** * Use `shouldStateUpdate()` to let StoreGroup know if a event is not affected. * The default behavior is to emitChange on every life-cycle change, * and in the vast majority of cases you should rely on the default behavior. * Default behavior is shallow-equal prev/next state. * * ## Example * * If you want to use `Object.is` to equal states, overwrite following. * * ```js * shouldStateUpdate(prevState, nextState) { * return !Object.is(prevState, nextState) * } * ``` */ shouldStateUpdate(prevState: any, nextState: any): boolean { return !shallowEqual(prevState, nextState); } /** * Emit change if the state is changed. * If call with no-arguments, use ChangedPayload by default. */ emitChange(): void { this.emitChangeIfStateIsChange(); } private tryToUpdateState(payload: Payload, meta: DispatcherPayloadMeta, debugId?: DebugId) { this.writePhaseInRead(this.stores, payload, meta, debugId); // StoreGroup soft lock `emitChange` in the transaction. if (!this.isTransactionWorking) { this.emitChangeIfStateIsChange(payload, meta); } } /** * **Internal** * * ## Implementation Notes: * * StoreGroup should be push-model. * Almin can control all transaction to StoreGroup. * * It means that StoreGroup doesn't use `this.onDispatch`. * It use `commit` insteadof receive data via `this.onDispatch`. */ commit(commitment: Commitment): void { const payload = commitment.payload; const meta = commitment.meta; const debugId = commitment.debugId; if (isTransactionBeganPayload(payload)) { // TODO: lock emitChange this.isTransactionWorking = true; } else if (!meta.isTrusted) { this.tryToUpdateState(payload, meta, debugId); } else if (isErrorPayload(payload)) { this.tryToUpdateState(payload, meta, debugId); } else if (isWillExecutedPayload(payload) && meta.useCase) { this._workingUseCaseMap.set(meta.useCase.id, true); } else if (isDidExecutedPayload(payload) && meta.useCase) { if (meta.isUseCaseFinished) { this._finishedUseCaseMap.set(meta.useCase.id, true); } this.tryToUpdateState(payload, meta, debugId); } else if (isCompletedPayload(payload) && meta.useCase && meta.isUseCaseFinished) { // if the useCase is already finished, doesn't emitChange in CompletedPayload // In other word, If the UseCase that return non-promise value, doesn't emitChange in CompletedPayload if (this._finishedUseCaseMap.has(meta.useCase.id)) { this._finishedUseCaseMap.delete(meta.useCase.id); // clean up about this UseCase this._workingUseCaseMap.delete(meta.useCase.id); return; } // if the UseCase#execute has async behavior, try to update before actual completed this.tryToUpdateState(payload, meta, debugId); // Now, this UseCase actual finish this._workingUseCaseMap.delete(meta.useCase.id); } else if (isTransactionEndedPayload(payload)) { // TODO: unlock emitChange this.isTransactionWorking = false; // try to emitChange after finish the transaction this.emitChangeIfStateIsChange(payload, meta); } } useStrict() { this.isStrictMode = true; } // read -> emitChange if needed private emitChangeIfStateIsChange(payload?: Payload, meta?: DispatcherPayloadMeta): void { this._pruneChangingStateOfStores(); const nextState = this.readPhaseInRead(this.stores); if (!this.shouldStateUpdate(this.state, nextState)) { return; } this.state = nextState; const changingStores = this._changingStores.slice(); // the reason details of this change const details: StoreGroupReasonForChange | undefined = payload && meta ? { payload, meta } : undefined; // emit changes this.storeGroupChangeEvent.emit({ stores: changingStores, details }); } /** * Observe changes of the store group. * * For example, the user can change store using `Store#setState` manually. * In this case, the `details` is defined and report. * * Contrast, almin try to update store in a lifecycle(didUseCase, completeUseCase etc...). * In this case, the `details` is not defined and report. * * StoreGroup#onChange workflow: https://code2flow.com/mHFviS */ onChange(handler: (stores: Array<Store<T>>, details?: StoreGroupReasonForChange) => void): () => void { const releaseHandler = this.storeGroupChangeEvent.addEventListener((event) => handler(event.stores, event.details) ); this._releaseHandlers.push(releaseHandler); return releaseHandler; } /** * Release all events handler. * You can call this when no more call event handler */ release(): void { this._releaseHandlers.forEach((releaseHandler) => releaseHandler()); this._releaseHandlers.length = 0; this._pruneChangingStateOfStores(); } /** * register store and listen onChange. * If you release store, and do call `release` method. */ private _registerStore(store: Store<T>): () => void { const onChangeHandler = () => { if (process.env.NODE_ENV !== "production") { const prevState = this._stateCacheMap.get(store); const nextState = store.getState(); // mark `store` as `emitChange`ed store in a UseCase life-cycle this.storeGroupEmitChangeChecker.mark(store, prevState, nextState); if (this.isStrictMode) { // warning if this store is not allowed update at the time this.storeGroupChangingStoreStrictChecker.warningIfStoreIsNotAllowedUpdate(store); } } // if not exist working UseCases, immediate invoke emitChange. if (!this.existWorkingUseCase) { this.emitChangeIfStateIsChange(); } }; if (process.env.NODE_ENV !== "production") { (onChangeHandler as any).displayName = `${store.name}#onChange->handler`; } return store.onChange(onChangeHandler); } private _addChangingStateOfStores(store: Store<T>) { if (this._changingStores.indexOf(store) === -1) { this._changingStores.push(store); } } private _pruneChangingStateOfStores() { this._changingStores = []; } }
the_stack
import { ClientType, ExtensionClient, ColonyClientV6, getLogs, getBlockTime, MotionState as NetworkMotionState, getEvents, getMultipleEvents, ROOT_DOMAIN_ID, } from '@colony/colony-js'; import { bigNumberify, LogDescription, hexStripZeros } from 'ethers/utils'; import { AddressZero } from 'ethers/constants'; import { Resolvers } from '@apollo/client'; import { Context } from '~context/index'; import { createAddress } from '~utils/web3'; import { getMotionActionType, getMotionState } from '~utils/events'; import { MotionVote, getMotionRequiredStake, getEarlierEventTimestamp, } from '~utils/colonyMotions'; import { ColonyAndExtensionsEvents } from '~types/index'; import { UserReputationQuery, UserReputationQueryVariables, UserReputationDocument, } from '~data/index'; import { ActionsPageFeedType, SystemMessage, SystemMessagesName, } from '~dashboard/ActionsPageFeed'; import { availableRoles } from '~dashboard/PermissionManagementDialog'; import { DEFAULT_NETWORK_TOKEN } from '~constants'; import { ProcessedEvent } from './colonyActions'; const getMotionEvents = async ( votingReputationClient: ExtensionClient, motionId: string, ) => { const motionStakedLogs = await getLogs( votingReputationClient, // @TODO Add missing types to colonyjs // @ts-ignore votingReputationClient.filters.MotionStaked(motionId, null, null, null), ); const motionFinalizedLogs = await getLogs( votingReputationClient, // @TODO Add missing types to colonyjs // @ts-ignore votingReputationClient.filters.MotionFinalized(motionId, null, null), ); const motionStakeClaimedLogs = await getLogs( votingReputationClient, // @TODO Add missing types to colonyjs // @ts-ignore votingReputationClient.filters.MotionRewardClaimed(motionId, null, null), ); const parsedMotionEvents = await Promise.all( [ ...motionStakedLogs, ...motionFinalizedLogs, ...motionStakeClaimedLogs, ].map(async (log) => { const parsedLog = votingReputationClient.interface.parseLog(log); const { address, blockHash, blockNumber, transactionHash } = log; const { name, values: { amount, ...rest }, } = parsedLog; const stakeAmount = name === ColonyAndExtensionsEvents.MotionStaked ? amount : null; return { type: ActionsPageFeedType.NetworkEvent, name, values: { ...rest, stakeAmount, }, createdAt: blockHash ? await getBlockTime(votingReputationClient.provider, blockHash) : 0, emmitedBy: ClientType.VotingReputationClient, address, blockNumber, transactionHash, } as ProcessedEvent; }), ); const sortedMotionEvents = parsedMotionEvents.sort( (firstEvent, secondEvent) => firstEvent.createdAt - secondEvent.createdAt, ); const firstMotionStakedNAYEvent = sortedMotionEvents.find( (event) => event.name === ColonyAndExtensionsEvents.MotionStaked && event.values.vote.eq(MotionVote.Nay), ); if (firstMotionStakedNAYEvent) { const { values, address, blockNumber, transactionHash, } = firstMotionStakedNAYEvent; sortedMotionEvents.push({ type: ActionsPageFeedType.NetworkEvent, name: ColonyAndExtensionsEvents.ObjectionRaised, /* * @NOTE: I substract 1 second out of the timestamp * to make the event appear before the first NAY stake */ createdAt: getEarlierEventTimestamp(firstMotionStakedNAYEvent.createdAt), values, emmitedBy: ClientType.VotingReputationClient, address, blockNumber, transactionHash, }); } return sortedMotionEvents; }; const getTimeoutPeriods = async (colonyManager, colonyAddress, motionId) => { try { const extensionClient = await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, ); const { networkClient } = colonyManager; const blockTime = (await getBlockTime(networkClient.provider, 'latest')) || 0; const escalationPeriod = await extensionClient.getEscalationPeriod(); const { events } = await extensionClient.getMotion(motionId); const timeLeftToStake = events[0] * 1000 - blockTime; const timeLeftToSubmit = events[1] * 1000 - blockTime; const timeLeftToReveal = events[2] * 1000 - blockTime; const timeLeftToEscalate = timeLeftToReveal + escalationPeriod.toNumber() * 1000; return { __typename: 'MotionTimeoutPeriods', timeLeftToStake: timeLeftToStake > 0 ? timeLeftToStake : 0, timeLeftToSubmit: timeLeftToSubmit > 0 ? timeLeftToSubmit : 0, timeLeftToReveal: timeLeftToReveal > 0 ? timeLeftToReveal : 0, timeLeftToEscalate: timeLeftToEscalate > 0 ? timeLeftToEscalate : 0, }; } catch (error) { console.error('Could not get Voting Reputation extension period values'); console.error(error); return null; } }; export const motionsResolvers = ({ colonyManager: { networkClient }, colonyManager, apolloClient, }: Required<Context>): Resolvers => ({ Query: { async motionStakes(_, { colonyAddress, userAddress, motionId }) { try { const colonyClient = (await colonyManager.getClient( ClientType.ColonyClient, colonyAddress, )) as ColonyClientV6; const votingReputationClient = await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, ); const { skillRep, stakes, domainId, rootHash, } = await votingReputationClient.getMotion(motionId); const { skillId } = await colonyClient.getDomain(domainId); const { reputationAmount, } = await colonyClient.getReputationWithoutProofs( skillId, userAddress, rootHash, ); // @NOTE There's no prettier compatible solution to this :( // eslint-disable-next-line max-len const totalStakeFraction = await votingReputationClient.getTotalStakeFraction(); // eslint-disable-next-line max-len const userMinStakeFraction = await votingReputationClient.getUserMinStakeFraction(); const [totalNAYStakes, totalYAYStaked] = stakes; const requiredStake = getMotionRequiredStake( skillRep, totalStakeFraction, 18, ); const remainingToFullyYayStaked = requiredStake.sub(totalYAYStaked); const remainingToFullyNayStaked = requiredStake.sub(totalNAYStakes); const userMinStakeAmount = skillRep .mul(totalStakeFraction) .mul(userMinStakeFraction) /* * @NOTE 36 in here has a reason. * Both totalStakeFraction and userMinStakeFraction are fixed point 18 * meaning they both divide by 10 to the power of 18 * * So since we've multiplied by both, we need to divide by * 10 to the power of 18 times 2 */ .div(bigNumberify(10).pow(36)); return { totalNAYStakes: totalNAYStakes.toString(), remainingToFullyYayStaked: remainingToFullyYayStaked.toString(), remainingToFullyNayStaked: remainingToFullyNayStaked.toString(), maxUserStake: reputationAmount.toString(), minUserStake: userMinStakeAmount.toString(), }; } catch (error) { console.error(error); return null; } }, async motionsSystemMessages(_, { motionId, colonyAddress }) { const { provider } = networkClient; const votingReputationClient = (await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, )) as ExtensionClient; const motion = await votingReputationClient.getMotion(motionId); const motionNetworkState = await votingReputationClient.getMotionState( motionId, ); const { domainId: motionDomainId } = motion; const systemMessages: SystemMessage[] = []; // @TODO Add missing types to colonyjs // @ts-ignore const motionStakedFilter = votingReputationClient.filters.MotionStaked( motionId, null, null, null, ); const motionStakedLogs = await getLogs( votingReputationClient, motionStakedFilter, ); // @ts-ignore // eslint-disable-next-line max-len const motionVoteSubmittedFilter = votingReputationClient.filters.MotionVoteSubmitted( motionId, null, ); const motionVoteSubmittedLogs = await getLogs( votingReputationClient, motionVoteSubmittedFilter, ); // @ts-ignore // eslint-disable-next-line max-len const motionVoteRevealedFilter = votingReputationClient.filters.MotionVoteRevealed( motionId, null, null, ); const motionVoteRevealedLogs = await getLogs( votingReputationClient, motionVoteRevealedFilter, ); const parsedEvents = await Promise.all( [ ...motionStakedLogs, ...motionVoteRevealedLogs, ...motionVoteSubmittedLogs, ].map(async (log) => { const parsedLog = votingReputationClient.interface.parseLog(log); const { address, blockHash, blockNumber, transactionHash } = log; const { name, values } = parsedLog; return { type: ActionsPageFeedType.NetworkEvent, name, values, createdAt: blockHash ? await getBlockTime(provider, blockHash) : 0, emmitedBy: ClientType.ColonyClient, address, blockNumber, transactionHash, } as ProcessedEvent; }), ); const sortedEvents = parsedEvents.sort( (firstEvent, secondEvent) => secondEvent.createdAt - firstEvent.createdAt, ); const blocktime = await getBlockTime(networkClient.provider, 'latest'); const timeToSubmitMS = motion.events[1].toNumber() * 1000; const timeToSubmitInPast = timeToSubmitMS < blocktime; const newestVoteSubmittedEvent = sortedEvents.find( (event) => event.name === ColonyAndExtensionsEvents.MotionVoteSubmitted, ); // eslint-disable-next-line max-len const totalStakeFraction = await votingReputationClient.getTotalStakeFraction(); const requiredStake = getMotionRequiredStake( motion.skillRep, totalStakeFraction, 18, ); const latestMotionStakedYAYEvent = sortedEvents.find( (event) => event.name === ColonyAndExtensionsEvents.MotionStaked && event.values.vote.eq(MotionVote.Yay), ); const latestMotionStakedNAYEvent = sortedEvents.find( (event) => event.name === ColonyAndExtensionsEvents.MotionStaked && event.values.vote.eq(MotionVote.Nay), ); if (latestMotionStakedNAYEvent) { if (motion.stakes[MotionVote.Nay].gte(requiredStake)) { if ( (motion.stakes[MotionVote.Yay].eq(motion.stakes[MotionVote.Nay]) && latestMotionStakedYAYEvent && latestMotionStakedNAYEvent.createdAt < latestMotionStakedYAYEvent.createdAt) || motion.stakes[MotionVote.Nay].gt(motion.stakes[MotionVote.Yay]) ) { systemMessages.push({ type: ActionsPageFeedType.SystemMessage, name: SystemMessagesName.ObjectionFullyStaked, createdAt: latestMotionStakedNAYEvent.createdAt, }); } } } if (latestMotionStakedYAYEvent) { if (motion.stakes[MotionVote.Yay].gte(requiredStake)) { if ( motion.stakes[MotionVote.Yay].eq(motion.stakes[MotionVote.Nay]) && latestMotionStakedNAYEvent && latestMotionStakedNAYEvent.createdAt < latestMotionStakedYAYEvent.createdAt ) { systemMessages.push({ type: ActionsPageFeedType.SystemMessage, name: SystemMessagesName.MotionFullyStakedAfterObjection, createdAt: latestMotionStakedYAYEvent.createdAt, }); } else { systemMessages.push({ type: ActionsPageFeedType.SystemMessage, name: SystemMessagesName.MotionFullyStaked, createdAt: latestMotionStakedYAYEvent.createdAt, }); } } } if ( motionNetworkState === NetworkMotionState.Reveal || timeToSubmitInPast ) { if (newestVoteSubmittedEvent) { systemMessages.push({ type: ActionsPageFeedType.SystemMessage, name: SystemMessagesName.MotionRevealPhase, createdAt: timeToSubmitMS, }); } } if ( motionNetworkState === NetworkMotionState.Submit || newestVoteSubmittedEvent ) { systemMessages.push({ type: ActionsPageFeedType.SystemMessage, name: SystemMessagesName.MotionVotingPhase, createdAt: motion.events[0].toNumber() * 1000, }); } if ( motionNetworkState === NetworkMotionState.Closed && !motionDomainId.eq(ROOT_DOMAIN_ID) ) { systemMessages.push({ type: ActionsPageFeedType.SystemMessage, name: SystemMessagesName.MotionCanBeEscalated, /* * @NOTE We can just use the current time, since this is the last entry * in the feed */ createdAt: blocktime, }); } if ( motionNetworkState === NetworkMotionState.Finalizable || motionNetworkState === NetworkMotionState.Finalized ) { const newestStakeOrVoteEvent = sortedEvents.find( (event) => event.name === ColonyAndExtensionsEvents.MotionStaked || event.name === ColonyAndExtensionsEvents.MotionVoteRevealed, ); if (newestStakeOrVoteEvent) { if ( motion.votes[0].lt(motion.votes[1]) || motion.stakes[0].lt(motion.stakes[1]) ) { systemMessages.push({ type: ActionsPageFeedType.SystemMessage, name: SystemMessagesName.MotionHasPassed, createdAt: getEarlierEventTimestamp( newestStakeOrVoteEvent.createdAt, -5, ), }); } } } if ( motionNetworkState === NetworkMotionState.Finalizable || motionNetworkState === NetworkMotionState.Finalized ) { const newestVoteRevealed = sortedEvents.find( (event) => event.name === ColonyAndExtensionsEvents.MotionVoteRevealed, ); if (newestVoteRevealed) { if (motion.votes[0].gte(motion.votes[1])) { systemMessages.push({ type: ActionsPageFeedType.SystemMessage, name: SystemMessagesName.MotionRevealResultObjectionWon, createdAt: getEarlierEventTimestamp( newestVoteRevealed.createdAt, -1, ), }); systemMessages.push({ type: ActionsPageFeedType.SystemMessage, name: SystemMessagesName.MotionHasFailedFinalizable, createdAt: getEarlierEventTimestamp( newestVoteRevealed.createdAt, -5, ), }); } else { systemMessages.push({ type: ActionsPageFeedType.SystemMessage, name: SystemMessagesName.MotionRevealResultMotionWon, createdAt: getEarlierEventTimestamp( newestVoteRevealed.createdAt, -1, ), }); } } else if ( motion.votes[0].gte(motion.votes[1]) && motion.stakes[0].gte(motion.stakes[1]) ) { systemMessages.push({ type: ActionsPageFeedType.SystemMessage, name: SystemMessagesName.MotionHasFailedFinalizable, createdAt: motion.events[2].toNumber() * 1000, }); } } if (motionNetworkState === NetworkMotionState.Failed) { systemMessages.push({ type: ActionsPageFeedType.SystemMessage, name: SystemMessagesName.MotionHasFailedNotFinalizable, createdAt: motion.events[1].toNumber() * 1000, }); } return Promise.all(systemMessages); }, async motionVoterReward(_, { motionId, colonyAddress, userAddress }) { try { const votingReputationClient = await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, ); const { domainId, rootHash } = await votingReputationClient.getMotion( motionId, ); const state = await votingReputationClient.getMotionState(motionId); const { data } = await apolloClient.query< UserReputationQuery, UserReputationQueryVariables >({ query: UserReputationDocument, variables: { colonyAddress, address: userAddress, domainId: domainId.toNumber(), rootHash, }, }); if (data?.userReputation) { let reward = bigNumberify(0); let minReward = bigNumberify(0); let maxReward = bigNumberify(0); if (state === NetworkMotionState.Submit) { try { const [ minUserReward, maxUserReward, ] = await votingReputationClient.getVoterRewardRange( bigNumberify(motionId), bigNumberify(data.userReputation), createAddress(userAddress), ); minReward = minUserReward; maxReward = maxUserReward; } catch (error) { /* getVoterRewardRange return error if no-one has voted yet or user in question has no reputaiton. */ } } else { reward = await votingReputationClient.getVoterReward( bigNumberify(motionId), bigNumberify(data.userReputation), ); } return { reward: reward.toString(), minReward: minReward.toString(), maxReward: maxReward.toString(), }; } return null; } catch (error) { console.error('Could not fetch users vote reward'); console.error(error); return null; } }, async eventsForMotion(_, { motionId, colonyAddress }) { try { const votingReputationClient = (await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, )) as ExtensionClient; return await getMotionEvents(votingReputationClient, motionId); } catch (error) { console.error(error); return []; } }, async motionCurrentUserVoted(_, { motionId, colonyAddress, userAddress }) { try { const votingReputationClient = await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, ); // @ts-ignore // eslint-disable-next-line max-len const motionVoteFilter = votingReputationClient.filters.MotionVoteSubmitted( bigNumberify(motionId), userAddress, ); const voteSubmittedEvents = await getEvents( votingReputationClient, motionVoteFilter, ); return !!voteSubmittedEvents.length; } catch (error) { console.error('Could not fetch current user vote status'); console.error(error); return null; } }, async motionUserVoteRevealed(_, { motionId, colonyAddress, userAddress }) { try { let userVote = { revealed: false, vote: null, }; const votingReputationClient = await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, ); // @ts-ignore // eslint-disable-next-line max-len const motionVoteRevealedFilter = votingReputationClient.filters.MotionVoteRevealed( bigNumberify(motionId), userAddress, null, ); const [userReveal] = await getEvents( votingReputationClient, motionVoteRevealedFilter, ); if (userReveal) { userVote = { revealed: true, vote: userReveal.values.vote.toNumber(), }; } return userVote; } catch (error) { console.error('Could not fetch user vote revealed state'); console.error(error); return null; } }, async motionVoteResults(_, { motionId, colonyAddress, userAddress }) { try { const voteResult: { currentUserVoteSide: number | null; yayVotes: string | null; yayVoters: string[]; nayVotes: string | null; nayVoters: string[]; } = { currentUserVoteSide: null, yayVotes: null, yayVoters: [], nayVotes: null, nayVoters: [], }; const votingReputationClient = await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, ); const { votes } = await votingReputationClient.getMotion(motionId); voteResult.yayVotes = votes[1].toString(); voteResult.nayVotes = votes[0].toString(); // @ts-ignore // eslint-disable-next-line max-len const motionVoteRevealedFilter = votingReputationClient.filters.MotionVoteRevealed( bigNumberify(motionId), null, null, ); const revealEvents = await getEvents( votingReputationClient, motionVoteRevealedFilter, ); revealEvents?.map(({ values: { vote, voter } }) => { const currentUserVoted = createAddress(voter) === createAddress(userAddress); /* * @NOTE We're using this little hack in order to ensure, that if * the currently logged in user was one of the voters, that * their avatar is going to show up first in the vote results */ const arrayMethod = currentUserVoted ? 'unshift' : 'push'; if (currentUserVoted) { voteResult.currentUserVoteSide = vote.toNumber(); } if (vote.toNumber() === MotionVote.Yay) { voteResult.yayVoters[arrayMethod](createAddress(voter)); } /* * @NOTE We expressly declare NAY rather then using "else" to prevent * any other *unexpected* values coming from the chain messing up our * data (eg if vote was 2 due to weird issues) */ if (vote.toNumber() === MotionVote.Nay) { voteResult.nayVoters[arrayMethod](createAddress(voter)); } }); return voteResult; } catch (error) { console.error('Could not fetch motion voting results'); console.error(error); return null; } }, async votingState(_, { colonyAddress, motionId }) { try { const votingReputationClient = await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, ); const { skillRep, repSubmitted, } = await votingReputationClient.getMotion(motionId); // eslint-disable-next-line max-len const maxVoteFraction = await votingReputationClient.getMaxVoteFraction(); const thresholdValue = getMotionRequiredStake( skillRep, maxVoteFraction, 18, ); return { thresholdValue: thresholdValue.toString(), totalVotedReputation: repSubmitted.toString(), skillRep: skillRep.toString(), }; } catch (error) { console.error(error); return null; } }, async motionStatus(_, { motionId, colonyAddress }) { try { const votingReputationClient = await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, ); const motion = await votingReputationClient.getMotion(motionId); const motionState = await votingReputationClient.getMotionState( motionId, ); return getMotionState( motionState, votingReputationClient as ExtensionClient, motion, ); } catch (error) { console.error('Could not fetch motion state'); console.error(error); return null; } }, async motionFinalized(_, { motionId, colonyAddress }) { try { const votingReputationClient = await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, ); const { finalized } = await votingReputationClient.getMotion(motionId); return finalized; } catch (error) { console.error('Could not fetch motion finalized state'); console.error(error); return null; } }, async motionStakerReward(_, { motionId, colonyAddress, userAddress }) { try { let stakerReward: { stakingRewardYay: string | null; stakingRewardNay: string | null; stakesYay: string | null; stakesNay: string | null; claimedReward: boolean | null; } = { stakingRewardYay: null, stakingRewardNay: null, stakesYay: null, stakesNay: null, claimedReward: null, }; const votingReputationClient = await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, ); const motionStakedFilter = votingReputationClient.filters.MotionStaked( bigNumberify(motionId), userAddress.toLowerCase(), null, ); // eslint-disable-next-line max-len const stakeClaimedFilter = votingReputationClient.filters.MotionRewardClaimed( bigNumberify(motionId), userAddress.toLowerCase(), null, null, ); const events = await getMultipleEvents(votingReputationClient, [ motionStakedFilter, stakeClaimedFilter, ]); const userStakeEvents = events.filter( ({ name }) => name === ColonyAndExtensionsEvents.MotionStaked, ); const rewardClaimedEvents = events.filter( ({ name }) => name === ColonyAndExtensionsEvents.MotionRewardClaimed, ); let stakesYay = bigNumberify(0); let stakesNay = bigNumberify(0); userStakeEvents.map(({ values: { amount, vote } }) => { if (vote.toNumber() === 1) { stakesYay = stakesYay.add(amount); return stakesYay; } stakesNay = stakesNay.add(amount); return stakesNay; }); /* * @NOTE We need to do a little bit of try/catch trickery here because of * the way the contracts function * * If **anyone** staked on a side, calling the rewards function (even for * a user who didnd't stake) returns 0 * * But calling the rewards function on a side where **no one** has voted * will result in an error being thrown. * * For this we initialize both with zero, call them both in a try/catch * block. If they succeed, they overwrite their initial valiues, if they * fail, they fall back to the initial 0. */ let stakingRewardYay = bigNumberify(0); let stakingRewardNay = bigNumberify(0); try { [stakingRewardYay] = await votingReputationClient.getStakerReward( motionId, userAddress, 1, ); } catch (error) { /* * We don't care to catch the error since we fallback to it's initial value */ // silent error } try { [stakingRewardNay] = await votingReputationClient.getStakerReward( motionId, userAddress, 0, ); } catch (error) { /* * We don't care to catch the error since we fallback to it's initial value */ // silent error } /* * @NOTE If we claimed the rewards, than `getStakerReward` will return 0 * (since we already claimed the reward, hence no more reward left). * * To be able to display the "original" value of the reward, we need to * parse the claim reward events */ rewardClaimedEvents.map(({ values: { amount, vote } }) => { if (vote.toNumber() === 1) { stakingRewardYay = amount; return stakingRewardYay; } stakingRewardNay = amount; return stakingRewardNay; }); stakerReward = { stakingRewardYay: stakingRewardYay.toString(), stakingRewardNay: stakingRewardNay.toString(), stakesYay: stakesYay.toString(), stakesNay: stakesNay.toString(), claimedReward: !!rewardClaimedEvents.length, }; return stakerReward; } catch (error) { console.error('Could not fetch the rewards for the current staker'); console.error(error); return null; } }, async motionObjectionAnnotation(_, { motionId, colonyAddress }) { let objectionAnnotation = { address: null, metadata: null, }; try { const colonyClient = await colonyManager.getClient( ClientType.ColonyClient, colonyAddress, ); const votingReputationClient = await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, ); const nayStakedFilter = votingReputationClient.filters.MotionStaked( bigNumberify(motionId), null, bigNumberify(0), null, ); const nayStakeEvents = await getLogs( votingReputationClient, nayStakedFilter, ); let annotationEvents: LogDescription[] = []; await Promise.all( nayStakeEvents.map(async ({ transactionHash }) => { const events = await getEvents( colonyClient, colonyClient.filters.Annotation(null, transactionHash, null), ); annotationEvents = [...annotationEvents, ...events]; }), ); if (annotationEvents.length) { const [latestAnnotatedNayStake] = annotationEvents; objectionAnnotation = { address: latestAnnotatedNayStake.values.agent, metadata: latestAnnotatedNayStake.values.metadata, }; } return objectionAnnotation; } catch (error) { console.error('Could not nay side stake annotation for current motion'); console.error(error); return null; } }, async motionTimeoutPeriods(_, { colonyAddress, motionId }) { return getTimeoutPeriods(colonyManager, colonyAddress, motionId); }, }, Motion: { async state({ fundamentalChainId, associatedColony: { colonyAddress } }) { const motionId = bigNumberify(fundamentalChainId); const votingReputationClient = await colonyManager.getClient( ClientType.VotingReputationClient, createAddress(colonyAddress), ); const motion = await votingReputationClient.getMotion(motionId); const state = await votingReputationClient.getMotionState(motionId); return getMotionState( state, votingReputationClient as ExtensionClient, motion, ); }, async type({ fundamentalChainId, associatedColony: { colonyAddress: address }, }) { const colonyAddress = createAddress(address); const votingReputationClient = await colonyManager.getClient( ClientType.VotingReputationClient, colonyAddress, ); const oneTxPaymentClient = await colonyManager.getClient( ClientType.OneTxPaymentClient, colonyAddress, ); const colonyClient = await colonyManager.getClient( ClientType.ColonyClient, colonyAddress, ); return getMotionActionType( votingReputationClient as ExtensionClient, oneTxPaymentClient as ExtensionClient, colonyClient, bigNumberify(fundamentalChainId), ); }, async timeoutPeriods({ fundamentalChainId: motionId, associatedColony: { colonyAddress }, }) { return getTimeoutPeriods(colonyManager, colonyAddress, motionId); }, async args({ action, associatedColony: { colonyAddress } }) { const colonyClient = await colonyManager.getClient( ClientType.ColonyClient, colonyAddress, ); const actionValues = colonyClient.interface.parseTransaction({ data: action, }); const tokenAddress = colonyClient.tokenClient.address; const { symbol, decimals, } = await colonyClient.tokenClient.getTokenInfo(); const defaultValues = { amount: '0', token: { id: tokenAddress, symbol, decimals, }, }; // PaymentMotion if (!actionValues) { const oneTxPaymentClient = await colonyManager.getClient( ClientType.OneTxPaymentClient, colonyAddress, ); const paymentValues = oneTxPaymentClient.interface.parseTransaction({ data: action, }); if ( !paymentValues || paymentValues.signature !== 'makePaymentFundedFromDomain(uint256,uint256,uint256,uint256,address[],address[],uint256[],uint256,uint256)' // eslint-disable-line max-len ) { return defaultValues; } const [ , , , , [recipient], [paymentTokenAddress], [paymentAmount], ] = paymentValues?.args; /* * If the payment was made with the native chain's token. Eg: Xdai or Eth */ if (paymentTokenAddress === AddressZero) { return { amount: paymentAmount.toString(), recipient, token: { id: AddressZero, symbol: DEFAULT_NETWORK_TOKEN.symbol, decimals: DEFAULT_NETWORK_TOKEN.decimals, }, }; } /* * Otherwise the payment was made with the native token's address, or an * equally similar ERC20 token */ let tokenClient; try { tokenClient = await colonyManager.getTokenClient(paymentTokenAddress); } catch (error) { /* * If this try/catch block triggers it means that we have a non-standard * ERC-20 token, which we can't handle * For that, we will just replace the values with the colony's native token */ tokenClient = await colonyManager.getTokenClient(tokenAddress); } const { symbol: paymentTokenSymbol, decimals: paymentTokenDecimals, } = await tokenClient.getTokenInfo(); return { amount: paymentAmount.toString(), recipient, token: { id: tokenClient.address, symbol: paymentTokenSymbol, decimals: paymentTokenDecimals, }, }; } if ( actionValues.signature === 'moveFundsBetweenPots(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,address)' // eslint-disable-line max-len ) { const fromDomain = await colonyClient.getDomainFromFundingPot( actionValues.args[5], ); const toDomain = await colonyClient.getDomainFromFundingPot( actionValues.args[6], ); const tokenClient = await colonyManager.getTokenClient( actionValues.args[8], ); const tokenInfo = await tokenClient.getTokenInfo(); return { amount: actionValues.args[7].toString(), fromDomain: fromDomain.toNumber(), toDomain: toDomain.toNumber(), token: { id: actionValues.args[8], symbol: tokenInfo.symbol, decimals: tokenInfo.decimals, }, }; } if (actionValues.name === 'addDomain') { return { ...defaultValues, metadata: actionValues.args[3], }; } if ( actionValues.signature === 'editDomain(uint256,uint256,uint256,string)' ) { return { ...defaultValues, fromDomain: parseInt(actionValues.args[2].toString(), 10), }; } if (actionValues.name === 'editColony') { return { ...defaultValues, metadata: actionValues.args[0], }; } if ( actionValues.signature === 'setUserRoles(uint256,uint256,address,uint256,bytes32)' ) { const roleBitMask = parseInt( hexStripZeros(actionValues.args[4]), 16, ).toString(2); const roleBitMaskArray = roleBitMask.split('').reverse(); const roles = availableRoles.map((role) => ({ id: role, setTo: roleBitMaskArray[role] === '1', })); return { ...defaultValues, recipient: actionValues.args[2], fromDomain: bigNumberify(actionValues.args[3]).toNumber(), roles, }; } // MintTokenMotion - default return { amount: bigNumberify(actionValues?.args[0] || '0').toString(), token: { id: tokenAddress, symbol, decimals, }, }; }, }, });
the_stack
import * as vscode from "vscode"; import { Context, Selections } from "."; import type { Input, SetInput } from "../commands"; import { CancellationError } from "../utils/errors"; const actionEvent = new vscode.EventEmitter<Parameters<typeof prompt.notifyActionRequested>[0]>(); /** * Displays a prompt to the user. */ export function prompt( options: prompt.Options, context = Context.WithoutActiveEditor.current, ) { if (options.value === undefined && options.history !== undefined && options.history.length > 0) { options.value = options.history[options.history.length - 1]; } const inputBox = vscode.window.createInputBox(); const promise = new Promise<string>((resolve, reject) => { // Ported from // https://github.com/microsoft/vscode/blob/14f61093f4312f7730135b9bc4bd97472e58ce04/src/vs/base/parts/quickinput/browser/quickInput.ts#L1465 // // We can't use `showInputBox` because we may need to edit the text of the // box while it is open, so we do everything manually below. const token = context.cancellationToken; if (token.isCancellationRequested) { return reject(new CancellationError(CancellationError.Reason.CancellationToken)); } const validateInput = options.validateInput ?? (() => Promise.resolve(undefined)); let validationValue = options.value ?? "", validation = Promise.resolve(validateInput(validationValue)); let historyIndex = options.history?.length, lastHistoryValue = validationValue; function updateAndValidateValue(value: string, setValue = false) { if (setValue) { inputBox.value = value; } if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then((result) => { if (value === validationValue) { inputBox.validationMessage = result ?? undefined; } }); } const disposables = [ inputBox, inputBox.onDidChangeValue(updateAndValidateValue), inputBox.onDidAccept(() => { const value = inputBox.value; if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then((result) => { if (result == null) { const history = options.history, historySize = options.historySize ?? 50; if (history !== undefined) { const existingIndex = history.indexOf(value); if (existingIndex !== -1) { history.splice(existingIndex, 1); } history.push(value); if (history.length > historySize) { history.shift(); } } resolve(value); inputBox.hide(); } else if (value === validationValue) { inputBox.validationMessage = result ?? undefined; } }); }), token.onCancellationRequested(() => { inputBox.hide(); }), inputBox.onDidHide(() => { disposables.forEach((d) => d.dispose()); const reason = context.cancellationToken?.isCancellationRequested ? CancellationError.Reason.CancellationToken : CancellationError.Reason.PressedEscape; // Note: ignored if resolve() was previously called with a valid value. reject(new CancellationError(reason)); }), actionEvent.event((action) => { switch (action) { case "clear": updateAndValidateValue("", /* setValue= */ true); break; case "next": if (historyIndex !== undefined) { if (historyIndex === options.history!.length) { return; } historyIndex++; if (historyIndex === options.history!.length) { updateAndValidateValue(lastHistoryValue, /* setValue= */ true); } else { updateAndValidateValue(options.history![historyIndex], /* setValue= */ true); } } break; case "previous": if (historyIndex !== undefined) { if (historyIndex === 0) { return; } if (historyIndex === options.history!.length) { lastHistoryValue = inputBox.value; } historyIndex--; updateAndValidateValue(options.history![historyIndex], /* setValue= */ true); } break; } }), ]; updateAndValidateValue(options.value ?? "", /* setValue= */ true); inputBox.title = options.title; inputBox.prompt = options.prompt; inputBox.placeholder = options.placeHolder; inputBox.password = !!options.password; inputBox.ignoreFocusOut = !!options.ignoreFocusOut; // Hack to set the `valueSelection`, since it isn't supported when using // `createInputBox`. if (options.valueSelection !== undefined) { (inputBox as any).update({ valueSelection: options.valueSelection }); } inputBox.show(); }); return context.wrap(promise); } export namespace prompt { type RegExpFlag = "m" | "u" | "s" | "y" | "i" | "g"; type RegExpFlags = RegExpFlag | `${RegExpFlag}${RegExpFlag}` | `${RegExpFlag}${RegExpFlag}${RegExpFlag}` | `${RegExpFlag}${RegExpFlag}${RegExpFlag}${RegExpFlag}`; /** * Options for spawning a `prompt`. */ export interface Options extends vscode.InputBoxOptions { readonly history?: string[]; readonly historySize?: number; } /** * Returns `vscode.InputBoxOptions` that only validate if a number in a given * range is entered. */ export function numberOpts( opts: { integer?: boolean; range?: [number, number] } = {}, ): vscode.InputBoxOptions { return { validateInput(input) { const n = +input; if (isNaN(n)) { return "Invalid number."; } if (opts.range && (n < opts.range[0] || n > opts.range[1])) { return `Number out of range ${JSON.stringify(opts.range)}.`; } if (opts.integer && (n | 0) !== n) { return `Number must be an integer.`; } return; }, }; } /** * Equivalent to `+await prompt(numberOpts(), context)`. */ export function number( opts: Parameters<typeof numberOpts>[0], context = Context.WithoutActiveEditor.current, ) { return prompt(numberOpts(opts), context).then((x) => +x); } /** * Last used inputs for `regexp` prompts. */ export const regexpHistory: string[] = []; /** * Returns `vscode.InputBoxOptions` that only validate if a valid ECMAScript * regular expression is entered. */ export function regexpOpts(flags: RegExpFlags): prompt.Options { return { prompt: "Regular expression", validateInput(input) { if (input.length === 0) { return "RegExp cannot be empty"; } try { new RegExp(input, flags); return undefined; } catch { return "invalid RegExp"; } }, history: regexpHistory, }; } /** * Equivalent to `new RegExp(await prompt(regexpOpts(flags), context), flags)`. */ export function regexp( flags: RegExpFlags, context = Context.WithoutActiveEditor.current, ) { return prompt(regexpOpts(flags), context).then((x) => new RegExp(x, flags)); } /** * Prompts the user for a result interactively. */ export function interactive<T>( compute: (input: string) => T | Thenable<T>, reset: () => void, options: vscode.InputBoxOptions = {}, interactive: boolean = true, ): Thenable<T> { let result: T; const validateInput = options.validateInput; if (!interactive) { return prompt(options).then((value) => compute(value)); } return prompt({ ...options, async validateInput(input) { const validationError = await validateInput?.(input); if (validationError) { return validationError; } try { result = await compute(input); return; } catch (e) { return `${e}`; } }, }).then( () => result, (err) => { reset(); throw err; }, ); } /** * @internal */ export async function manipulateSelectionsInteractively<I, R>( _: Context, input: Input<I>, setInput: SetInput<R>, interactive: boolean, options: prompt.Options, f: (input: string | I, selections: readonly vscode.Selection[]) => Thenable<R>, ) { const selections = _.selections; function execute(input: string | I) { return _.runAsync(() => f(input, selections)); } function undo() { Selections.set(selections); } if (input === undefined) { setInput(await prompt.interactive(execute, undo, options, interactive)); } else { await execute(input); } } export type ListPair = readonly [string, string]; /** * Prompts the user to choose one item among a list of items, and returns the * index of the item that was picked. */ export function one( items: readonly ListPair[], init?: (quickPick: vscode.QuickPick<vscode.QuickPickItem>) => void, context = Context.WithoutActiveEditor.current, ) { return promptInList(false, items, init ?? (() => {}), context.cancellationToken); } export namespace one { /** * Prompts the user for actions in a menu, only hiding it when a * cancellation is requested or `Escape` pressed. */ export function locked( items: readonly (readonly [string, string, () => void])[], init?: (quickPick: vscode.QuickPick<vscode.QuickPickItem>) => void, cancellationToken = Context.WithoutActiveEditor.current.cancellationToken, ) { const itemsKeys = items.map(([k, _]) => k.includes(", ") ? k.split(", ") : [...k]); return new Promise<void>((resolve, reject) => { const quickPick = vscode.window.createQuickPick(), quickPickItems = [] as vscode.QuickPickItem[]; let isCaseSignificant = false; for (let i = 0; i < items.length; i++) { const [label, description] = items[i]; quickPickItems.push({ label, description }); isCaseSignificant = isCaseSignificant || label.toLowerCase() !== label; } quickPick.items = quickPickItems; quickPick.placeholder = "Press one of the below keys."; const subscriptions = [ quickPick.onDidChangeValue((rawKey) => { quickPick.value = ""; // This causes the menu to disappear and reappear for a frame, but // without this the shown items don't get refreshed after the value // change above. quickPick.items = quickPickItems; let key = rawKey; if (!isCaseSignificant) { key = key.toLowerCase(); } const index = itemsKeys.findIndex((x) => x.includes(key)); if (index !== -1) { items[index][2](); } }), quickPick.onDidHide(() => { subscriptions.splice(0).forEach((s) => s.dispose()); resolve(); }), quickPick.onDidAccept(() => { subscriptions.splice(0).forEach((s) => s.dispose()); const picked = quickPick.selectedItems[0]; try { items.find((x) => x[1] === picked.description)![2](); } finally { resolve(); } }), cancellationToken?.onCancellationRequested(() => { subscriptions.splice(0).forEach((s) => s.dispose()); reject(new CancellationError(CancellationError.Reason.CancellationToken)); }), quickPick, ]; init?.(quickPick); quickPick.show(); }); } } /** * Prompts the user to choose many items among a list of items, and returns a * list of indices of picked items. */ export function many( items: readonly ListPair[], init?: (quickPick: vscode.QuickPick<vscode.QuickPickItem>) => void, context = Context.WithoutActiveEditor.current, ) { return promptInList(true, items, init ?? (() => {}), context.cancellationToken); } /** * Notifies an active prompt, if any, that an action has been requested. */ export function notifyActionRequested(action: "next" | "previous" | "clear") { actionEvent.fire(action); } } /** * Awaits a keypress from the user and returns the entered key. */ export function keypress(context = Context.current): Promise<string> { if (context.cancellationToken.isCancellationRequested) { return Promise.reject(new CancellationError(CancellationError.Reason.CancellationToken)); } const previousMode = context.mode; return context.switchToMode(context.extension.modes.inputMode).then(() => new Promise<string>((resolve, reject) => { try { const subscriptions = [ vscode.commands.registerCommand("type", ({ text }: { text: string }) => { if (subscriptions.length > 0) { subscriptions.splice(0).forEach((s) => s.dispose()); context.switchToMode(previousMode).then(() => resolve(text)); } }), context.cancellationToken.onCancellationRequested(() => { if (subscriptions.length > 0) { subscriptions.splice(0).forEach((s) => s.dispose()); context.switchToMode(previousMode) .then(() => reject( new CancellationError( context.extension.cancellationReasonFor(context.cancellationToken) ?? CancellationError.Reason.CancellationToken))); } }), ]; } catch { reject(new Error("unable to listen to keyboard events; is an extension " + 'overriding the "type" command (e.g VSCodeVim)?')); } }), ); } export namespace keypress { /** * Awaits a keypress describing a register and returns the specified register. */ export async function forRegister(context = Context.current) { const firstKey = await keypress(context); if (firstKey !== " ") { return context.extension.registers.get(firstKey); } const secondKey = await keypress(context); return context.extension.registers.forDocument(context.document).get(secondKey); } } function promptInList( canPickMany: true, items: readonly (readonly [string, string])[], init: (quickPick: vscode.QuickPick<vscode.QuickPickItem>) => void, cancellationToken: vscode.CancellationToken, ): Thenable<string | number[]>; function promptInList( canPickMany: false, items: readonly (readonly [string, string])[], init: (quickPick: vscode.QuickPick<vscode.QuickPickItem>) => void, cancellationToken: vscode.CancellationToken, ): Thenable<string | number>; function promptInList( canPickMany: boolean, items: readonly (readonly [string, string])[], init: (quickPick: vscode.QuickPick<vscode.QuickPickItem>) => void, cancellationToken: vscode.CancellationToken, ): Thenable<string | number | number[]> { const itemsKeys = items.map(([k, _]) => k.includes(", ") ? k.split(", ") : [...k]); return new Promise<string | number | number[]>((resolve, reject) => { const quickPick = vscode.window.createQuickPick(), quickPickItems = [] as vscode.QuickPickItem[]; let isCaseSignificant = false; for (let i = 0; i < items.length; i++) { const [label, description] = items[i]; quickPickItems.push({ label, description }); isCaseSignificant = isCaseSignificant || label.toLowerCase() !== label; } quickPick.items = quickPickItems; quickPick.placeholder = "Press one of the below keys."; quickPick.canSelectMany = canPickMany; const subscriptions = [ quickPick.onDidChangeValue((rawKey) => { if (subscriptions.length === 0) { return; } let key = rawKey; if (!isCaseSignificant) { key = key.toLowerCase(); } const index = itemsKeys.findIndex((x) => x.includes(key)); subscriptions.splice(0).forEach((s) => s.dispose()); if (index === -1) { return resolve(rawKey); } if (canPickMany) { resolve([index]); } else { resolve(index); } }), quickPick.onDidAccept(() => { if (subscriptions.length === 0) { return; } let picked = quickPick.selectedItems; if (picked !== undefined && picked.length === 0) { picked = quickPick.activeItems; } subscriptions.splice(0).forEach((s) => s.dispose()); if (picked === undefined) { return reject(new CancellationError(CancellationError.Reason.PressedEscape)); } if (canPickMany) { resolve(picked.map((x) => items.findIndex((item) => item[1] === x.description))); } else { resolve(items.findIndex((x) => x[1] === picked[0].description)); } }), quickPick.onDidHide(() => { if (subscriptions.length === 0) { return; } subscriptions.splice(0).forEach((s) => s.dispose()); reject(new CancellationError(CancellationError.Reason.PressedEscape)); }), cancellationToken?.onCancellationRequested(() => { if (subscriptions.length === 0) { return; } subscriptions.splice(0).forEach((s) => s.dispose()); reject(new CancellationError(CancellationError.Reason.CancellationToken)); }), quickPick, ]; init(quickPick); quickPick.show(); }); }
the_stack
import 'setimmediate'; import path from 'path'; import memfs from 'memfs'; import webpack, {Compiler, Stats} from 'webpack'; import {HEADER, Options, Entrypoint} from '../shared'; import {withWorkspace} from './utilities/workspace'; const BUILD_TIMEOUT = 10000; const DEFAULT_SERVER_FILE_PATH = `${Entrypoint.Server}.js`; const DEFAULT_CLIENT_FILE_PATH = `${Entrypoint.Client}.js`; describe('webpack-plugin', () => { describe('node', () => { it( 'generates the server and client entrypoints when the virtual server & client modules are present', async () => { const name = 'node-no-entrypoints'; await withWorkspace(name, async ({workspace}) => { await workspace.write('index.js', BASIC_JS_MODULE); await workspace.write('webpack.config.js', BASIC_WEBPACK_CONFIG); const [client, server] = await runBuild(name, [ DEFAULT_CLIENT_FILE_PATH, DEFAULT_SERVER_FILE_PATH, ]); expect(client).toBeDefined(); expect(client).toMatch(HEADER); expect(server).toBeDefined(); expect(server).toMatch(HEADER); expect(server).toMatch('port: '); }); }, BUILD_TIMEOUT, ); }); describe('rails', () => { it( 'generates the server and client entrypoints when they do not exist', async () => { const name = 'rails-no-entrypoints'; await withWorkspace(name, async ({workspace}) => { await workspace.write('index.js', BASIC_JS_MODULE); await workspace.write('webpack.config.js', BASIC_WEBPACK_CONFIG); const [client, server] = await runBuild(name, [ DEFAULT_CLIENT_FILE_PATH, DEFAULT_SERVER_FILE_PATH, ]); expect(server).toMatch(HEADER); expect(client).toMatch(HEADER); }); }, BUILD_TIMEOUT, ); it( 'does not use the generated client module when a folder with an index file is present', async () => { const name = 'client-index-entrypoint'; await withWorkspace(name, async ({workspace}) => { await workspace.write('index.js', BASIC_JS_MODULE); await workspace.write('webpack.config.js', BASIC_WEBPACK_CONFIG); await workspace.write('client/index.js', BASIC_ENTRY); const [client, clientIndex, server] = await runBuild(name, [ DEFAULT_CLIENT_FILE_PATH, 'client/index.js', DEFAULT_SERVER_FILE_PATH, ]); expect(server).toMatch(HEADER); expect(client).toBeNull(); expect(clientIndex).toMatch('I am a bespoke entry'); expect(clientIndex).not.toMatch(HEADER); }); }, BUILD_TIMEOUT, ); it( 'does not use the generated client module when a bespoke file is present', async () => { const name = 'client-entrypoint'; await withWorkspace(name, async ({workspace}) => { await workspace.write('index.js', BASIC_JS_MODULE); await workspace.write('webpack.config.js', BASIC_WEBPACK_CONFIG); await workspace.write('client.js', BASIC_ENTRY); const [client, server] = await runBuild(name, [ DEFAULT_CLIENT_FILE_PATH, DEFAULT_SERVER_FILE_PATH, ]); expect(server).toMatch(HEADER); expect(client).toMatch('I am a bespoke entry'); expect(client).not.toMatch(HEADER); }); }, BUILD_TIMEOUT, ); it( 'does not use the generated server module when a bespoke file is present', async () => { const name = 'server-entrypoint'; await withWorkspace(name, async ({workspace}) => { await workspace.write('index.js', BASIC_JS_MODULE); await workspace.write('webpack.config.js', BASIC_WEBPACK_CONFIG); await workspace.write('server.js', BASIC_ENTRY); const [client, server] = await runBuild(name, [ DEFAULT_CLIENT_FILE_PATH, DEFAULT_SERVER_FILE_PATH, ]); expect(server).not.toMatch(HEADER); expect(server).toMatch('I am a bespoke entry'); expect(client).toMatch(HEADER); }); }, BUILD_TIMEOUT, ); it( 'does not use the generated server module when a folder with an index file is present', async () => { const name = 'server-index-entrypoint'; await withWorkspace(name, async ({workspace}) => { await workspace.write('index.js', BASIC_JS_MODULE); await workspace.write('webpack.config.js', BASIC_WEBPACK_CONFIG); await workspace.write('server/index.js', BASIC_ENTRY); const [client, server, serverIndex] = await runBuild(name, [ DEFAULT_CLIENT_FILE_PATH, DEFAULT_SERVER_FILE_PATH, 'server/index.js', ]); expect(server).toBeNull(); expect(serverIndex).not.toMatch(HEADER); expect(serverIndex).toMatch('I am a bespoke entry'); expect(client).toMatch(HEADER); }); }, BUILD_TIMEOUT, ); it( 'uses the given basePath', async () => { const name = 'custom-base-path'; const basePath = './app/ui'; await withWorkspace(name, async ({workspace}) => { await workspace.write('index.js', BASIC_JS_MODULE); await workspace.write( 'webpack.config.js', createWebpackConfig({basePath}), ); await workspace.write(`${basePath}/index.js`, BASIC_ENTRY); const [client, server] = await runBuild(name, [ `${basePath}/${DEFAULT_CLIENT_FILE_PATH}`, `${basePath}/${DEFAULT_SERVER_FILE_PATH}`, ]); expect(server).toMatch(HEADER); expect(client).toMatch(HEADER); }); }, BUILD_TIMEOUT, ); it( 'uses default server configuration options', async () => { const name = 'default-server-config'; const customConfig = { port: 3000, host: '127.0.0.1', assetPrefix: 'https://localhost/webpack/assets', basePath: '.', }; await withWorkspace(name, async ({workspace}) => { await workspace.write('index.js', BASIC_JS_MODULE); await workspace.write( 'webpack.config.js', createWebpackConfig(customConfig), ); const [server] = await runBuild(name, [DEFAULT_SERVER_FILE_PATH]); expect(server).toMatch('proxy: false'); }); }, BUILD_TIMEOUT, ); it( 'uses the given server configuration options', async () => { const name = 'custom-server-config'; const customConfig = { port: 3000, host: '127.0.0.1', assetPrefix: 'https://localhost/webpack/assets', basePath: '.', proxy: true, }; await withWorkspace(name, async ({workspace}) => { await workspace.write('index.js', BASIC_JS_MODULE); await workspace.write( 'webpack.config.js', createWebpackConfig(customConfig), ); const [server] = await runBuild(name, [DEFAULT_SERVER_FILE_PATH]); expect(server).toMatch(`port: ${customConfig.port}`); expect(server).toMatch(`ip: "${customConfig.host}"`); expect(server).toMatch(`assetPrefix: "${customConfig.assetPrefix}"`); expect(server).toMatch(`proxy: ${customConfig.proxy}`); }); }, BUILD_TIMEOUT, ); }); describe('error component', () => { it( 'imports the Error component in the server when error.js exists', async () => { const name = 'rails-includes-error-component'; const basePath = './app/ui'; await withWorkspace(name, async ({workspace}) => { await workspace.write(`${basePath}/index.js`, BASIC_JS_MODULE); await workspace.write( `${basePath}/error.js`, BASIC_JS_ERROR_COMPOENT, ); await workspace.write( 'webpack.config.js', createWebpackConfig({basePath}), ); const [server] = await runBuild(name, [ `${basePath}/${DEFAULT_SERVER_FILE_PATH}`, ]); expect(server).toMatch("import Error from 'error';"); }); }, BUILD_TIMEOUT, ); it( 'does not import the Error component in the server when error.js does not exists', async () => { const name = 'rails-doesnt-include-error-component'; const basePath = './app/ui'; await withWorkspace(name, async ({workspace}) => { await workspace.write(`${basePath}/index.js`, BASIC_JS_MODULE); await workspace.write( 'webpack.config.js', createWebpackConfig({basePath}), ); const [server] = await runBuild(name, [ `${basePath}/${DEFAULT_SERVER_FILE_PATH}`, ]); expect(server).not.toMatch("import Error from 'error';"); }); }, BUILD_TIMEOUT, ); it( 'includes the Error component in the server when an error folder exists', async () => { const name = 'rails-includes-error-component-folder'; const basePath = './app/ui'; await withWorkspace(name, async ({workspace}) => { await workspace.write(`${basePath}/index.js`, BASIC_JS_MODULE); await workspace.write( `${basePath}/error/index.js`, BASIC_JS_ERROR_COMPOENT, ); await workspace.write( 'webpack.config.js', createWebpackConfig({basePath}), ); const [server] = await runBuild(name, [ `${basePath}/${DEFAULT_SERVER_FILE_PATH}`, ]); expect(server).toMatch("import Error from 'error';"); }); }, BUILD_TIMEOUT, ); }); }); function runBuild( configPath: string, basePaths: string[], ): Promise<(string | null)[]> { return new Promise((resolve, reject) => { const pathFromRoot = path.resolve( './packages/react-server/src/webpack-plugin/tests/fixtures', configPath, ); // eslint-disable-next-line @typescript-eslint/no-var-requires const config = require(`${pathFromRoot}/webpack.config.js`); const contextConfig = Array.isArray(config) ? config.map((config) => ({ ...config, context: pathFromRoot, })) : { ...config, context: pathFromRoot, }; const compiler: Compiler = webpack(contextConfig); // We use memfs.fs to prevent webpack from outputting to our actual FS // from https://github.com/webpack/webpack/blob/4837c3ddb9da8e676c73d97460e19689dd9d4691/test/configCases/types/filesystems/webpack.config.js#L8 compiler.outputFileSystem = memfs.fs; compiler.run((err, stats) => { if (err) { reject(err); return; } if (stats!.hasErrors()) { reject(stats!.toString()); return; } // the Stats type is incorrect from webpack v5.39.1 // https://github.com/webpack/webpack/blob/5d297327bc1f208de16c29f5c9b31d2b8a06bce4/types.d.ts#L1848 const fs = ((stats as any).stats[0] as Stats).compilation .inputFileSystem as typeof memfs.fs; const sources = basePaths.map((basePath) => { try { return fs.readFileSync(path.join(pathFromRoot, basePath)).toString(); } catch { return null; } }); resolve(sources); }); }); } const BASIC_ENTRY = `console.log('I am a bespoke entry');`; const BASIC_JS_MODULE = `module.exports = () => { return 'I am totally a react component'; };`; const BASIC_JS_ERROR_COMPOENT = `module.exports = () => { return 'I am totally an Error component'; };`; const createWebpackConfig = ( {basePath, port, host, assetPrefix, proxy}: Options = { basePath: '.', }, ) => ` const path = require('path'); const {ReactServerPlugin} = require('../../../webpack-plugin'); const universal = { mode: 'production', optimization: { minimize: false, }, plugins: [new ReactServerPlugin({ ${printIf('basePath', basePath)} ${printIf('port', port)} ${printIf('host', host)} ${printIf('assetPrefix', assetPrefix)} ${printIf('proxy', proxy)} })], resolve: { modules: ['node_modules', path.resolve(__dirname, '${basePath}')], }, module: { rules: [ { test: /\\.mjs$/, resolve: { fullySpecified: false, }, }, { test: /node\\/.*\\.js$/, loader: 'node-loader', } ] } }; const server = { ...universal, name: 'server', target: 'node', entry: './${basePath}/server', externals: [ ({context, request}, callback) => { if (/node_modules/.test(context)) { return callback(null, 'commonjs ' + request); } callback(); }, ], }; const client = { ...universal, name: 'client', target: 'web', entry: './${basePath}/client', }; module.exports = [server, client];`; const printIf = (key, value) => { return value ? `${key}: "${value}",` : ''; }; const BASIC_WEBPACK_CONFIG = createWebpackConfig();
the_stack
import _ from 'lodash' import { CommandArgument, CommandDescriptor, CommandName, Commands } from 'constants/command' import Notice from 'libs/Notice' import { SerializedRoomState } from 'libs/RoomState' import Twitch from 'libs/Twitch' import { Log } from 'store/ducks/logs' /** * Actions that could arise when handling a command. */ export enum CommandDelegateAction { AddLog, AddToHistory, Say, SayWithoutHistory, Timeout, Whisper, } /** * Command class. */ export default class Command { /** * Checks if a message is a command (starting by a `/` or a `.`). * @param message - A message potentially containing a command. */ public static isCommand(message: string) { const firstCharacter = message.charAt(0) return firstCharacter === '/' || firstCharacter === '.' } /** * Checks if a message is a whisper reply command (`/r`). * @param message - A message potentially containing a whisper reply command. */ public static isWhisperReplyCommand(message: string) { return /^[/|.]r /i.test(message) } /** * Checks if a message is a help command (`/help`). * @param message - A message potentially containing a help command. */ public static isHelpCommand(message: string) { return /^[/|.]help(?:$|\s)/i.test(message) } /** * Checks if the cursor in a message is associated to a command username auto-completable argument. * Note: at the moment, it is assumed that all commands having a username completable argument have that argument at * the first position. * @param message - The message. * @param cursor - The cursor position. * @return `true` when the cursor is matching a username completable argument. */ public static isUsernameCompletableCommandArgument(message: string, cursor: number) { // Bail out if the message is not even a command. if (!Command.isCommand(message)) { return false } // Grab the command name and the first argument. const words = message.split(' ') const commandName = words[0].substr(1) const firstArgument = words[1] // If we don't have a first argument yet, bail out. if (_.isNil(firstArgument)) { return false } const firstArgumentStart = commandName.length + 2 const firstArgumentEnd = firstArgumentStart + firstArgument.length // If we're not auto-completing the first agument, bail out. if (cursor < firstArgumentStart || cursor > firstArgumentEnd) { return false } // Get the descriptor for this command. const descriptor = Command.getDescriptor(commandName) // If we can't get a valid descriptor, this means the command is unknown. if (_.isNil(descriptor.name)) { return false } const firstArgumentDescriptor = _.get(descriptor, 'arguments[0]') as Optional<CommandArgument> // If the command doesn't accept any argument or the first argument is not a // username, bail out. if (_.isNil(firstArgumentDescriptor) || firstArgumentDescriptor.name !== 'username') { return false } return true } /** * Parses a message as a whisper command (/w user message). * @return The whisper details. */ public static parseWhisper(message: string) { const matches = message.match(/^[/|.]w (\S+) (.+)/i) const details = { username: undefined as Optional<string>, whisper: undefined as Optional<string> } if (!_.isNil(matches)) { details.username = matches[1] details.whisper = matches[2] } return details } /** * Parses a message as a shrug command (/shrug). * @return The new message with the inserted shrug if the message contained a shrug command.. */ public static parseShrug(message: string) { const matches = message.match(/(^|.* )[/|.]shrug($| .*)/i) const result = { isShrug: false, message } if (!_.isNil(matches)) { const before = matches[1] const after = matches[2] result.isShrug = true result.message = `${before}¯\\_(ツ)_/¯ ${after}` } return result } /** * Returns a command usage. * @param descriptor - The command descriptor. * @return The command usage. */ public static getUsage(descriptor: EnhancedCommandDescriptor) { const args = _.map(descriptor.arguments, (argument) => { if (argument.optional) { return `[${argument.name}]` } return `<${argument.name}>` }) return `/${descriptor.name} ${args.join(' ')}` } /** * Returns the descriptor of the command. * @return The descriptor. */ public static getDescriptor(commandName: string | CommandName): EnhancedCommandDescriptor { const formattedCommandName = _.upperFirst(commandName) if (!Command.isKnownCommand(formattedCommandName)) { throw new Error('Unknown command name.') } const name: CommandName = CommandName[formattedCommandName] return { ...Commands[name], name } } /** * Defines if an emote code matches a Twitch RegExp emote. * @param code - The emote code. * @return `true` when the code matches a Twitch RegExp emote. */ private static isKnownCommand(code: string): code is keyof typeof CommandName { return code in CommandName } private command: string private arguments: string[] /** * Creates a new instance of the class. * @class * @param message - A message containing a command validated by * `Command.isCommand()`. */ constructor( private message: string, private delegate: CommandDelegate, private delegateDataFetcher: CommandDelegateDataFetcher ) { const [command, ...args] = message.slice(1).split(' ') this.command = command.toLowerCase() this.arguments = args } /** * Handles the command. */ public async handle() { if (!_.includes(CommandName, this.command)) { this.say(this.message) } else { const descriptor = Command.getDescriptor(this.command) const handler = this.getHandler(descriptor) if (_.isNil(handler)) { await this.say(this.message) } else { await handler() if (!descriptor.ignoreHistory) { this.addToHistory(this.message) } } } } /** * Sends a message. * @param message - The message to send. * @param ignoreHistory - Defines if the message should not be added to the * history. */ private async say(message: string, ignoreHistory: boolean = false) { const action = ignoreHistory ? CommandDelegateAction.SayWithoutHistory : CommandDelegateAction.Say this.delegate(action, message) } /** * Adds a message to the history. * @param message - The message to add. */ private async addToHistory(message: string) { this.delegate(CommandDelegateAction.AddToHistory, message) } /** * Adds a log entry. * @param log - The log entry to add. */ private addLog(log: Log) { this.delegate(CommandDelegateAction.AddLog, log) } /** * Sends a whisper. * @param username - The recipient. * @param whisper - The whisper to send. * @param [command] - The command used to send the whisper. */ private whisper(username: string, whisper: string, command?: string) { this.delegate(CommandDelegateAction.Whisper, username, whisper, command) } /** * Timeouts a user. * @param username - The name of the user to timeout. * @param duration - The duration of the timeout in seconds. */ private timeout(username: string, duration: number) { this.delegate(CommandDelegateAction.Timeout, username, duration) } /** * Sends a help notice about the command. */ private sendHelpNotice() { const descriptor = Command.getDescriptor(this.command) const notice = new Notice(`Usage: "${Command.getUsage(descriptor)}" - ${descriptor.description}`, null) this.addLog(notice.serialize()) } /** * Returns the handler of a command. * @param description - The command descriptor. * @return The handler. */ private getHandler(descriptor: EnhancedCommandDescriptor) { return this.commandHandlers[descriptor.name] } /** * Handles the /followed command. */ private handleCommandFollowed = async () => { const { channelId } = this.delegateDataFetcher() if (!_.isNil(channelId)) { const relationship = await Twitch.fetchRelationship(channelId) const notice = new Notice( _.isNil(relationship) ? 'Channel not followed.' : `Followed since ${new Date(relationship.followed_at).toLocaleDateString()}.`, null ) this.addLog(notice.serialize()) } } /** * Handles the /marker command. */ private handleCommandMarker = async () => { const { channelId } = this.delegateDataFetcher() const [description] = this.arguments if (!_.isNil(channelId)) { let noticeStr try { await Twitch.createMarker(channelId, description) noticeStr = 'Marker created successfully.' } catch (error) { noticeStr = 'Something went wrong while creating a marker.' const matches = /message:"(?<message>[^"]*)/.exec(error) if (matches) { const message = _.get(matches, 'groups.message') if (message) { noticeStr = message } } } const notice = new Notice(noticeStr, null) this.addLog(notice.serialize()) } } /** * Handles the /title command. */ private handleCommandTitle = async () => { const { channelId } = this.delegateDataFetcher() const title = this.arguments.join(' ') if (!_.isNil(channelId)) { let noticeStr if (_.isEmpty(title)) { try { const channelInfos = await Twitch.fetchChannelInformations(channelId) noticeStr = `Current title: ${channelInfos.title}` } catch (error) { noticeStr = 'Something went wrong while fetching the title.' } } else { try { await Twitch.updateChannelInformations(channelId, title) noticeStr = `New title: ${title}` } catch (error) { noticeStr = 'Something went wrong while updating the title.' } } const notice = new Notice(noticeStr, null) this.addLog(notice.serialize()) } } /** * Handles the /block & /unblock commands. */ private handleCommandBlockUnblock = async () => { const [username] = this.arguments if (_.isEmpty(username)) { this.sendHelpNotice() } else { let noticeStr try { const user = await Twitch.fetchUserByName(username) if (_.isNil(user)) { throw new Error(`Invalid user name provided for the ${this.command} command.`) } const blockFn = this.command === 'block' ? Twitch.blockUser : Twitch.unblockUser await blockFn(user.id) noticeStr = `${username} is now ${this.command}ed.` } catch (error) { noticeStr = `Something went wrong while trying to ${this.command} ${username}.` } const notice = new Notice(noticeStr, null) this.addLog(notice.serialize()) } } /** * Handles the /purge command. */ private handleCommandPurge = () => { const [username] = this.arguments if (_.isEmpty(username)) { this.sendHelpNotice() } else { this.timeout(username, 1) } } /** * Handles the /w command. */ private handleCommandWhisper = () => { const [username, ...fragments] = this.arguments const whisper = fragments.join(' ') if (!_.isEmpty(username) && !_.isEmpty(whisper)) { this.whisper(username, whisper, this.message) } else { this.sendHelpNotice() } } /** * Handles the /uniquechat command. */ private handleCommandUniqueChat = () => { this.say('/r9kbeta', true) } /** * Handles the /uniquechatoff command. */ private handleCommandUniqueChatOff = () => { this.say('/r9kbetaoff', true) } /** * Handles the /user command. */ private handleCommandUser = () => { const [username] = this.arguments if (_.isEmpty(username)) { this.sendHelpNotice() } else { const { channel } = this.delegateDataFetcher() if (!_.isNil(channel)) { Twitch.openViewerCard(channel, username) } } } /** * List of commands with special handlers. */ private commandHandlers: { [key in CommandName]?: () => void } = { [CommandName.Block]: this.handleCommandBlockUnblock, [CommandName.Followed]: this.handleCommandFollowed, [CommandName.Marker]: this.handleCommandMarker, [CommandName.Purge]: this.handleCommandPurge, [CommandName.Title]: this.handleCommandTitle, [CommandName.Unblock]: this.handleCommandBlockUnblock, [CommandName.Uniquechat]: this.handleCommandUniqueChat, [CommandName.Uniquechatoff]: this.handleCommandUniqueChatOff, [CommandName.User]: this.handleCommandUser, [CommandName.W]: this.handleCommandWhisper, } } /** * Command delegate data fetcher. */ export type CommandDelegateDataFetcher = () => { channel: string | null channelId: SerializedRoomState['roomId'] | undefined } /** * The commande delegate signature. */ export interface CommandDelegate { (action: CommandDelegateAction.AddLog, log: Log): void (action: CommandDelegateAction.Timeout, username: string, duration: number): void (action: CommandDelegateAction.Whisper, username: string, whisper: string, command?: string): void ( action: CommandDelegateAction.AddToHistory | CommandDelegateAction.Say | CommandDelegateAction.SayWithoutHistory, message: string ): void } /** * An enhanced command descriptor including the command name. */ type EnhancedCommandDescriptor = CommandDescriptor & { name: CommandName }
the_stack
import * as util from './util'; import * as logger from './logger'; var errors = { typeMismatch: "Unexpected type: ", duplicatePathPart: "A path component name is duplicated: ", }; export type Object = { [prop: string]: any }; export interface Exp { type: string; valueType: string; } export interface ExpValue extends Exp { value: any; } export interface RegExpValue extends ExpValue { modifiers: string; } export interface ExpNull extends Exp { } export interface ExpOp extends Exp { op: string; args: Exp[]; } export interface ExpVariable extends Exp { name: string; } export interface ExpLiteral extends Exp { name: string; } // base[accessor] export interface ExpReference extends Exp { base: Exp; accessor: Exp; } export interface ExpCall extends Exp { ref: ExpReference | ExpVariable; args: Exp[]; } export interface Params { [name: string]: Exp; }; export type BuiltinFunction = (args: Exp[], params: Params) => Exp; export interface ExpBuiltin extends Exp { fn: BuiltinFunction; } export type ExpType = ExpSimpleType | ExpUnionType | ExpGenericType; export interface TypeParams { [name: string]: ExpType; }; // Simple Type (reference) export interface ExpSimpleType extends Exp { name: string; } // Union Type: Type1 | Type2 | ... export interface ExpUnionType extends Exp { types: ExpType[]; } // Generic Type (reference): Type<Type1, Type2, ...> export interface ExpGenericType extends Exp { name: string; params: ExpType[]; } export interface Method { params: string[]; body: Exp; } export class PathPart { label: string; variable: string; // "label", undefined - static path part // "$label", X - variable path part // X, !undefined - variable path part constructor(label: string, variable?: string) { if (label[0] === '$' && variable === undefined) { variable = label; } if (variable && label[0] !== '$') { label = '$' + label; } this.label = label; this.variable = <string> variable; } } export class PathTemplate { parts: PathPart[]; constructor(parts = <(string | PathPart)[]> []) { this.parts = <PathPart[]> parts.map((part) => { if (util.isType(part, 'string')) { return new PathPart(<string> part); } else { return <PathPart> part; } }); } copy() { let result = new PathTemplate(); result.push(this); return result; } getLabels(): string[] { return this.parts.map((part) => part.label); } // Mapping from variables to JSON labels getScope(): Params { let result = <Params> {}; this.parts.forEach((part) => { if (part.variable) { if (result[part.variable]) { throw new Error(errors.duplicatePathPart + part.variable); } result[part.variable] = literal(part.label); } }); return result; } push(temp: PathTemplate) { util.extendArray(this.parts, temp.parts); } pop(temp: PathTemplate) { temp.parts.forEach((part) => { this.parts.pop(); }); } length(): number { return this.parts.length; } getPart(i: number): PathPart { if (i > this.parts.length || i < -this.parts.length) { let l = this.parts.length; throw new Error("Path reference out of bounds: " + i + " [" + -l + " .. " + l + "]"); } if (i < 0) { return this.parts[this.parts.length + i]; } return this.parts[i]; } } export interface Path { template: PathTemplate; isType: ExpType; methods: { [name: string]: Method }; }; export class Schema { derivedFrom: ExpType; properties: TypeParams; methods: { [name: string]: Method }; // Generic parameters - if a Generic schema params?: string[]; getValidator?: (params: Exp[]) => Object; static isGeneric(schema: Schema): boolean { return schema.params !== undefined && schema.params.length > 0; } }; export var string: (v: string) => ExpValue = valueGen('String'); export var boolean: (v: boolean) => ExpValue = valueGen('Boolean'); export var number: (v: number) => ExpValue = valueGen('Number'); export var array: (v: Array<any>) => ExpValue = valueGen('Array'); export var neg = opGen('neg', 1); export var not = opGen('!', 1); export var mult = opGen('*'); export var div = opGen('/'); export var mod = opGen('%'); export var add = opGen('+'); export var sub = opGen('-'); export var eq = opGen('=='); export var lt = opGen('<'); export var lte = opGen('<='); export var gt = opGen('>'); export var gte = opGen('>='); export var ne = opGen('!='); export var and = opGen('&&'); export var or = opGen('||'); export var ternary = opGen('?:', 3); export var value = opGen('value', 1); export function variable(name: string): ExpVariable { return { type: 'var', valueType: 'Any', name: name }; } export function literal(name: string): ExpLiteral { return { type: 'literal', valueType: 'Any', name: name }; } export function nullType(): ExpNull { return { type: 'Null', valueType: 'Null' }; } export function reference(base: Exp, prop: Exp): ExpReference { return { type: 'ref', valueType: 'Any', base: base, accessor: prop }; } let reIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_]*$/; export function isIdentifierStringExp(exp: Exp) { return exp.type === 'String' && reIdentifier.test((<ExpValue> exp).value); } // Shallow copy of an expression (so it can be modified and preserve // immutability of the original expression). export function copyExp(exp: Exp): Exp { exp = <Exp> util.extend({}, exp); switch (exp.type) { case 'op': case 'call': let opExp = <ExpOp> exp; opExp.args = util.copyArray(opExp.args); return opExp; case 'union': let unionExp = <ExpUnionType> exp; unionExp.types = util.copyArray(unionExp.types); return unionExp; case 'generic': let genericExp = <ExpGenericType> exp; genericExp.params = util.copyArray(genericExp.params); return genericExp; default: return exp; } } // Make a (shallow) copy of the base expression, setting (or removing) it's // valueType. // // valueType is a string indicating the type of evaluating an expression (e.g. // 'Snapshot') - used to know when type coercion is needed in the context // of parent expressions. export function cast(base: Exp, valueType: string): Exp { var result = copyExp(base); result.valueType = valueType; return result; } export function call(ref: ExpReference | ExpVariable, args: Exp[]= []): ExpCall { return { type: 'call', valueType: 'Any', ref: ref, args: args }; } // Return empty string if not a function. export function getFunctionName(exp: ExpCall): string { if (exp.ref.type === 'ref') { return ''; } return (<ExpVariable> exp.ref).name; } // Return empty string if not a (simple) method call -- ref.fn() export function getMethodName(exp: ExpCall): string { if (exp.ref.type === 'var') { return (<ExpVariable> exp.ref).name; } if (exp.ref.type !== 'ref') { return ''; } return getPropName(<ExpReference> exp.ref); } export function getPropName(ref: ExpReference): string { if (ref.accessor.type !== 'String') { return ''; } return (<ExpValue> ref.accessor).value; } // TODO: Type of function signature does not fail this declaration? export function builtin(fn: BuiltinFunction): ExpBuiltin { return { type: 'builtin', valueType: 'Any', fn: fn }; } export function snapshotVariable(name: string): ExpVariable { return <ExpVariable> cast(variable(name), 'Snapshot'); } export function snapshotParent(base: Exp): Exp { if (base.valueType !== 'Snapshot') { throw new Error(errors.typeMismatch + "expected Snapshot"); } return cast(call(reference(cast(base, 'Any'), string('parent'))), 'Snapshot'); } export function ensureValue(exp: Exp): Exp { if (exp.valueType === 'Snapshot') { return snapshotValue(exp); } return exp; } // ref.val() export function snapshotValue(exp: Exp): ExpCall { return call(reference(cast(exp, 'Any'), string('val'))); } // Ensure expression is a boolean (when used in a boolean context). export function ensureBoolean(exp: Exp): Exp { exp = ensureValue(exp); if (isCall(exp, 'val')) { exp = eq(exp, boolean(true)); } return exp; } export function isCall(exp: Exp, methodName: string): boolean { return exp.type === 'call' && (<ExpCall> exp).ref.type === 'ref' && (<ExpReference> (<ExpCall> exp).ref).accessor.type === 'String' && (<ExpValue> (<ExpReference> (<ExpCall> exp).ref).accessor).value === methodName; } // Return value generating function for a given Type. function valueGen(typeName: string): ((val: any) => ExpValue) { return function(val): ExpValue { return { type: typeName, // Exp type identifying a constant value of this Type. valueType: typeName, // The type of the result of evaluating this expression. value: val // The (constant) value itself. }; }; } export function regexp(pattern: string, modifiers = ""): RegExpValue { switch (modifiers) { case "": case "i": break; default: throw new Error("Unsupported RegExp modifier: " + modifiers); } return { type: 'RegExp', valueType: 'RegExp', value: pattern, modifiers: modifiers }; } function cmpValues(v1: Exp, v2: ExpValue): boolean { if (v1.type !== v2.type) { return false; } return (<ExpValue> v1).value === v2.value; } function isOp(opType: string, exp: Exp): boolean { return exp.type === 'op' && (<ExpOp> exp).op === opType; } // Return a generating function to make an operator exp node. function opGen(opType: string, arity: number = 2): ((...args: Exp[]) => ExpOp) { return function(...args): ExpOp { if (args.length !== arity) { throw new Error("Operator has " + args.length + " arguments (expecting " + arity + ")."); } return op(opType, args); }; } export var andArray = leftAssociateGen('&&', boolean(true), boolean(false)); export var orArray = leftAssociateGen('||', boolean(false), boolean(true)); // Create an expression builder function which operates on arrays of values. // Returns new expression like v1 op v2 op v3 ... // // - Any identityValue's in array input are ignored. // - If zeroValue is found - just return zeroValue. // // Our function re-orders top-level op in array elements to the resulting // expression is left-associating. E.g.: // // [a && b, c && d] => (((a && b) && c) && d) // (NOT (a && b) && (c && d)) function leftAssociateGen(opType: string, identityValue: ExpValue, zeroValue: ExpValue) { return function(a: Exp[]): Exp { var i: number; function reducer(result: Exp, current: Exp) { if (result === undefined) { return current; } return op(opType, [result, current]); } // First flatten all top-level op values to one flat array. var flat = <Exp[]>[]; for (i = 0; i < a.length; i++) { flatten(opType, a[i], flat); } var result = <Exp[]>[]; for (i = 0; i < flat.length; i++) { // Remove identifyValues from array. if (cmpValues(flat[i], identityValue)) { continue; } // Just return zeroValue if found if (cmpValues(flat[i], zeroValue)) { return zeroValue; } result.push(flat[i]); } if (result.length === 0) { return identityValue; } // Return left-associative expression of opType. return result.reduce(reducer); }; } // Flatten the top level tree of op into a single flat array of expressions. export function flatten(opType: string, exp: Exp, flat?: Exp[]): Exp[] { var i: number; if (flat === undefined) { flat = []; } if (!isOp(opType, exp)) { flat.push(exp); return flat; } for (i = 0; i < (<ExpOp> exp).args.length; i++) { flatten(opType, (<ExpOp> exp).args[i], flat); } return flat; } export function op(opType: string, args: Exp[]): ExpOp { return { type: 'op', // This is (multi-argument) operator. valueType: 'Any', op: opType, // The operator (string, e.g. '+'). args: args // Arguments to the operator Array<exp> }; } // Warning: NOT an expression type! export function method(params: string[], body: Exp): Method { return { params: params, body: body }; } export function typeType(typeName: string): ExpSimpleType { return { type: "type", valueType: "type", name: typeName }; } export function unionType(types: ExpType[]): ExpUnionType { return { type: "union", valueType: "type", types: types }; } export function genericType(typeName: string, params: ExpType[]): ExpGenericType { return { type: "generic", valueType: "type", name: typeName, params: params }; } export class Symbols { functions: { [name: string]: Method }; paths: Path[]; schema: { [name: string]: Schema }; constructor() { this.functions = {}; this.paths = []; this.schema = {}; } register<T>(map: {[name: string]: T}, typeName: string, name: string, object: T): T { if (map[name]) { logger.error("Duplicated " + typeName + " definition: " + name + "."); } else { map[name] = object; } return map[name]; } registerFunction(name: string, params: string[], body: Exp): Method { return this.register<Method>(this.functions, 'functions', name, method(params, body)); } registerPath(template: PathTemplate, isType: ExpType | void, methods: { [name: string]: Method; } = {}): Path { isType = isType || typeType('Any'); var p: Path = { template: template.copy(), isType: <ExpType> isType, methods: methods }; this.paths.push(p); return p; } registerSchema(name: string, derivedFrom?: ExpType, properties = <TypeParams> {}, methods = <{ [name: string]: Method }> {}, params = <string[]> []) : Schema { derivedFrom = derivedFrom || typeType(Object.keys(properties).length > 0 ? 'Object' : 'Any'); var s: Schema = { derivedFrom: <ExpType> derivedFrom, properties: properties, methods: methods, params: params, }; return this.register<Schema>(this.schema, 'schema', name, s); } isDerivedFrom(type: ExpType, ancestor: string): boolean { if (ancestor === 'Any') { return true; } switch (type.type) { case 'type': case 'generic': let simpleType = <ExpSimpleType> type; if (simpleType.name === ancestor) { return true; } if (simpleType.name === 'Any') { return false; } let schema = this.schema[simpleType.name]; if (!schema) { return false; } return this.isDerivedFrom(schema.derivedFrom, ancestor); case 'union': return (<ExpUnionType> type).types .map((subType) => this.isDerivedFrom(subType, ancestor)) .reduce(util.or); default: throw new Error("Unknown type: " + type.type); } } } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence interface OpPriority { rep?: string; p: number; } var JS_OPS: { [op: string]: OpPriority; } = { 'value': { rep: "", p: 18 }, 'neg': { rep: "-", p: 15}, '!': { p: 15}, '*': { p: 14}, '/': { p: 14}, '%': { p: 14}, '+': { p: 13 }, '-': { p: 13 }, '<': { p: 11 }, '<=': { p: 11 }, '>': { p: 11 }, '>=': { p: 11 }, 'in': { p: 11 }, '==': { p: 10 }, "!=": { p: 10 }, '&&': { p: 6 }, '||': { p: 5 }, '?:': { p: 4 }, ',': { p: 0}, }; // From an AST, decode as an expression (string). export function decodeExpression(exp: Exp, outerPrecedence?: number): string { if (outerPrecedence === undefined) { outerPrecedence = 0; } var innerPrecedence = precedenceOf(exp); var result = ''; switch (exp.type) { case 'Boolean': case 'Number': result = JSON.stringify((<ExpValue> exp).value); break; case 'String': result = util.quoteString((<ExpValue> exp).value); break; // RegExp assumed to be in pre-quoted format. case 'RegExp': let regexp = <RegExpValue> exp; result = '/' + regexp.value + '/'; if (regexp.modifiers !== '') { result += regexp.modifiers; } break; case 'Array': result = '[' + decodeArray((<ExpValue> exp).value) + ']'; break; case 'Null': result = 'null'; break; case 'var': case 'literal': result = (<ExpVariable> exp).name; break; case 'ref': let expRef = <ExpReference> exp; if (isIdentifierStringExp(expRef.accessor)) { result = decodeExpression(expRef.base, innerPrecedence) + '.' + (<ExpValue> expRef.accessor).value; } else { result = decodeExpression(expRef.base, innerPrecedence) + '[' + decodeExpression(expRef.accessor) + ']'; } break; case 'call': let expCall = <ExpCall> exp; result = decodeExpression(expCall.ref) + '(' + decodeArray(expCall.args) + ')'; break; case 'builtin': result = decodeExpression(exp); break; case 'op': let expOp = <ExpOp> exp; var rep = JS_OPS[expOp.op].rep === undefined ? expOp.op : JS_OPS[expOp.op].rep; if (expOp.args.length === 1) { result = rep + decodeExpression(expOp.args[0], innerPrecedence); } else if (expOp.args.length === 2) { result = decodeExpression(expOp.args[0], innerPrecedence) + ' ' + rep + ' ' + // All ops are left associative - so nudge the innerPrecendence // down on the right hand side to force () for right-associating // operations. decodeExpression(expOp.args[1], innerPrecedence + 1); if ((innerPrecedence >= outerPrecedence) && ((expOp.op === '&&') || (expOp.op === '||'))) { result = '(' + result + ')'; } } else if (expOp.args.length === 3) { result = decodeExpression(expOp.args[0], innerPrecedence) + ' ? ' + decodeExpression(expOp.args[1], innerPrecedence) + ' : ' + decodeExpression(expOp.args[2], innerPrecedence); } break; case 'type': result = (<ExpSimpleType> exp).name; break; case 'union': result = (<ExpUnionType> exp).types.map(decodeExpression).join(' | '); break; case 'generic': let genericType = <ExpGenericType> exp; return genericType.name + '<' + decodeArray(genericType.params) + '>'; default: result = "***UNKNOWN TYPE*** (" + exp.type + ")"; break; } if (innerPrecedence < outerPrecedence) { result = '(' + result + ')'; } return result; } function decodeArray(args: Exp[]): string { return args.map(decodeExpression).join(', '); } function precedenceOf(exp: Exp): number { let result: number; switch (exp.type) { case 'op': result = JS_OPS[(<ExpOp> exp).op].p; break; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence // lists call as 17 and ref as 18 - but how could they be anything other than left to right? // http://www.scriptingmaster.com/javascript/operator-precedence.asp - agrees. case 'call': result = 18; break; case 'ref': result = 18; break; default: result = 19; break; } return result; }
the_stack
import i18next, { InitOptions, i18n, TFunction, TOptions } from "i18next"; import { DOM, PLATFORM } from "aurelia-pal"; import * as LogManager from "aurelia-logging"; import { EventAggregator } from "aurelia-event-aggregator"; import { BindingSignaler } from "aurelia-templating-resources"; export interface AureliaEnhancedOptions extends InitOptions { attributes?: string[]; skipTranslationOnMissingKey?: boolean; } export interface AureliaEnhancedI18Next extends i18n { options: AureliaEnhancedOptions; } // tslint:disable-next-line:interface-name export interface I18NEventPayload { oldValue: string; newValue: string; } export const I18N_EA_SIGNAL = "i18n:locale:changed"; export class I18N { public static inject() { return [EventAggregator, BindingSignaler]; } public i18nextDeferred: Promise<AureliaEnhancedI18Next>; public i18next: AureliaEnhancedI18Next; public Intl: typeof Intl; private globalVars: { [key: string]: any } = {}; constructor(private ea: EventAggregator, private signaler: BindingSignaler) { this.i18next = i18next; this.Intl = PLATFORM.global.Intl; } public async setup(options?: AureliaEnhancedOptions & InitOptions) { const defaultOptions: AureliaEnhancedOptions & InitOptions = { skipTranslationOnMissingKey: false, compatibilityJSON: "v1", lng: "en", attributes: ["t", "i18n"], fallbackLng: "en", debug: false }; this.i18nextDeferred = new Promise((resolve, reject) => { this.i18next.init(options || defaultOptions, (err) => { if (err && !Array.isArray(err)) { reject(err); } // make sure attributes is an array in case a string was provided if (this.i18next.options.attributes instanceof String) { this.i18next.options.attributes = [this.i18next.options.attributes as any as string]; } resolve(this.i18next); }); }); return this.i18nextDeferred; } public i18nextReady() { return this.i18nextDeferred; } public setLocale(locale: string): Promise<TFunction> { return new Promise((resolve, reject) => { const oldLocale = this.getLocale(); this.i18next.changeLanguage(locale, (err, tr) => { if (err) { reject(err); } this.ea.publish(I18N_EA_SIGNAL, { oldValue: oldLocale, newValue: locale }); this.signaler.signal("aurelia-translation-signal"); resolve(tr); }); }); } public getLocale() { return this.i18next.language; } public nf(options?: Intl.NumberFormatOptions, locales?: string | string[]) { return new this.Intl.NumberFormat(locales || this.getLocale(), options || {}); } public uf(numberLike: string, locale?: string) { const nf = this.nf({}, locale || this.getLocale()); const comparer = nf.format(10000 / 3); let thousandSeparator = comparer[1]; const decimalSeparator = comparer[5]; if (thousandSeparator === ".") { thousandSeparator = "\\."; } // remove all thousand seperators const result = numberLike.replace(new RegExp(thousandSeparator, "g"), "") // remove non-numeric signs except -> , . .replace(/[^\d.,-]/g, "") // replace original decimalSeparator with english one .replace(decimalSeparator, "."); // return real number return Number(result); } public df(options?: Intl.DateTimeFormatOptions, locales?: string | string[]) { return new this.Intl.DateTimeFormat(locales || this.getLocale(), options); } public tr(key: string | string[], options?: TOptions<object>) { let fullOptions = this.globalVars; if (options !== undefined) { fullOptions = Object.assign(Object.assign({}, this.globalVars), options); } return this.i18next.t(key, fullOptions); } public registerGlobalVariable(key: string, value: any) { this.globalVars[key] = value; } public unregisterGlobalVariable(key: string) { delete this.globalVars[key]; } /** * Scans an element for children that have a translation attribute and * updates their innerHTML with the current translation values. * * If an image is encountered the translated value will be applied to the src attribute. * * @param el HTMLElement to search within */ public updateTranslations(el: HTMLElement) { if (!el || !el.querySelectorAll) { return; } let i; let l; // create a selector from the specified attributes to look for // var selector = [].concat(this.i18next.options.attributes); const attributes = this.i18next.options.attributes!; let selector = [].concat(attributes as any) as any; for (i = 0, l = selector.length; i < l; i++) { selector[i] = "[" + selector[i] + "]"; } selector = selector.join(","); // get the nodes const nodes = el.querySelectorAll(selector); for (i = 0, l = nodes.length; i < l; i++) { const node = nodes[i]; let keys; let params; // test every attribute and get the first one that has a value for (let i2 = 0, l2 = attributes.length; i2 < l2; i2++) { keys = node.getAttribute(attributes[i2]); const pname = attributes[i2] + "-params"; if (pname && node.au && node.au[pname]) { params = node.au[pname].viewModel.value; } if (keys) { break; } } // skip if nothing was found if (!keys) { continue; } // split the keys into multiple keys separated by a ; this.updateValue(node, keys, params); } } public updateValue(node: Element & { au: any }, value: string, params: any) { if (value === null || value === undefined) { value = ""; } const keys = value.toString().split(";"); let i = keys.length; while (i--) { let key = keys[i]; // remove the optional attribute const re = /\[([a-z\-, ]*)\]/ig; let m; let attr = "text"; // set default attribute to src if this is an image node if (node.nodeName === "IMG") { attr = "src"; } // check if a attribute was specified in the key // tslint:disable-next-line:no-conditional-assignment while ((m = re.exec(key)) !== null) { if (m.index === re.lastIndex) { re.lastIndex++; } if (m) { key = key.replace(m[0], ""); attr = m[1]; } } const attrs = attr.split(","); let j = attrs.length; while (j--) { attr = attrs[j].trim(); if (!(node as any)._textContent) { (node as any)._textContent = node.textContent; } if (!(node as any)._innerHTML) { (node as any)._innerHTML = node.innerHTML; } // convert to camelCase // tslint:disable-next-line:only-arrow-functions const attrCC = attr.replace(/-([a-z])/g, function(g) { return g[1].toUpperCase(); }); const reservedNames = ["prepend", "append", "text", "html"]; const i18nLogger = LogManager.getLogger("i18n"); if (reservedNames.indexOf(attr) > -1 && node.au && node.au.controller && node.au.controller.viewModel && attrCC in node.au.controller.viewModel) { i18nLogger.warn(`Aurelia I18N reserved attribute name\n [${reservedNames.join(", ")}]\n Your custom element has a bindable named ${attr} which is a reserved word.\n If you'd like Aurelia I18N to translate your bindable instead, please consider giving it another name.`); } if (this.i18next.options.skipTranslationOnMissingKey && this.tr(key, params) === key) { i18nLogger.warn(`Couldn't find translation for key: ${key}`); return; } // handle various attributes // anything other than text,prepend,append or html will be added as an attribute on the element. switch (attr) { case "text": const newChild = DOM.createTextNode(this.tr(key, params)); if ((node as any)._newChild && (node as any)._newChild.parentNode === node) { node.removeChild((node as any)._newChild); } (node as any)._newChild = newChild; while (node.firstChild) { node.removeChild(node.firstChild); } node.appendChild((node as any)._newChild); break; case "prepend": const prependParser = DOM.createElement("div"); prependParser.innerHTML = this.tr(key, params); for (let ni = node.childNodes.length - 1; ni >= 0; ni--) { if ((node.childNodes[ni] as any)._prepended) { node.removeChild(node.childNodes[ni]); } } for (let pi = prependParser.childNodes.length - 1; pi >= 0; pi--) { (prependParser.childNodes[pi] as any)._prepended = true; if (node.firstChild) { node.insertBefore(prependParser.childNodes[pi], node.firstChild); } else { node.appendChild(prependParser.childNodes[pi]); } } break; case "append": const appendParser = DOM.createElement("div"); appendParser.innerHTML = this.tr(key, params); for (let ni = node.childNodes.length - 1; ni >= 0; ni--) { if ((node.childNodes[ni] as any)._appended) { node.removeChild(node.childNodes[ni]); } } while (appendParser.firstChild) { (appendParser.firstChild as any)._appended = true; node.appendChild(appendParser.firstChild); } break; case "html": node.innerHTML = this.tr(key, params); break; default: // normal html attribute if (node.au && node.au.controller && node.au.controller.viewModel && attrCC in node.au.controller.viewModel) { node.au.controller.viewModel[attrCC] = this.tr(key, params); } else { node.setAttribute(attr, this.tr(key, params)); } break; } } } } }
the_stack
import { gql } from "@apollo/client"; import { v4 as uuidV4 } from "uuid"; import { Membership, MembershipRole, MutationCreateMembershipArgs, MutationCreateWorkspaceArgs, User, Workspace, } from "@labelflow/graphql-types"; import { getPrismaClient } from "../../prisma-client"; import { client, user as loggedInUser, user } from "../../dev/apollo-client"; // @ts-ignore fetch.disableFetchMocks(); const testUser1Id = uuidV4(); const testUser2Id = uuidV4(); const testUser3Id = uuidV4(); const testUser4Id = uuidV4(); beforeEach(async () => { await (await getPrismaClient()).membership.deleteMany({}); await (await getPrismaClient()).workspace.deleteMany({}); return await (await getPrismaClient()).user.deleteMany({}); }); afterAll(async () => { // Needed to avoid having the test process running indefinitely after the test suite has been run await (await getPrismaClient()).$disconnect(); }); const createMembership = async ( data?: MutationCreateMembershipArgs["data"] ) => { return await client.mutate<{ createMembership: Membership; }>({ mutation: gql` mutation createMembership($data: MembershipCreateInput!) { createMembership(data: $data) { id role } } `, variables: { data }, }); }; const createWorkspace = async ( data?: Partial<MutationCreateWorkspaceArgs["data"]> ) => { return await client.mutate<{ createWorkspace: Pick<Workspace, "id" | "name" | "slug" | "plan" | "type">; }>({ mutation: gql` mutation createWorkspace($data: WorkspaceCreateInput!) { createWorkspace(data: $data) { id name slug plan type } } `, variables: { data: { ...data, name: data?.name ?? "test" } }, }); }; describe("users query", () => { it("returns an empty array when there aren't any", async () => { const { data } = await client.query({ query: gql` { users { id } } `, fetchPolicy: "no-cache", }); expect(data.users).toEqual([]); }); it("returns only the current user if he is not linked to any other user through a workspace", async () => { await ( await getPrismaClient() ).user.create({ data: { id: testUser1Id, name: "test-user-1" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser2Id, name: "test-user-2" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser3Id, name: "test-user-3" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser4Id, name: "test-user-4" }, }); loggedInUser.id = testUser1Id; await createWorkspace(); const { data } = await client.query<{ users: Pick<User, "id" | "name">[]; }>({ query: gql` { users { id name } } `, fetchPolicy: "no-cache", }); expect(data.users.map((userData) => userData.name)).toEqual([ "test-user-1", ]); }); it("returns only the users linked to the current user through a workspace", async () => { await ( await getPrismaClient() ).user.create({ data: { id: testUser1Id, name: "test-user-1" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser2Id, name: "test-user-2" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser3Id, name: "test-user-3" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser4Id, name: "test-user-4" }, }); loggedInUser.id = testUser1Id; const workspaceSlug = (await createWorkspace()).data?.createWorkspace .slug as string; await createMembership({ userId: testUser2Id, workspaceSlug, role: MembershipRole.Admin, }); await createMembership({ userId: testUser3Id, workspaceSlug, role: MembershipRole.Admin, }); const { data } = await client.query<{ users: Pick<User, "id" | "name">[]; }>({ query: gql` { users { id name } } `, fetchPolicy: "no-cache", }); expect(data.users.map((userData) => userData.name)).toEqual([ "test-user-1", "test-user-2", "test-user-3", ]); }); it("can skip results", async () => { await ( await getPrismaClient() ).user.create({ data: { id: testUser1Id, name: "test-user-1" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser2Id, name: "test-user-2" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser3Id, name: "test-user-3" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser4Id, name: "test-user-4" }, }); loggedInUser.id = testUser1Id; const workspaceSlug = (await createWorkspace()).data?.createWorkspace .slug as string; await createMembership({ userId: testUser2Id, workspaceSlug, role: MembershipRole.Admin, }); await createMembership({ userId: testUser3Id, workspaceSlug, role: MembershipRole.Admin, }); const { data } = await client.query<{ users: Pick<User, "id" | "name">[]; }>({ query: gql` { users(skip: 1) { id name } } `, fetchPolicy: "no-cache", }); expect(data.users.map((userData) => userData.name)).toEqual([ "test-user-2", "test-user-3", ]); }); it("can limit the number of results", async () => { await ( await getPrismaClient() ).user.create({ data: { id: testUser1Id, name: "test-user-1" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser2Id, name: "test-user-2" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser3Id, name: "test-user-3" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser4Id, name: "test-user-4" }, }); loggedInUser.id = testUser1Id; const workspaceSlug = (await createWorkspace()).data?.createWorkspace .slug as string; await createMembership({ userId: testUser2Id, workspaceSlug, role: MembershipRole.Admin, }); await createMembership({ userId: testUser3Id, workspaceSlug, role: MembershipRole.Admin, }); const { data } = await client.query<{ users: Pick<User, "id" | "name">[]; }>({ query: gql` { users(first: 2) { id name } } `, fetchPolicy: "no-cache", }); expect(data.users.map((userData) => userData.name)).toEqual([ "test-user-1", "test-user-2", ]); }); it("can limit the number of results and skip some", async () => { await ( await getPrismaClient() ).user.create({ data: { id: testUser1Id, name: "test-user-1" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser2Id, name: "test-user-2" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser3Id, name: "test-user-3" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser4Id, name: "test-user-4" }, }); loggedInUser.id = testUser1Id; const workspaceSlug = (await createWorkspace()).data?.createWorkspace .slug as string; await createMembership({ userId: testUser2Id, workspaceSlug, role: MembershipRole.Admin, }); await createMembership({ userId: testUser3Id, workspaceSlug, role: MembershipRole.Admin, }); const { data } = await client.query<{ users: Pick<User, "id" | "name">[]; }>({ query: gql` { users(skip: 1, first: 1) { id name } } `, fetchPolicy: "no-cache", }); expect(data.users.map((userData) => userData.name)).toEqual([ "test-user-2", ]); }); }); describe("user query", () => { const queryUser = async (id: string) => await client.query<{ user: Pick<User, "id" | "name">; }>({ query: gql` query user($id: ID!) { user(where: { id: $id }) { id name } } `, variables: { id }, fetchPolicy: "no-cache", }); it("returns the user corresponding to the given id", async () => { await ( await getPrismaClient() ).user.create({ data: { id: testUser1Id, name: "test-user-1" }, }); loggedInUser.id = testUser1Id; await createWorkspace(); const { data } = await queryUser(testUser1Id); expect(data.user.name).toEqual("test-user-1"); }); it("throws if the user does not access to the user", async () => { await ( await getPrismaClient() ).user.create({ data: { id: testUser1Id, name: "test-user-1" }, }); await ( await getPrismaClient() ).user.create({ data: { id: testUser2Id, name: "test-user-2" }, }); loggedInUser.id = testUser2Id; await expect(queryUser(testUser1Id)).rejects.toThrow( "User not authorized to access user" ); }); it("throws if the provided id doesn't match any user", async () => { const idOfAnUserThaDoesNotExist = uuidV4(); await expect(() => queryUser(idOfAnUserThaDoesNotExist)).rejects.toThrow( `User not authorized to access user` ); }); }); describe("updateUser mutation", () => { const updateUser = async ({ id, name, image, }: { id: string; name?: string; image?: string; }) => await client.mutate<{ updateUser: Pick<User, "id" | "name">; }>({ mutation: gql` mutation updateUser($id: ID!, $data: UserUpdateInput!) { updateUser(where: { id: $id }, data: $data) { id name image } } `, variables: { id, data: { name, image } }, fetchPolicy: "no-cache", }); it("can change the user name", async () => { await ( await getPrismaClient() ).user.create({ data: { id: testUser1Id, name: "test-user-1" }, }); user.id = testUser1Id; const { data } = await updateUser({ id: testUser1Id, name: "New name", }); expect(data?.updateUser.name).toEqual("New name"); }); it("can change the user image", async () => { await ( await getPrismaClient() ).user.create({ data: { id: testUser1Id, name: "test-user-1" }, }); user.id = testUser1Id; const { data } = await updateUser({ id: testUser1Id, name: "New image", }); expect(data?.updateUser.name).toEqual("New image"); }); it("throws if a user tries to update another user", async () => { await ( await getPrismaClient() ).user.create({ data: { id: testUser1Id, name: "test-user-1" }, }); user.id = testUser2Id; await expect(() => updateUser({ id: testUser1Id, name: "New image", }) ).rejects.toThrow("User not authorized to access user"); }); it("throws if the membership to update doesn't exist", async () => { const idOfAnUserThaDoesNotExist = uuidV4(); await expect(() => updateUser({ id: idOfAnUserThaDoesNotExist, name: "This will fail anyway", }) ).rejects.toThrow(); }); }); describe("nested resolvers", () => { it("can return user's memberships", async () => { await ( await getPrismaClient() ).user.create({ data: { id: testUser1Id, name: "test-user-1" }, }); loggedInUser.id = testUser1Id; await createWorkspace({ name: "test" }); const { data } = await client.query<{ user: Pick<User, "id" | "memberships">; }>({ query: gql` query user($id: ID!) { user(where: { id: $id }) { id memberships { id workspace { id } } } } `, variables: { id: testUser1Id }, fetchPolicy: "no-cache", }); expect(data.user.memberships.length).toEqual(1); }); });
the_stack
import { AppCredentials, TokenStatus } from 'botframework-connector'; import { CustomWebAdapter } from '@botbuildercommunity/core'; import { AlexaContextExtensions } from './alexaContextExtensions'; import { AlexaMessageMapper } from './alexaMessageMapper'; import { Activity, ActivityTypes, TurnContext, ConversationReference, ResourceResponse, WebRequest, WebResponse, TokenResponse } from 'botbuilder'; import { RequestEnvelope, ResponseEnvelope } from 'ask-sdk-model'; import { SkillRequestSignatureVerifier, TimestampVerifier } from 'ask-sdk-express-adapter'; /** * @module botbuildercommunity/adapter-alexa */ /** * Settings used to configure a `AlexaAdapter` instance. */ export interface AlexaAdapterSettings { /** * https://developer.amazon.com/en-US/docs/alexa/echo-button-skills/keep-session-open.html * @default true */ shouldEndSessionByDefault?: boolean; /** * @default false */ tryConvertFirstActivityAttachmentToAlexaCard?: boolean; /** * This prevents a malicious developer from configuring a skill with your endpoint and then using that skill to send requests to your service. * https://developer.amazon.com/en-US/docs/alexa/custom-skills/handle-requests-sent-by-alexa.html * @default true */ validateIncomingAlexaRequests?: boolean; } /** * Bot Framework Adapter for Alexa */ export class AlexaAdapter extends CustomWebAdapter { public static readonly channel: string = 'alexa'; protected readonly settings: AlexaAdapterSettings; /** * Creates a new AlexaAdapter instance. * @param settings configuration settings for the adapter. */ public constructor(settings?: AlexaAdapterSettings) { super(); const defaultSettings: AlexaAdapterSettings = { shouldEndSessionByDefault: true, tryConvertFirstActivityAttachmentToAlexaCard: false, validateIncomingAlexaRequests: true }; this.settings = { ...defaultSettings, ...settings }; } /** * Sends a set of outgoing activities to the appropriate channel server. * * @param context Context for the current turn of conversation with the user. * @param activities List of activities to send. */ public async sendActivities(context: TurnContext, activities: Partial<Activity>[]): Promise<ResourceResponse[]> { const responses: ResourceResponse[] = []; const messageActivities: Partial<Activity>[] = []; for (let i = 0; i < activities.length; i++) { const activity: Partial<Activity> = activities[i]; switch (activity.type) { case 'delay': AlexaContextExtensions.sendProgressiveResponse(context, `<break time="${ typeof activity.value === 'number' ? activity.value : 1000 }ms"/>`); responses.push({} as ResourceResponse); break; case ActivityTypes.Message: if (!activity.conversation || !activity.conversation.id) { throw new Error(`AlexaAdapter.sendActivities(): Activity doesn't contain a conversation id.`); } // eslint-disable-next-line no-case-declarations messageActivities.push(activity); responses.push({ id: activity.id }); break; default: responses.push({} as ResourceResponse); console.warn(`AlexaAdapter.sendActivities(): Activities of type '${ activity.type }' aren't supported.`); } } const activity = this.processOutgoingActivities(messageActivities); if (!activity) { return responses; } const alexaResponse = AlexaMessageMapper.activityToAlexaResponse(activity, this.settings); // Create Alexa response const responseEnvelope: ResponseEnvelope = { version: '1.0', response: alexaResponse }; context.turnState.set('httpBody', responseEnvelope); return responses; } /** * Concatenates outgoing activities into a single activity. If any of the activities being processed * contains an outer SSML speak tag within the value of the Speak property, these are removed from the individual activities and a <speak> * tag is wrapped around the resulting concatenated string. An SSML strong break tag is added between activity * content. For more infomation about the supported SSML for Alexa see * [Speech Synthesis Markup Language (SSML) Reference](https://developer.amazon.com/en-US/docs/alexa/custom-skills/speech-synthesis-markup-language-ssml-reference.html#break) * @param activities */ public processOutgoingActivities(activities: Partial<Activity>[]): Partial<Activity> { if (activities.length === 0) { return; } const finalActivity = activities[0]; for (let i = 1; i < activities.length; i++) { const activity = activities[i]; // Merge text if (activity.text) { finalActivity.text = finalActivity.text + ' ' + activity.text; } // Merge speech if (activity.speak) { finalActivity.speak = finalActivity.speak + '<break strength="strong"/>' + activity.speak; } // Merge attachments if (activity.attachments?.length > 0) { finalActivity.attachments = [...finalActivity.attachments, ...activity.attachments]; } } if (finalActivity.speak) { finalActivity.speak = finalActivity.speak.replace(/<speak>/ig, ''); finalActivity.speak = finalActivity.speak.replace(/<\/speak>/ig, ''); finalActivity.speak = `<speak>${ finalActivity.speak }</speak>`; } return finalActivity; } // eslint-disable-next-line @typescript-eslint/no-unused-vars public async updateActivity(context: TurnContext, activity: Partial<Activity>): Promise<void> { throw new Error('Method not supported by Alexa API.'); } // eslint-disable-next-line @typescript-eslint/no-unused-vars public async deleteActivity(context: TurnContext, reference: Partial<ConversationReference>): Promise<void> { throw new Error('Method not supported by Alexa API.'); } /** * TODO IMPLEMENT https://developer.amazon.com/en-US/docs/alexa/smapi/proactive-events-api.html * @param reference * @param logic */ public async continueConversation(reference: Partial<ConversationReference>, logic: (context: TurnContext) => Promise<void>): Promise<void> { const request: Partial<Activity> = TurnContext.applyConversationReference( { type: 'event', name: 'continueConversation' }, reference, true ); const context: TurnContext = this.createContext(request); return this.runMiddleware(context, logic); } /** * Processes an incoming request received by the bots web server into a TurnContext. * * @param req An Express or Restify style Request object. * @param res An Express or Restify style Response object. * @param logic A function handler that will be called to perform the bots logic after the received activity has been pre-processed by the adapter and routed through any middleware for processing. */ public async processActivity(req: WebRequest, res: WebResponse, logic: (context: TurnContext) => Promise<any>): Promise<void> { const alexaRequestBody: RequestEnvelope = await this.retrieveBody(req); if (this.settings.validateIncomingAlexaRequests) { // Verify if request is a valid request from Alexa // https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-web-service.html#verify-request-sent-by-alexa try { await new SkillRequestSignatureVerifier().verify(JSON.stringify(alexaRequestBody), req.headers); await new TimestampVerifier().verify(JSON.stringify(alexaRequestBody)); } catch (error) { console.warn(`AlexaAdapter.processActivity(): ${ error.toString() }`); res.status(400); res.send(`${ error.toString() }`); return; } } const activity = AlexaMessageMapper.alexaRequestToActivity(alexaRequestBody); // Create a Conversation Reference const context: TurnContext = this.createContext(activity); context.turnState.set('httpStatus', 200); await this.runMiddleware(context, logic); // Send HTTP response back res.status(context.turnState.get('httpStatus')); if (context.turnState.get('httpBody')) { res.send(context.turnState.get('httpBody')); } else { res.end(); } } /** * Allows for the overriding of the context object in unit tests and derived adapters. * @param request Received request. */ protected createContext(request: Partial<Activity>): TurnContext { return new TurnContext(this as any, request); } /** * Asynchronously attempts to retrieve the token for a user that's in a login flow. * * @param context The context object for the turn. * @param connectionName The name of the auth connection to use. * @param magicCode Optional. The validation code the user entered. * @param oAuthAppCredentials AppCredentials for OAuth. * * @returns A [TokenResponse](xref:botframework-schema.TokenResponse) object that contains the user token. */ public async getUserToken(context: TurnContext, connectionName?: string, magicCode?: string): Promise<TokenResponse>; public async getUserToken(context: TurnContext, connectionName?: string, magicCode?: string, oAuthAppCredentials?: AppCredentials): Promise<TokenResponse>; public async getUserToken(context: TurnContext, connectionName?: string, magicCode?: string, oAuthAppCredentials?: AppCredentials): Promise<TokenResponse> { if (!context.activity.from || !context.activity.from.id) { throw new Error(`CustomWebAdapter.getUserToken(): missing from or from.id`); } // Retrieve Alexa OAuth token from context const alexaBody = AlexaContextExtensions.getAlexaRequestBody(context); const result: Partial<TokenResponse> = { connectionName: 'AlexaAccountLinking', token: alexaBody.session?.user?.accessToken }; return new Promise<TokenResponse>((resolve, reject) => { if (!result || !result.token) { resolve(undefined); } else { resolve(result as TokenResponse); } }); } /** * Asynchronously retrieves the token status for each configured connection for the given user. * * @param context The context object for the turn. * @param userId Optional. If present, the ID of the user to retrieve the token status for. * Otherwise, the ID of the user who sent the current activity is used. * @param includeFilter Optional. A comma-separated list of connection's to include. If present, * the `includeFilter` parameter limits the tokens this method returns. * @param oAuthAppCredentials AppCredentials for OAuth. * * @returns The [TokenStatus](xref:botframework-connector.TokenStatus) objects retrieved. */ public async getTokenStatus(context: TurnContext, userId?: string, includeFilter?: string): Promise<TokenStatus[]>; public async getTokenStatus(context: TurnContext, userId?: string, includeFilter?: string, oAuthAppCredentials?: AppCredentials): Promise<TokenStatus[]>; public async getTokenStatus(context: TurnContext, userId?: string, includeFilter?: string, oAuthAppCredentials?: AppCredentials): Promise<TokenStatus[]> { if (!userId && (!context.activity.from || !context.activity.from.id)) { throw new Error(`CustomWebAdapter.getTokenStatus(): missing from or from.id`); } // Retrieve Alexa OAuth token from context const alexaBody = AlexaContextExtensions.getAlexaRequestBody(context); const token = alexaBody.session?.user?.accessToken; const tokenStatus: Partial<TokenStatus> = { hasToken: (token ? true : false) }; return new Promise<TokenStatus[]>((resolve, reject) => { resolve([tokenStatus]); }); } /** * Asynchronously signs out the user from the token server. * * @param context The context object for the turn. * @param connectionName The name of the auth connection to use. * @param userId The ID of user to sign out. * @param oAuthAppCredentials AppCredentials for OAuth. */ public async signOutUser(context: TurnContext, connectionName?: string, userId?: string): Promise<void>; public async signOutUser(context: TurnContext, connectionName?: string, userId?: string, oAuthAppCredentials?: AppCredentials): Promise<void> { throw new Error('Method not supported by Alexa API.'); } /** * Asynchronously gets a sign-in link from the token server that can be sent as part * of a [SigninCard](xref:botframework-schema.SigninCard). * * @param context The context object for the turn. * @param connectionName The name of the auth connection to use. * @param oAuthAppCredentials AppCredentials for OAuth. * @param userId The user id that will be associated with the token. * @param finalRedirect The final URL that the OAuth flow will redirect to. */ public async getSignInLink(context: TurnContext, connectionName: string, oAuthAppCredentials?: AppCredentials, userId?: string, finalRedirect?: string): Promise<string> { if (userId && userId != context.activity.from.id) { throw new ReferenceError(`cannot retrieve OAuth signin link for a user that's different from the conversation`); } // Send empty string back to not break SignInCard return new Promise<string>((resolve, reject) => { resolve(''); }); } }
the_stack
import { test } from 'uvu' import * as assert from 'uvu/assert' import { snoop } from 'snoop' import { createStore, createEvent } from 'effector' import { createHistoryMock } from './mocks/history.mock' import { createLocationMock } from './mocks/location.mock' import { createEventsMock } from './mocks/events.mock' import { persist, pushState, replaceState, locationAssign, locationReplace, } from '../src/query' // // Mock history, location and events // declare let global: any let events: ReturnType<typeof createEventsMock> test.before.each(() => { global.history = createHistoryMock(null, '', 'http://domain.test') global.location = createLocationMock('http://domain.test') global.history._location(global.location) global.location._history(global.history) events = createEventsMock() global.addEventListener = events.addEventListener }) test.after.each(() => { delete global.history delete global.location delete global.addEventListener }) // // Tests // test('should export adapter and `persist` function', () => { assert.type(persist, 'function') assert.type(pushState, 'function') assert.type(replaceState, 'function') assert.type(locationAssign, 'function') assert.type(locationReplace, 'function') }) test('should be ok on good parameters', () => { const $store = createStore('0', { name: 'query::store' }) assert.not.throws(() => persist({ store: $store })) }) test('store initial value should NOT be put in query string', () => { const $id = createStore('0', { name: 'id' }) persist({ store: $id }) assert.is(global.location.search, '') }) test('store new value should be put in query string', () => { const $id = createStore('0', { name: 'id' }) persist({ store: $id }) assert.is(global.location.search, '') ;($id as any).setState('42') assert.is(global.location.search, '?id=42') }) test('should change store value to default, in case history go back', async () => { const $id = createStore('1212', { name: 'id' }) persist({ store: $id }) assert.is(global.location.search, '') ;($id as any).setState('4242') assert.is(global.location.search, '?id=4242') global.history.back() await events.dispatchEvent('popstate', null) await new Promise((resolve) => setTimeout(resolve, 10)) assert.is(global.location.search, '') assert.is($id.getState(), '1212') }) test('store value should be set from query string', () => { global.history = createHistoryMock(null, '', 'http://domain.test?id=111') global.location = createLocationMock('http://domain.test?id=111') global.history._location(global.location) global.location._history(global.history) const $id = createStore('0', { name: 'id' }) persist({ store: $id }) assert.is($id.getState(), '111') }) test('store delete query string parameter in case of store null value', () => { global.history = createHistoryMock(null, '', 'http://domain.test?id=7777') global.location = createLocationMock('http://domain.test?id=7777') global.history._location(global.location) global.location._history(global.history) const $id = createStore('0', { name: 'id' }) persist({ store: $id }) assert.is($id.getState(), '7777') ;($id as any).setState(null) assert.is(global.location.search, '') }) test('should preserve url hash part', () => { global.history = createHistoryMock( null, '', 'http://domain.test?id=8888#test' ) global.location = createLocationMock('http://domain.test?id=8888#test') global.history._location(global.location) global.location._history(global.history) assert.is(global.location.hash, '#test') const $id = createStore('0', { name: 'id' }) persist({ store: $id }) assert.is($id.getState(), '8888') ;($id as any).setState(null) assert.is(global.location.search, '') assert.is(global.location.hash, '#test') ;($id as any).setState('9999') assert.is(global.location.search, '?id=9999') assert.is(global.location.hash, '#test') }) test('should use `pushState` by default', () => { const snoopPushState = snoop(() => undefined) const snoopReplaceState = snoop(() => undefined) const snoopLocationAssign = snoop(() => undefined) const snoopLocationReplace = snoop(() => undefined) global.history._callbacks({ pushState: snoopPushState.fn, replaceState: snoopReplaceState.fn, }) global.location._callbacks({ assign: snoopLocationAssign.fn, replace: snoopLocationReplace.fn, }) const $id = createStore('0', { name: 'id' }) persist({ store: $id }) assert.is(global.location.search, '') assert.is(global.history.length, 1) ;($id as any).setState('123') assert.is(global.location.search, '?id=123') assert.is(global.history.length, 2) assert.is(snoopPushState.callCount, 1) assert.is(snoopReplaceState.callCount, 0) assert.is(snoopLocationAssign.callCount, 0) assert.is(snoopLocationReplace.callCount, 0) assert.equal(snoopPushState.calls[0].arguments, [null, '', '/?id=123']) }) test('should preserve state by default', () => { global.history = createHistoryMock({ test: 'test' }, '', 'http://domain.test') global.location = createLocationMock('http://domain.test') global.history._location(global.location) global.location._history(global.history) const snoopPushState = snoop(() => undefined) const snoopReplaceState = snoop(() => undefined) const snoopLocationAssign = snoop(() => undefined) const snoopLocationReplace = snoop(() => undefined) global.history._callbacks({ pushState: snoopPushState.fn, replaceState: snoopReplaceState.fn, }) global.location._callbacks({ assign: snoopLocationAssign.fn, replace: snoopLocationReplace.fn, }) const $id = createStore('0', { name: 'id' }) persist({ store: $id }) assert.is(global.location.search, '') assert.is(global.history.length, 1) ;($id as any).setState('111') assert.is(global.location.search, '?id=111') assert.is(global.history.length, 2) assert.is(snoopPushState.callCount, 1) assert.is(snoopReplaceState.callCount, 0) assert.is(snoopLocationAssign.callCount, 0) assert.is(snoopLocationReplace.callCount, 0) assert.equal(snoopPushState.calls[0].arguments, [ { test: 'test' }, '', '/?id=111', ]) }) test('should erase state if state="erase"', () => { global.history = createHistoryMock({ test: 'test' }, '', 'http://domain.test') global.location = createLocationMock('http://domain.test') global.history._location(global.location) global.location._history(global.history) const snoopPushState = snoop(() => undefined) const snoopReplaceState = snoop(() => undefined) const snoopLocationAssign = snoop(() => undefined) const snoopLocationReplace = snoop(() => undefined) global.history._callbacks({ pushState: snoopPushState.fn, replaceState: snoopReplaceState.fn, }) global.location._callbacks({ assign: snoopLocationAssign.fn, replace: snoopLocationReplace.fn, }) const $id = createStore('0', { name: 'id' }) persist({ store: $id, state: 'erase' }) assert.is(global.location.search, '') assert.is(global.history.length, 1) ;($id as any).setState('222') assert.is(global.location.search, '?id=222') assert.is(global.history.length, 2) assert.is(snoopPushState.callCount, 1) assert.is(snoopReplaceState.callCount, 0) assert.is(snoopLocationAssign.callCount, 0) assert.is(snoopLocationReplace.callCount, 0) assert.equal(snoopPushState.calls[0].arguments, [null, '', '/?id=222']) }) test('use `pushState` explicitly', () => { const snoopPushState = snoop(() => undefined) const snoopReplaceState = snoop(() => undefined) const snoopLocationAssign = snoop(() => undefined) const snoopLocationReplace = snoop(() => undefined) global.history._callbacks({ pushState: snoopPushState.fn, replaceState: snoopReplaceState.fn, }) global.location._callbacks({ assign: snoopLocationAssign.fn, replace: snoopLocationReplace.fn, }) const $id = createStore('0', { name: 'id' }) persist({ store: $id, method: pushState }) assert.is(global.location.search, '') assert.is(global.history.length, 1) ;($id as any).setState('987') assert.is(global.location.search, '?id=987') assert.is(global.history.length, 2) assert.is(snoopPushState.callCount, 1) assert.is(snoopReplaceState.callCount, 0) assert.is(snoopLocationAssign.callCount, 0) assert.is(snoopLocationReplace.callCount, 0) assert.equal(snoopPushState.calls[0].arguments, [null, '', '/?id=987']) }) test('use of `replaceState` explicitly', () => { const snoopPushState = snoop(() => undefined) const snoopReplaceState = snoop(() => undefined) const snoopLocationAssign = snoop(() => undefined) const snoopLocationReplace = snoop(() => undefined) global.history._callbacks({ pushState: snoopPushState.fn, replaceState: snoopReplaceState.fn, }) global.location._callbacks({ assign: snoopLocationAssign.fn, replace: snoopLocationReplace.fn, }) const $id = createStore('0', { name: 'id' }) persist({ store: $id, method: replaceState }) assert.is(global.location.search, '') assert.is(global.history.length, 1) ;($id as any).setState('321') assert.is(global.location.search, '?id=321') assert.is(global.history.length, 1) assert.is(snoopPushState.callCount, 0) assert.is(snoopReplaceState.callCount, 1) assert.is(snoopLocationAssign.callCount, 0) assert.is(snoopLocationReplace.callCount, 0) assert.equal(snoopReplaceState.calls[0].arguments, [null, '', '/?id=321']) }) test('`replaceState` should erase state if state="erase"', () => { global.history = createHistoryMock({ test: 'test' }, '', 'http://domain.test') global.location = createLocationMock('http://domain.test') global.history._location(global.location) global.location._history(global.history) const snoopPushState = snoop(() => undefined) const snoopReplaceState = snoop(() => undefined) const snoopLocationAssign = snoop(() => undefined) const snoopLocationReplace = snoop(() => undefined) global.history._callbacks({ pushState: snoopPushState.fn, replaceState: snoopReplaceState.fn, }) global.location._callbacks({ assign: snoopLocationAssign.fn, replace: snoopLocationReplace.fn, }) const $id = createStore('0', { name: 'id' }) persist({ store: $id, method: replaceState, state: 'erase' }) assert.is(global.location.search, '') assert.is(global.history.length, 1) ;($id as any).setState('123123') assert.is(global.location.search, '?id=123123') assert.is(global.history.length, 1) assert.is(snoopPushState.callCount, 0) assert.is(snoopReplaceState.callCount, 1) assert.is(snoopLocationAssign.callCount, 0) assert.is(snoopLocationReplace.callCount, 0) assert.equal(snoopReplaceState.calls[0].arguments, [null, '', '/?id=123123']) }) test('use of `locationAssign` explicitly', () => { const snoopPushState = snoop(() => undefined) const snoopReplaceState = snoop(() => undefined) const snoopLocationAssign = snoop(() => undefined) const snoopLocationReplace = snoop(() => undefined) global.history._callbacks({ pushState: snoopPushState.fn, replaceState: snoopReplaceState.fn, }) global.location._callbacks({ assign: snoopLocationAssign.fn, replace: snoopLocationReplace.fn, }) const $id = createStore('0', { name: 'id' }) persist({ store: $id, method: locationAssign }) assert.is(global.location.search, '') assert.is(global.history.length, 1) ;($id as any).setState('345') assert.is(global.location.search, '?id=345') assert.is(global.history.length, 2) assert.is(snoopPushState.callCount, 0) assert.is(snoopReplaceState.callCount, 0) assert.is(snoopLocationAssign.callCount, 1) assert.is(snoopLocationReplace.callCount, 0) assert.equal(snoopLocationAssign.calls[0].arguments, ['/?id=345']) }) test('use of `locationReplace` explicitly', () => { const snoopPushState = snoop(() => undefined) const snoopReplaceState = snoop(() => undefined) const snoopLocationAssign = snoop(() => undefined) const snoopLocationReplace = snoop(() => undefined) global.history._callbacks({ pushState: snoopPushState.fn, replaceState: snoopReplaceState.fn, }) global.location._callbacks({ assign: snoopLocationAssign.fn, replace: snoopLocationReplace.fn, }) const $id = createStore('0', { name: 'id' }) persist({ store: $id, method: locationReplace }) assert.is(global.location.search, '') assert.is(global.history.length, 1) ;($id as any).setState('555') assert.is(global.location.search, '?id=555') assert.is(global.history.length, 1) assert.is(snoopPushState.callCount, 0) assert.is(snoopReplaceState.callCount, 0) assert.is(snoopLocationAssign.callCount, 0) assert.is(snoopLocationReplace.callCount, 1) assert.equal(snoopLocationReplace.calls[0].arguments, ['/?id=555']) }) test('should work with source/target (issue #20)', () => { const watchSource = snoop(() => undefined) const watchTarget = snoop(() => undefined) global.history = createHistoryMock(null, '', 'http://domain.test?id=20_1_1') global.location = createLocationMock('http://domain.test?id=20_1_1') global.history._location(global.location) global.location._history(global.history) const source = createEvent<string>() const target = createEvent<string>() source.watch(watchSource.fn) target.watch(watchTarget.fn) persist({ source, target, key: 'id', }) // pass initial query state to target assert.is(global.location.search, '?id=20_1_1') assert.is(watchSource.callCount, 0) assert.is(watchTarget.callCount, 2) // first and second // fix later? assert.equal(watchTarget.calls[0].arguments, ['20_1_1']) assert.equal(watchTarget.calls[1].arguments, ['20_1_1']) // set new value to source -> should pass to query state source('20_1_2') assert.is(global.location.search, '?id=20_1_2') assert.is(watchSource.callCount, 1) assert.is(watchTarget.callCount, 3) assert.equal(watchSource.calls[0].arguments, ['20_1_2']) assert.equal(watchTarget.calls[2].arguments, ['20_1_2']) }) test('should work with source/target with default state (issue #20)', () => { const watchTarget = snoop(() => undefined) global.history = createHistoryMock(null, '', 'http://domain.test') global.location = createLocationMock('http://domain.test') global.history._location(global.location) global.location._history(global.history) const source = createEvent<string | null>() const target = createEvent<string | null>() target.watch(watchTarget.fn) persist({ source, target, key: 'id', def: '20_2_0', }) // pass default value to target assert.is(global.location.search, '') assert.is(watchTarget.callCount, 2) // first and second // fix later? assert.equal(watchTarget.calls[0].arguments, ['20_2_0']) assert.equal(watchTarget.calls[1].arguments, ['20_2_0']) }) // // Launch tests // test.run()
the_stack
import * as assert from 'assert'; import rewire = require('rewire'); import sinon = require('sinon'); import { Constants } from '../../src/Constants'; import { AzureBlockchainServiceValidator } from '../../src/validators/AzureBlockchainServiceValidator'; const { azureBlockchainResourceName, password, resourceGroup } = Constants.lengthParam; describe('Azure Blockchain Service Validator', () => { const emptyValues = ['', ' ']; const { valueCannotBeEmpty, noLowerCaseLetter, noUpperCaseLetter, noDigits, noSpecialChars, lengthRange, unresolvedSymbols, forbiddenChars, invalidResourceGroupName, invalidAzureName } = Constants.validationMessages; describe('Unit tests', () => { describe('accessPasswordValidator', () => { emptyValues.forEach((testPassword) => { it(`returns error message when password is empty: '${testPassword}'`, async () => { // Arrange, Act const result = await AzureBlockchainServiceValidator.validateAccessPassword(testPassword) as string; // Assert assert.strictEqual(result.includes(valueCannotBeEmpty), true, 'empty password should be invalid'); }); }); it('returns error message when password has no lower case letter', async () => { // Arrange const invalidPassword = 'AAAAAA111!!!'; // Act const result = await AzureBlockchainServiceValidator.validateAccessPassword(invalidPassword); // Assert assert.strictEqual(result, noLowerCaseLetter, 'password without lower case should be invalid'); }); it('returns error message when password has no upper case letter', async () => { // Arrange const invalidPassword = 'aaaaaa111!!!'; // Act const result = await AzureBlockchainServiceValidator.validateAccessPassword(invalidPassword); // Assert assert.strictEqual(result, noUpperCaseLetter, 'password without upper case should be invalid'); }); it('returns error message when password has no digit', async () => { // Arrange const invalidPassword = 'AAAaaaAAA!!!'; // Act const result = await AzureBlockchainServiceValidator.validateAccessPassword(invalidPassword); // Assert assert.strictEqual(result, noDigits, 'password without digit should be invalid'); }); it('returns error message when password has no special char', async () => { // Arrange const invalidPassword = 'AAAaaa111222'; // Act const result = await AzureBlockchainServiceValidator.validateAccessPassword(invalidPassword); // Assert assert.strictEqual(result, noSpecialChars, 'password without special char should be invalid'); }); it('returns error message when password has forbidden char', async () => { // Arrange const invalidPassword = 'AAAaaa111!!!*'; // Act const result = await AzureBlockchainServiceValidator.validateAccessPassword(invalidPassword); // Assert assert.strictEqual( result, unresolvedSymbols(forbiddenChars.password), 'password with forbidden char should be invalid'); }); const invalidPasswordLengthList = [password.min - 1, password.max + 1]; invalidPasswordLengthList.forEach((length) => { it(`returns error message when password has invalid length: '${length}'`, async () => { // Arrange const mainSymbols = 'Aa1!'; mainSymbols.repeat(25); const invalidPassword = mainSymbols.substr(0, length); // Act const result = await AzureBlockchainServiceValidator.validateAccessPassword(invalidPassword); // Assert assert.strictEqual( result, lengthRange(password.min, password.max), `password with length: ${length} should be invalid`); }); }); it('error contains several messages when several requirements failed', async () => { // Arrange const invalidPassword = 'A;'; // Act const result = await AzureBlockchainServiceValidator.validateAccessPassword(invalidPassword) as string; // Assert assert.strictEqual(result.includes(noLowerCaseLetter), true, 'error should have lower case message'); assert.strictEqual(result.includes(noDigits), true, 'error should have digits message'); assert.strictEqual(result.includes(noSpecialChars), true, 'error should have special chars message'); assert.strictEqual(result.includes( unresolvedSymbols(forbiddenChars.password)), true, 'error should have forbidden chars message'); assert.strictEqual(result.includes( lengthRange(password.min, password.max)), true, 'error should have length message'); }); }); describe('validateResourceGroupName', () => { let azureBlockchainServiceValidator: any; before(() => { azureBlockchainServiceValidator = rewire('../../src/validators/AzureBlockchainServiceValidator'); }); emptyValues.forEach((testResourceGroup) => { it(`returns error message when resource group name (${testResourceGroup}) is empty`, async () => { // Arrange, Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateResourceGroupName(testResourceGroup, { checkExistence: sinon.stub().returns(Promise.resolve(true)), }); // Assert assert.strictEqual(result, invalidResourceGroupName, 'empty resource group name should be invalid'); }); }); const resourceGroupHasDotAtTheEndList = ['.', 'a.']; resourceGroupHasDotAtTheEndList.forEach((name) => { it(`returns error message when resource group name ('${name}') ends with dot`, async () => { // Arrange, Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateResourceGroupName(name, { checkExistence: sinon.stub().returns(Promise.resolve(true)), }); // Assert assert.strictEqual( result, invalidResourceGroupName, 'resource group name with dot at the end should be invalid'); }); }); const resourceGroupHasUnavailableSymbolList = ['!', '@']; resourceGroupHasUnavailableSymbolList.forEach((name) => { it(`returns error message when resource group name ('${name}') has unavailable symbols`, async () => { // Arrange, Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateResourceGroupName(name, { checkExistence: sinon.stub().returns(Promise.resolve(true)), }); // Assert assert.strictEqual(result, invalidResourceGroupName, 'resource group name with unavailable symbols should be invalid'); }); }); const resourceGroupLengthList = [resourceGroup.min - 1, resourceGroup.max + 1]; resourceGroupLengthList.forEach((length) => { it(`returns error message when resource group name has invalid length: '${length}'`, async () => { // Arrange const mainSymbols = 'a'; const invalidResourceGroup = mainSymbols.repeat(resourceGroup.max + 1); // Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateResourceGroupName(invalidResourceGroup, { checkExistence: sinon.stub().returns(Promise.resolve(true)), }); // Assert assert.strictEqual(result, invalidResourceGroupName, `resource group name length: ${length} should be invalid`); }); }); it('returns error messages when resource group name is alreasy exist', async () => { // Arrange const existingResourceGroupName = 'resourceGroupName'; // Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateResourceGroupName(existingResourceGroupName, { checkExistence: sinon.stub().returns(Promise.resolve({ message: null, nameAvailable: false, reason: Constants.responseReason.alreadyExists, })), }); // Assert assert.strictEqual( result, Constants.validationMessages.resourceGroupAlreadyExists(existingResourceGroupName), 'resource group name should be exist'); }); const validResourceGroupNameList = ['-', '_', '(', ')', '1', 'rg', 'RG', 'a.a', '.a']; validResourceGroupNameList.forEach((name) => { it(`resource group name (${name}) should be valid`, async () => { // Arrange, Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateResourceGroupName(name, { checkExistence: sinon.stub().returns(Promise.resolve(false)), }); // Assert assert.strictEqual(result, null, 'resource group name should be valid'); }); }); const resourceGroupHasValidLengthList = [resourceGroup.min, resourceGroup.max]; resourceGroupHasValidLengthList.forEach((length) => { it(`resource group name should be valid with length: ${length}`, async () => { // Arrange const mainSymbols = 'a'; const validResourceGroup = mainSymbols.repeat(length); // Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateResourceGroupName(validResourceGroup, { checkExistence: sinon.stub().returns(Promise.resolve(false)), }); // Assert assert.strictEqual(result, null, `resource group name should be valid with length: ${length}`); }); }); }); describe('validateAzureBlockchainResourceName', () => { let azureBlockchainServiceValidator: any; before(() => { azureBlockchainServiceValidator = rewire('../../src/validators/AzureBlockchainServiceValidator'); }); emptyValues.forEach((consortiumName) => { it(`returns error message when consortium name (${consortiumName}) is empty`, async () => { // Arrange, Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateAzureBlockchainResourceName(consortiumName, { checkExistence: sinon.stub().returns(Promise.resolve(true)), }); // Assert assert.strictEqual(result, invalidAzureName, 'empty consortium name should be invalid'); }); }); const consortiumNameLengthList = [ azureBlockchainResourceName.min - 1, azureBlockchainResourceName.max + 1, ]; consortiumNameLengthList.forEach((length) => { it(`returns error message when consortium name has invalid length: '${length}'`, async () => { // Arrange const mainSymbols = 'a'; const invalidConsortiumName = mainSymbols.repeat(length); // Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateAzureBlockchainResourceName(invalidConsortiumName, { checkExistence: sinon.stub().returns(Promise.resolve(false)), }); // Assert assert.strictEqual(result, invalidAzureName, `consortium name length: ${length} should be invalid`); }); }); const consortiumNameWithUpperCaseLetterList = ['aA', 'Aa']; consortiumNameWithUpperCaseLetterList.forEach((name) => { it(`returns error message when consortium name ('${name}') has upper case letter`, async () => { // Arrange, Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateAzureBlockchainResourceName(name, { checkExistence: sinon.stub().returns(Promise.resolve(false)), }); // Assert assert.strictEqual(result, invalidAzureName, 'consortium name with upper case should be invalid'); }); }); const consortiumNameDigitAtFirstPlaceList = ['1a', '11']; consortiumNameDigitAtFirstPlaceList.forEach((name) => { it(`returns error message when consortium name ('${name}') has digit at first place`, async () => { // Arrange, Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateAzureBlockchainResourceName(name, { checkExistence: sinon.stub().returns(Promise.resolve(false)), }); // Assert assert.strictEqual(result, invalidAzureName, 'consortium name with digit at first place should be invalid'); }); }); it('returns error message when consortium name has unavailable symbols', async () => { // Arrange const invalidConsortiumName = 'aa!'; // Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateAzureBlockchainResourceName(invalidConsortiumName, { checkExistence: sinon.stub().returns(Promise.resolve(false)), }); // Assert assert.strictEqual(result, invalidAzureName, 'consortium name with unavailable symbols should be invalid'); }); const validConsortiumNames = [ 'aa', 'a1', 'a1a', 'a'.repeat(azureBlockchainResourceName.max), 'a'.repeat(azureBlockchainResourceName.min), ]; validConsortiumNames.forEach((name) => { it(`consortium name (${name}) should be valid`, async () => { // Arrange, Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateAzureBlockchainResourceName(name, { checkExistence: sinon.stub().returns(Promise.resolve({ message: null, nameAvailable: true, reason: '', })), }); // Assert assert.strictEqual(result, null, 'consortium name should be valid'); }); }); }); describe('validateAzureBlockchainResourceName', () => { let azureBlockchainServiceValidator: any; before(() => { azureBlockchainServiceValidator = rewire('../../src/validators/AzureBlockchainServiceValidator'); }); emptyValues.forEach((memberName) => { it(`returns error message when member name (${memberName}) is empty`, async () => { // Arrange, Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateAzureBlockchainResourceName(memberName, { checkExistence: sinon.stub().returns(Promise.resolve(true)), }); // Assert assert.strictEqual(result, invalidAzureName, 'empty member name should be invalid'); }); }); const memberNameLengthList = [ azureBlockchainResourceName.min - 1, azureBlockchainResourceName.max + 1, ]; memberNameLengthList.forEach((length) => { it(`returns error message when member name has invalid length: '${length}'`, async () => { // Arrange const mainSymbols = 'a'; const invalidMemberName = mainSymbols.repeat(length); // Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateAzureBlockchainResourceName(invalidMemberName, { checkExistence: sinon.stub().returns(Promise.resolve(false)), }); // Assert assert.strictEqual(result, invalidAzureName, `member name length: ${length} should be invalid`); }); }); const memberNameWithUpperCaseLetterList = ['aA', 'Aa']; memberNameWithUpperCaseLetterList.forEach((name) => { it(`returns error message when member name ('${name}') has upper case letter`, async () => { // Arrange, Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateAzureBlockchainResourceName(name, { checkExistence: sinon.stub().returns(Promise.resolve(false)), }); // Assert assert.strictEqual(result, invalidAzureName, 'member name with upper case should be invalid'); }); }); const memberNameDigitAtFirstPlaceList = ['1a', '11']; memberNameDigitAtFirstPlaceList.forEach((name) => { it(`returns error message when member name ('${name}') has digit at first place`, async () => { // Arrange, Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateAzureBlockchainResourceName(name, { checkExistence: sinon.stub().returns(Promise.resolve(false)), }); // Assert assert.strictEqual(result, invalidAzureName, 'member name with digit at first place should be invalid'); }); }); it('returns error message when member name has unavailable symbols', async () => { // Arrange const invalidMemberName = 'aa!'; // Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateAzureBlockchainResourceName(invalidMemberName, { checkExistence: sinon.stub().returns(Promise.resolve(false)), }); // Assert assert.strictEqual(result, invalidAzureName, 'member name with unavailable symbols should be invalid'); }); const validMemberNames = [ 'aa', 'a1', 'a1a', 'a'.repeat(azureBlockchainResourceName.max), 'a'.repeat(azureBlockchainResourceName.min), ]; validMemberNames.forEach((name) => { it(`member name (${name}) should be valid`, async () => { // Arrange, Act const result = await azureBlockchainServiceValidator.AzureBlockchainServiceValidator .validateAzureBlockchainResourceName(name, { checkExistence: sinon.stub().returns(Promise.resolve({ message: null, nameAvailable: true, reason: '', })), }); // Assert assert.strictEqual(result, null, 'member name should be valid'); }); }); }); }); });
the_stack
import { Component, NgZone, OnInit, AfterViewInit, Input, Output, EventEmitter, OnDestroy, ViewChild, ElementRef, SimpleChanges } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; // services import { ConversationsService } from '../../providers/conversations.service'; import { ConversationsHandlerService } from '../../../chat21-core/providers/abstract/conversations-handler.service'; import { Globals } from '../../utils/globals'; import { getUrlImgProfile, setColorFromString, avatarPlaceholder, convertMessage, compareValues } from '../../utils/utils'; import { FIREBASESTORAGE_BASE_URL_IMAGE, IMG_PROFILE_BOT, IMG_PROFILE_DEFAULT } from '../../utils/constants'; import { WaitingService } from '../../providers/waiting.service'; import { TranslatorService } from '../../providers/translator.service'; // models import { ConversationModel } from '../../../chat21-core/models/conversation'; import { User } from '../../../models/User'; // import * as moment from 'moment/moment'; // import 'moment-duration-format'; import {HumanizeDurationLanguage, HumanizeDuration} from 'humanize-duration-ts'; import { CustomTranslateService } from '../../../chat21-core/providers/custom-translate.service'; import { ChatManager } from '../../../chat21-core/providers/chat-manager'; import { ImageRepoService } from '../../../chat21-core/providers/abstract/image-repo.service'; import { LoggerService } from '../../../chat21-core/providers/abstract/logger.service'; import { LoggerInstance } from '../../../chat21-core/providers/logger/loggerInstance'; @Component({ selector: 'chat-home-conversations', templateUrl: './home-conversations.component.html', styleUrls: ['./home-conversations.component.scss'] }) export class HomeConversationsComponent implements OnInit, OnDestroy { // ========= begin:: Input/Output values ============// @Input() listConversations: Array<ConversationModel>; // uid utente ex: JHFFkYk2RBUn87LCWP2WZ546M7d2 @Input() archivedConversations: Array<ConversationModel>; @Input() stylesMap: Map<string, string> @Output() onNewConversation = new EventEmitter<string>(); @Output() onConversationSelected = new EventEmitter<ConversationModel>(); @Output() onOpenAllConvesations = new EventEmitter(); @Output() onImageLoaded = new EventEmitter<ConversationModel>(); @Output() onConversationLoaded = new EventEmitter<ConversationModel>(); // ========= end:: Input/Output values ============// // ========= begin:: sottoscrizioni ======= // subscriptions: Subscription[] = []; /** */ // subOpenConversations; subListConversations; subArchivedConversations; // ========= end:: sottoscrizioni ======= // // ========= begin:: dichiarazione funzioni ======= // convertMessage = convertMessage; setColorFromString = setColorFromString; avatarPlaceholder = avatarPlaceholder; getUrlImgProfile = getUrlImgProfile; // ========= end:: dichiarazione funzioni ========= // // ========= begin:: variabili del componente ======= // // conversations: ConversationModel[]; //listConversations: Array<ConversationModel>; // archivedConversations: Array<ConversationModel>; tenant = ''; themeColor = ''; themeForegroundColor = ''; LABEL_START_NW_CONV: string; availableAgents: Array<User> = []; // ========= end:: variabili del componente ======== // waitingTime: Number; langService: HumanizeDurationLanguage = new HumanizeDurationLanguage(); humanizer: HumanizeDuration; humanWaitingTime: string; WAITING_TIME_FOUND_WITH_REPLYTIME_PLACEHOLDER: string //new translationMapConversation: Map<string, string>; private logger: LoggerService = LoggerInstance.getInstance(); constructor( public g: Globals, private ngZone: NgZone, // public conversationsService: ConversationsService, // public conversationsHandlerService: ConversationsHandlerService, public imageRepoService: ImageRepoService, public chatManager: ChatManager, public waitingService: WaitingService, public translatorService: TranslatorService, private customTranslateService: CustomTranslateService, ) { // console.log(this.langService); // https://www.npmjs.com/package/humanize-duration-ts // https://github.com/Nightapes/HumanizeDuration.ts/blob/master/src/humanize-duration.ts this.humanizer = new HumanizeDuration(this.langService); this.humanizer.setOptions({round: true}); this.initialize(); } ngOnInit() { this.logger.debug('[HOMECONVERSATIONS]---ngOnInit--- ', this.listConversations); } public initTranslations() { const keysConversation = ['CLOSED']; const keys = ['YOU']; const translationMap = this.customTranslateService.translateLanguage(keys); this.translationMapConversation = this.customTranslateService.translateLanguage(keysConversation); } // ========= begin:: ACTIONS ============// onConversationSelectedFN(conversation: ConversationModel) { if(conversation){ // rimuovo classe animazione //this.removeAnimation(); this.onConversationSelected.emit(conversation); } } // ========= end:: ACTIONS ============// // showConversations() { // this.logger.debug(' showConversations:::: ', this.listConversations.length]); // const that = this; // let subListConversations; // if (!subListConversations) { // subListConversations = this.conversationsService.obsListConversations.subscribe((conversations) => { // that.ngZone.run(() => { // if (conversations && conversations.length > 3) { // that.listConversations = conversations.slice(0, 3); // that.logger.debug(' >3 :::: ', that.listConversations.length]); // } else if (conversations && conversations.length > 0) { // that.listConversations = conversations; // } // that.logger.debug(' conversations = 0 :::: ', that.listConversations]); // }); // }); // this.subscriptions.push(subListConversations); // } // if (!this.subArchivedConversations) { // this.subArchivedConversations = this.conversationsService.obsArchivedConversations.subscribe((conversations) => { // that.ngZone.run(() => { // that.archivedConversations = conversations; // that.logger.debug(' archivedConversations:::: ', that.archivedConversations]); // }); // }); // this.subscriptions.push(this.subArchivedConversations); // } // } initialize() { this.logger.debug('initialize: ListConversationsComponent'); this.initTranslations(); //this.senderId = this.g.senderId; this.tenant = this.g.tenant; this.LABEL_START_NW_CONV = this.g.LABEL_START_NW_CONV; // IN THE TEMPLATE REPLACED LABEL_START_NW_CONV WITH g.LABEL_START_NW_CONV this.listConversations = []; this.archivedConversations = []; this.waitingTime = -1; this.availableAgents = this.g.availableAgents.slice(0, 5) this.availableAgents.forEach(agent => { agent.imageurl = this.imageRepoService.getImagePhotoUrl(agent.id) }) //this.logger.debug('senderId: ', this.senderId]); this.logger.debug('[HOMECONVERSATIONS] tenant: ', this.tenant, this.availableAgents); // this.conversationsService.initialize(this.senderId, this.tenant); // this.conversationsService.checkListConversations(); // this.conversationsService.checkListArchivedConversations(); // this.listConversations = this.conversationsService.listConversations; // this.conversationsHandlerService.initialize(this.tenant,this.senderId, translationMap) // this.conversationsHandlerService.connect(); // this.listConversations = this.conversationsHandlerService.conversations; // 6 - save conversationHandler in chatManager // this.chatManager.setConversationsHandler(this.conversationsHandlerService); this.logger.debug('[HOMECONVERSATIONS] this.listConversations.length', this.listConversations.length); this.logger.debug('[HOMECONVERSATIONS] this.listConversations', this.listConversations); // if (this.g.supportMode) { // this.showWaitingTime(); // } this.showWaitingTime(); //this.showConversations(); } showWaitingTime() { const that = this; const projectid = this.g.projectid; if(projectid){ this.waitingService.getCurrent(projectid).subscribe(response => { that.logger.debug('[HOMECONVERSATIONS] response waiting', response); // console.log('response waiting ::::', response); if (response && response.length > 0 && response[0].waiting_time_avg) { const wt = response[0].waiting_time_avg; that.waitingTime = wt; that.logger.debug('[HOMECONVERSATIONS] that.waitingTime', that.waitingTime); // console.log('that.waitingTime', that.waitingTime); const lang = that.translatorService.getLanguage(); // console.log('lang', lang); that.humanWaitingTime = this.humanizer.humanize(wt, {language: lang}); // console.log('LIST CONVERSATION humanWaitingTime ', that.humanWaitingTime); // console.log('LIST CONVERSATION g.WAITING_TIME_FOUND ', this.g.WAITING_TIME_FOUND) // console.log('LIST CONVERSATION g.WAITING_TIME_FOUND contains $reply_time', this.g.WAITING_TIME_FOUND.includes("$reply_time") ) // REPLACE if (this.g.WAITING_TIME_FOUND.includes("$reply_time")) { // REPLACE if exist this.WAITING_TIME_FOUND_WITH_REPLYTIME_PLACEHOLDER = this.g.WAITING_TIME_FOUND.replace("$reply_time", that.humanWaitingTime); } // console.log('LIST CONVERSATION WAITING_TIME_FOUND_WITH_REPLYTIME_PLACEHOLDER', this.WAITING_TIME_FOUND_WITH_REPLYTIME_PLACEHOLDER) // console.log('LIST CONVERSATION g.dynamicWaitTimeReply ', this.g.dynamicWaitTimeReply ) // console.log('LIST CONVERSATION typeof g.dynamicWaitTimeReply ', typeof this.g.dynamicWaitTimeReply ) // console.log('xxx', this.humanizer.humanize(wt)); // 'The team typically replies in ' + moment.duration(response[0].waiting_time_avg).format(); } // else { // that.waitingTimeMessage = 'waiting_time_not_found'; // // that.waitingTimeMessage = 'Will reply as soon as they can'; // } }); } } checkShowAllConversation() { if (this.archivedConversations && this.archivedConversations.length > 0) { return true; } else if (this.listConversations && this.listConversations.length > 0) { return true; } return false; } // msToTime(duration) { // let milliseconds = parseInt((duration % 1000) / 100), // seconds = parseInt((duration / 1000) % 60), // minutes = parseInt((duration / (1000 * 60)) % 60), // hours = parseInt((duration / (1000 * 60 * 60)) % 24); // hours = (hours < 10) ? "0" + hours : hours; // minutes = (minutes < 10) ? "0" + minutes : minutes; // seconds = (seconds < 10) ? "0" + seconds : seconds; // return hours + ":" + minutes + ":" + seconds + "." + milliseconds; // } // dhm(t) { // let cd = 24 * 60 * 60 * 1000, // ch = 60 * 60 * 1000, // d = Math.floor(t / cd), // h = Math.floor( (t - d * cd) / ch), // m = Math.round( (t - d * cd - h * ch) / 60000), // pad = function(n){ return n < 10 ? '0' + n : n; }; // if ( m === 60 ) { // h++; // m = 0; // } // if ( h === 24 ) { // d++; // h = 0; // } // return [d, pad(h), pad(m)].join(':'); // } // setImageProfile(agent) { // //console.log(agent); // this.contactService.setImageProfile(agent) // .then(function (snapshot) { // if (snapshot.val().trim()) { // agent.image = snapshot.val(); // } // }) // .catch(function (err) { // console.log(err); // }); // } // ========= begin:: ACTIONS ============// openNewConversation() { this.onNewConversation.emit(); } returnOpenAllConversation() { this.onOpenAllConvesations.emit(); } onImageLoadedFN(conversation: ConversationModel){ this.onImageLoaded.emit(conversation) } onConversationLoadedFN(conversation: ConversationModel){ this.onConversationLoaded.emit(conversation) } /** */ // getUrlImgProfile(uid?: string): string { // const baseLocation = this.g.baseLocation; // if (!uid || uid === 'system' ) { // return baseLocation + IMG_PROFILE_BOT; // } else if (uid === 'error') { // return baseLocation + IMG_PROFILE_DEFAULT; // } else { // return baseLocation + IMG_PROFILE_DEFAULT; // } // } private openConversationByID(conversation) { this.logger.debug('[HOMECONVERSATIONS] openConversationByID: ', conversation); if ( conversation ) { // this.conversationsService.updateIsNew(conversation); // this.conversationsService.updateConversationBadge(); this.onConversationSelected.emit(conversation); } } // ========= end:: ACTIONS ============// // ========= begin:: DESTROY ALL SUBSCRIPTIONS ============// /** elimino tutte le sottoscrizioni */ ngOnDestroy() { this.logger.debug('[HOMECONVERSATIONS] ngOnDestroy list conv subscriptions', this.subscriptions); this.unsubscribe(); } /** */ unsubscribe() { this.subscriptions.forEach(function (subscription) { subscription.unsubscribe(); }); this.subscriptions = []; // this.subOpenConversations = null; this.subListConversations = null; this.subArchivedConversations = null; this.logger.debug('[HOMECONVERSATIONS] this.subscriptions', this.subscriptions); } // ========= end:: DESTROY ALL SUBSCRIPTIONS ============// }
the_stack
namespace com.keyman.dom { /** * As our touch-alias elements have historically been based on <div>s, this * defines the root element of touch-aliases as a merger type with HTMLDivElements. * */ export type TouchAliasElement = HTMLDivElement & TouchAliasData; // Many thanks to https://www.typescriptlang.org/docs/handbook/advanced-types.html for this. function link(elem: HTMLDivElement, data: TouchAliasData): TouchAliasElement { let e = <TouchAliasElement> elem; // Merges all properties and methods of KeyData onto the underlying HTMLDivElement, creating a merged class. for(let id in data) { if(!e.hasOwnProperty(id)) { (<any>e)[id] = (<any>data)[id]; } } return e; } // If the specified HTMLElement is either a TouchAliasElement or one of its children elements, // this method will return the root TouchAliasElement. export function findTouchAliasTarget(target: HTMLElement): TouchAliasElement { // The scrollable container element for the before & after text spans & the caret. // Not to be confused with the simulated scrollbar. let scroller: HTMLElement; // Identify the scroller element if(target && dom.Utils.instanceof(target, "HTMLSpanElement")) { scroller=target.parentNode as HTMLElement; } else if(target && (target.className != null && target.className.indexOf('keymanweb-input') >= 0)) { scroller=target.firstChild as HTMLElement; } else if(target && dom.Utils.instanceof(target, "HTMLDivElement")) { // Three possibilities: the scroller, the scrollbar, & the blinking DIV of the caret. // A direct click CAN trigger events on the blinking element itself if well-timed. scroller=target; // Ensures we land on the scroller, not the caret. if(scroller.parentElement && scroller.parentElement.className.indexOf('keymanweb-input') < 0) { scroller = scroller.parentElement; } // scroller is now either the actual scroller or the scrollbar element. // We don't return either of these, and they both have the same parent element. } else if(target['kmw_ip']) { // In case it's called on a TouchAliasElement's base (aliased) element. return target['kmw_ip'] as TouchAliasElement; } else { // If it's not in any way related to a TouchAliasElement, simply return null. return null; } // And the actual target element let root = scroller.parentNode; if(root['base'] !== undefined) { return root as TouchAliasElement; } else { return null; } } export function constructTouchAlias(base?: HTMLElement): TouchAliasElement { let div = document.createElement("div"); let ele = link(div, new TouchAliasData()); if(base) { ele.initWithBase(base); } else { ele.init(); } return ele; } /** * The core definition for touch-alias 'subclassing' of HTMLDivElement. * It's 'merged' with HTMLDivElement to avoid issues with DOM inheritance and DOM element creation. */ class TouchAliasData { ['base']: HTMLElement = null; // NOT undefined; we can use this distinction for 'type-checking'. __preCaret: HTMLSpanElement; __postCaret: HTMLSpanElement; __scrollDiv: HTMLDivElement; __scrollBar: HTMLDivElement; __caretSpan: HTMLSpanElement; __caretDiv: HTMLDivElement; __caretTimerId: number; __activeCaret: boolean = false; __resizeHandler: () => void; private static device: Device; private static getDevice(): Device { if(!TouchAliasData.device) { let device = new com.keyman.Device(); device.detect(); TouchAliasData.device = device; } return TouchAliasData.device; } private static getOS(): string { return this.getDevice().OS; } isMultiline(): boolean { return this['base'] && this['base'].nodeName == "TEXTAREA"; } initCaret(): void { /** * Create a caret to be appended to the scroller of the focussed input field. * The caret is appended to the scroller so that it will automatically be clipped * when the user manually scrolls it outside the element boundaries. * It is positioned exactly over the hidden span (__caretSpan) that is inserted * between the text spans before and after the insertion point. */ this.__caretDiv = <HTMLDivElement> document.createElement('DIV'); var cs=this.__caretDiv.style; cs.position='absolute'; cs.height='16px'; // default height, actual height set from element properties cs.width='2px'; cs.backgroundColor='blue'; cs.border='none'; cs.left=cs.top='0px'; // actual position set relative to parent when displayed cs.display='block'; cs.visibility='hidden'; cs.zIndex='9998'; // immediately below the OSK // Start the caret flash timer this.__caretTimerId = window.setInterval(this.flashCaret.bind(this), 500); } init() { // Remember, this type exists to be merged into HTMLDivElements, so this will work. // We have to trick TS a bit to make it happy, though. let divThis = <TouchAliasElement> (<any> this); divThis.className='keymanweb-input'; // Add a scrollable interior div let d = this.__scrollDiv = document.createElement<'div'>('div'); let xs = divThis.style; xs.overflow='hidden'; xs.position='absolute'; //xs.border='1px solid gray'; xs.border='hidden'; // hide when element empty - KMW-3 xs.border='none'; xs.borderRadius='5px'; // Add a scroll bar (horizontal for INPUT elements, vertical for TEXTAREA elements) var sb = this.__scrollBar = document.createElement<'div'>('div'), sbs=sb.style; sbs.position='absolute'; sbs.height=sbs.width='4px'; sbs.left=sbs.top='0'; sbs.display='block'; sbs.visibility='hidden'; sbs.backgroundColor='#808080'; sbs.borderRadius='2px'; // And add two spans for the text content before and after the caret, and a caret span this.__preCaret=document.createElement<'span'>('span'); this.__postCaret=document.createElement<'span'>('span'); this.__caretSpan=document.createElement<'span'>('span'); this.__preCaret.innerHTML = this.__postCaret.innerHTML = this.__caretSpan.innerHTML=''; this.__preCaret.className = this.__postCaret.className = this.__caretSpan.className='keymanweb-font'; d.appendChild(this.__preCaret); d.appendChild(this.__caretSpan); d.appendChild(this.__postCaret); divThis.appendChild(d); divThis.appendChild(sb); let ds=d.style; ds.position='absolute'; let preCaretStyle = this.__preCaret.style; let postCaretStyle = this.__postCaret.style; let styleCaret = this.__caretSpan.style; preCaretStyle.border=postCaretStyle.border='none'; //preCaretStyle.backgroundColor='rgb(220,220,255)'; //postCaretStyle.backgroundColor='rgb(220,255,220)'; //only for testing preCaretStyle.height=postCaretStyle.height='100%'; // The invisible caret-positioning span must have a border to ensure that // it remains in the layout, but colour doesn't matter, as it is never visible. // Span margins are adjusted to compensate for the border and maintain text positioning. styleCaret.border='1px solid red'; styleCaret.visibility='hidden'; styleCaret.marginLeft=styleCaret.marginRight='-1px'; // Set the outer element padding *after* appending the element, // otherwise Firefox misaligns the two elements xs.padding='8px'; // Set internal padding to match the TEXTAREA and INPUT elements ds.padding='0px 2px'; // OK for iPad, possibly device-dependent // Set the tabindex to 0 to allow a DIV to accept focus and keyboard input // c.f. http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-TECHS/SCR29.html divThis.tabIndex=0; // Disable (internal) pan and zoom on KMW input elements for IE10 divThis.style.msTouchAction='none'; ds.minWidth=xs.width; ds.height=xs.height; this.initCaret(); } initWithBase(base: HTMLElement) { this['base'] = base; this.init(); let divThis = <TouchAliasElement> (<any> this); // There's quite a bit of setup for touch-alias elements that only occurs if it has an associated base. this['base']['kmw_ip'] = divThis; base.disabled = true; let baseStyle = window.getComputedStyle(base, null); let scrollDivStyle = this.__scrollDiv.style; let preCaretStyle = this.__preCaret.style; let postCaretStyle = this.__postCaret.style; divThis.dir = base.dir; preCaretStyle.fontFamily = postCaretStyle.fontFamily = scrollDivStyle.fontFamily = baseStyle.fontFamily; // Set vertical centering for input elements if(base.nodeName.toLowerCase() == 'input') { if(!isNaN(parseInt(baseStyle.height,10))) { preCaretStyle.lineHeight = postCaretStyle.lineHeight = baseStyle.height; } } if(TouchAliasData.getOS() == 'Android' && baseStyle.backgroundColor == 'transparent') { scrollDivStyle.backgroundColor = '#fff'; } else { scrollDivStyle.backgroundColor = baseStyle.backgroundColor; } if(divThis.base.nodeName.toLowerCase() == 'textarea') { preCaretStyle.whiteSpace=postCaretStyle.whiteSpace='pre-wrap'; //scroll vertically } else { preCaretStyle.whiteSpace=postCaretStyle.whiteSpace='pre'; //scroll horizontally } divThis.base.parentNode.appendChild(divThis); divThis.updateInput(); let style = divThis.style; style.color=baseStyle.color; //style.backgroundColor=bs.backgroundColor; style.fontFamily=baseStyle.fontFamily; style.fontSize=baseStyle.fontSize; style.fontWeight=baseStyle.fontWeight; style.textDecoration=baseStyle.textDecoration; style.padding=baseStyle.padding; style.margin=baseStyle.margin; style.border=baseStyle.border; style.borderRadius=baseStyle.borderRadius; //xs.color='red'; //use only for checking alignment // Prevent highlighting of underlying element (Android) if('webkitTapHighlightColor' in style) { style.webkitTapHighlightColor='rgba(0,0,0,0)'; } if(base instanceof base.ownerDocument.defaultView.HTMLTextAreaElement) { // Correct rows value if defaulted and box height set by CSS // The rows value is used when setting the caret vertically if(base.rows == 2) { // 2 is default value var h=parseInt(baseStyle.height,10)-parseInt(baseStyle.paddingTop,10)-parseInt(baseStyle.paddingBottom,10), dh=parseInt(baseStyle.fontSize,10), calcRows=Math.round(h/dh); if(calcRows > base.rows+1) { base.rows=calcRows; } } scrollDivStyle.width=style.width; scrollDivStyle.minHeight=style.height; } else { scrollDivStyle.minWidth=style.width; scrollDivStyle.height=style.height; } base.style.visibility='hidden'; // hide by default: KMW-3 // Add an explicit event listener to allow the duplicated input element // to be adjusted for any changes in base element location or size // This will be called for each element after any rotation, as well as after user-initiated changes // It has to be wrapped in an anonymous function to preserve scope and be applied to each element. (function(xx: TouchAliasElement){ xx.__resizeHandler = function(){ /* A timeout is needed to let the base element complete its resizing before our * simulated element can properly resize itself. * * Not doing this causes errors if the input elements are resized for whatever reason, such as * changing languages to a text with greater height. */ window.setTimeout(function (){ xx.updateInput(); }, 1); }; xx.base.addEventListener('resize', xx.__resizeHandler, false); xx.base.addEventListener('orientationchange', xx.__resizeHandler, false); })(divThis); var textValue: string; if(base instanceof base.ownerDocument.defaultView.HTMLTextAreaElement || base instanceof base.ownerDocument.defaultView.HTMLInputElement) { textValue = base.value; } else { textValue = base.textContent; } // And copy the text content this.setText(textValue, null); } setText(t?: string, cp?: number): void { var tLen=0; var t1: string, t2: string; // Read current text if null passed (for caret positioning) if(t === null) { t1 = this.__preCaret.textContent; t2 = this.__postCaret.textContent; t = t1 + t2; } if(cp < 0) { cp = 0; //if(typeof t._kmwLength == 'undefined') return; } tLen=t._kmwLength(); if(cp === null || cp === undefined || cp > tLen) { cp=tLen; } t1=t._kmwSubstr(0,cp); t2=t._kmwSubstr(cp); this.__preCaret.textContent=t1; this.__postCaret.textContent=t2; this.updateBaseElement(); // KMW-3, KMW-29 } getTextBeforeCaret() { return this.__preCaret.textContent; } getTextAfterCaret() { return this.__postCaret.textContent; } setTextBeforeCaret(t: string): void { var tLen=0; // Collapse (trailing) whitespace to a single space for INPUT fields (also prevents wrapping) if(!this.isMultiline()) { t=t.replace(/\s+$/,' '); } this.__preCaret.textContent=t; // Test total length in order to control base element visibility tLen=t.length; tLen=tLen+this.__postCaret.textContent.length; // Update the base element then scroll into view if necessary this.updateBaseElement(); //KMW-3, KMW-29 this.scrollInput(); } getTextCaret(): number { return this.getTextBeforeCaret()._kmwLength(); } setTextCaret(cp: number): void { this.setText(null,cp); this.showCaret(); } /** * Set content, visibility, background and borders of input and base elements (KMW-3,KMW-29) */ updateBaseElement() { let e = <TouchAliasElement> (<any> this); // Only proceed if we actually have a base element. if(!e['base']) { return; } var Ldv = e.base.ownerDocument.defaultView; if(e.base instanceof Ldv.HTMLInputElement || e.base instanceof Ldv.HTMLTextAreaElement) { e.base.value = this.getText(); //KMW-29 } else { e.base.textContent = this.getText(); } let n = this.getText()._kmwLength(); e.style.backgroundColor = (n==0 ? 'transparent' : window.getComputedStyle(e.base, null).backgroundColor); if(TouchAliasData.getOS() == 'iOS') { e.base.style.visibility=(n==0?'visible':'hidden'); } } flashCaret(): void { // Significant change - each element manages its own caret, and its activation is managed through show/hideCaret() // without referencing core KMW code. (KMW must thus check if the active element is a TouchAliasElement, then use these // methods as appropriate.) if(this.__activeCaret) { var cs=this.__caretDiv.style; cs.visibility = cs.visibility != 'visible' ? 'visible' : 'hidden'; } }; /** * Position the caret at the start of the second span within the scroller */ showCaret() { var scroller=this.__scrollDiv, cs=this.__caretDiv.style, sp2=this.__caretSpan; // Attach the caret to this scroller and position it over the caret span if(this.__caretDiv.parentNode != <Node>scroller) { scroller.appendChild(this.__caretDiv); } cs.left=sp2.offsetLeft+'px'; cs.top=sp2.offsetTop+'px'; cs.height=(sp2.offsetHeight-1)+'px'; cs.visibility='hidden'; // best to wait for timer to display caret this.__activeCaret = true; // Scroll into view if required this.scrollBody(); // Display and position the scrollbar if necessary this.setScrollBar(); } hideCaret() { var e= <TouchAliasElement> (<any> this); // Always copy text back to underlying field on blur if(e.base instanceof e.base.ownerDocument.defaultView.HTMLTextAreaElement || e.base instanceof e.base.ownerDocument.defaultView.HTMLInputElement) { e.base.value = this.getText(); } // And set the scroller caret to the end of the element content (null preserves text) this.setText(null, 100000); // Set the element scroll to zero (or max for RTL INPUT) var ss=this.__scrollDiv.style; if(e.isMultiline()) { ss.top='0'; } else { if(e.base.dir == 'rtl') { ss.left=(e.offsetWidth - this.__scrollDiv.offsetWidth-8)+'px'; } else { ss.left='0'; } } // And hide the caret and scrollbar if(this.__caretDiv.parentNode) { this.__caretDiv.parentNode.removeChild(this.__caretDiv); } this.__caretDiv.style.visibility='hidden'; this.__scrollBar.style.visibility='hidden'; this.__activeCaret = false; } getText(): string { return (<TouchAliasElement> (<any> this)).textContent; } updateInput() { if(this['base']) { let divThis = (<TouchAliasElement> (<any> this)); var xs=divThis.style, b=divThis.base, s=window.getComputedStyle(b,null), mLeft=parseInt(s.marginLeft,10), mTop=parseInt(s.marginTop,10), x1=Utils.getAbsoluteX(b), y1=Utils.getAbsoluteY(b); var p=divThis.offsetParent as HTMLElement; if(p) { x1=x1-Utils.getAbsoluteX(p); y1=y1-Utils.getAbsoluteY(p); } if(isNaN(mLeft)) { mLeft=0; } if(isNaN(mTop)) { mTop=0; } xs.left=(x1-mLeft)+'px'; xs.top=(y1-mTop)+'px'; // FireFox does not want the offset! if(typeof(s.MozBoxSizing) != 'undefined') { xs.left=x1+'px'; xs.top=y1+'px'; } var w=b.offsetWidth, h=b.offsetHeight, pLeft=parseInt(s.paddingLeft,10), pRight=parseInt(s.paddingRight,10), pTop=parseInt(s.paddingTop,10), pBottom=parseInt(s.paddingBottom,10), bLeft=parseInt(s.borderLeft,10), bRight=parseInt(s.borderRight,10), bTop=parseInt(s.borderTop,10), bBottom=parseInt(s.borderBottom,10); // If using content-box model, must subtract the padding and border, // but *not* for border-box (as for WordPress PlugIn) var boxSizing='undefined'; if(typeof(s.boxSizing) != 'undefined') { boxSizing=s.boxSizing; } else if(typeof(s.MozBoxSizing) != 'undefined') { boxSizing=s.MozBoxSizing; } if(boxSizing == 'content-box') { if(!isNaN(pLeft)) w -= pLeft; if(!isNaN(pRight)) w -= pRight; if(!isNaN(bLeft)) w -= bLeft; if(!isNaN(bRight)) w -= bRight; if(!isNaN(pTop)) h -= pTop; if(!isNaN(pBottom)) h -= pBottom; if(!isNaN(bTop)) h -= bTop; if(!isNaN(bBottom)) h -= bBottom; } if(TouchAliasData.getOS() == 'Android') { // FireFox - adjust padding to match input and text area defaults if(typeof(s.MozBoxSizing) != 'undefined') { xs.paddingTop=(pTop+1)+'px'; xs.paddingLeft=pLeft+'px'; if(this.isMultiline()) { xs.marginTop='1px'; } else { xs.marginLeft='1px'; } w--; h--; } else { // Chrome, Opera, native browser (?) w++; h++; } } xs.width=w+'px'; xs.height=h+'px'; } } /** * Scroll the input field horizontally (INPUT base element) or * vertically (TEXTAREA base element) to bring the caret into view * as text is entered or deleted form an element */ scrollInput() { var scroller=this.__scrollDiv; let divThis = <TouchAliasElement> (<any> this); // Get the actual absolute position of the caret and the element var s2=this.__caretSpan, cx=dom.Utils.getAbsoluteX(s2),cy=dom.Utils.getAbsoluteY(s2), ex=dom.Utils.getAbsoluteX(divThis),ey=dom.Utils.getAbsoluteY(divThis), x=parseInt(scroller.style.left,10), y=parseInt(scroller.style.top,10), dx=0,dy=0; // Scroller offsets must default to zero if(isNaN(x)) x=0; if(isNaN(y)) y=0; // Scroll input field vertically if necessary if(divThis.isMultiline()) { var rowHeight=Math.round(divThis.offsetHeight/(<HTMLTextAreaElement> divThis.base).rows); if(cy < ey) { dy=cy-ey; } if(cy > ey+divThis.offsetHeight-rowHeight) { dy=cy-ey-divThis.offsetHeight+rowHeight; } if(dy != 0){ scroller.style.top=(y<dy?y-dy:0)+'px'; } } else { // or scroll horizontally if needed if(cx < ex+8) { dx=cx-ex-12; } if(cx > ex+divThis.offsetWidth-12) { dx=cx-ex-divThis.offsetWidth+12; } if(dx != 0) { scroller.style.left=(x<dx?x-dx:0)+'px'; } } // Display the caret (and scroll into view if necessary) this.showCaret(); } /** * Scroll the document body vertically to bring the active input into view */ scrollBody(): void { // Note the deliberate lack of typing; we don't want to include KMW's core in isolated // element interface testing, so we can't use it here. var oskHeight: number = 0; if(window['keyman']) { var osk = window['keyman'].osk; if(osk && osk._Box) { oskHeight = osk._Box.offsetHeight; } } // Get the absolute position of the caret var s2=this.__caretSpan, y=dom.Utils.getAbsoluteY(s2), t=window.pageYOffset,dy=0; if(y < t) { dy=y-t; } else { dy=y-t-(window.innerHeight - oskHeight - s2.offsetHeight - 2); if(dy < 0) { dy=0; } } // Hide OSK, then scroll, then re-anchor OSK with absolute position (on end of scroll event) if(dy != 0) { window.scrollTo(0,dy+window.pageYOffset); } } /** * Display and position a scrollbar in the input field if needed */ setScrollBar() { let e = <TouchAliasElement> (<any> this); // Display the scrollbar if necessary. Added isMultiline condition to correct rotation issue KMW-5. Fixed for 310 beta. var scroller=this.__scrollDiv, sbs=this.__scrollBar.style; if((scroller.offsetWidth > e.offsetWidth || scroller.offsetLeft < 0) && !e.isMultiline()) { sbs.height='4px'; sbs.width=100*(e.offsetWidth/scroller.offsetWidth)+'%'; sbs.left=100*(-scroller.offsetLeft/scroller.offsetWidth)+'%'; sbs.top='0'; sbs.visibility='visible'; } else if(scroller.offsetHeight > e.offsetHeight || scroller.offsetTop < 0) { sbs.width='4px'; sbs.height=100*(e.offsetHeight/scroller.offsetHeight)+'%'; sbs.top=100*(-scroller.offsetTop/scroller.offsetHeight)+'%'; sbs.left='0'; sbs.visibility='visible'; } else { sbs.visibility='hidden'; } } } }
the_stack
import CONST from './constant' import CURSOR_CONFIG from './cursorConfig' import { KeyPoint, PenCircle, PenLine } from './classes' import { IPenOptions, IPoint, IController } from './interface' import { convertStr2Num, chunk, getAbsoluteCordinate } from './utils' /** * declare Pen Tool Class */ class Pen { /** * Whether the penTool's edit mode is opened. Default false. */ penModeOn: boolean = false; /** * Store final path keyPoints data. */ keyPointData: KeyPoint[] = []; /** * Store the real path keyPoints data, cause it's different from keyPointData when mousemove. */ keyPointDataCache: KeyPoint[] = []; /** * Whether the path is closed */ closeState: boolean = false; /** * Whether the real-path is closed. * Fill the path containing area when cursor position and path start-point coincide during mousemoving (but not mouseup). */ cacheCloseState: boolean = false; /** * The svg Path string */ realPathStr: string; /** * Fabric.Path object */ pathRealObject: object; /** * State of keyPoint. * 'new' when mousedown which means new keyPoint, reset null when mouseup */ keyPointState: string; /** * Index of current operation point in the keyPointData */ currentKeyPointIndex: number; /** * Save the lastest mousedown positon */ penMouseMoveFix: any; /** * Save part of the keyPoint information which is activated by mousedown */ penMouseDownOrigin: any; /** * Whether the mousedown event is triggered */ penMouseDown: boolean = false; /** * <canvas> element */ canvas: HTMLCanvasElement; /** * canvas context('2d') */ canvasCtx: CanvasRenderingContext2D; /** * Custom setting options */ options: IPenOptions = { circle: new PenCircle(), line: new PenLine(), pathColor: '#000', pathFillColor: '#ebebeb', isFillPath: false } /** * Collection of objects drawn on canvas */ objects: any[] = []; /** * Whether edit the keyPoint position */ isEdit: boolean = false; /** * Save auxPoint or keyPoint when mousedown on the point */ mousedownTarget?: any; constructor(canvasId: string, options?: any, keyPointData?: KeyPoint[]) { try { if (!canvasId) { console.error("PenTool must based a canvas, please confirm that the canvasId is passed.") } else { this.canvas = <HTMLCanvasElement>document.getElementById(canvasId); this.canvasCtx = this.canvas.getContext('2d'); this.options = {...{ circle: new PenCircle(), line: new PenLine(), pathColor: '#000', // default pathColor pathFillColor: '#ebebeb' // default pathFillColor }, ...options}; this.closeState = options ? options.closeState: false this.keyPointData = keyPointData || []; if (this.keyPointData.length > 0) { this.realPathStr = this._generatePathStr(this.keyPointData) this.drawPath({closeState: options.closeState}) } // fire mouse event this._mouseDown(); this._mouseMove(); this._mouseUp(); this._keydown(); this._mouseDblclick(); } } catch (error) { console.error(error.message); } } /** * Open drawing mode */ enablePen(): void { this.penModeOn = true; this.setCursor(CONST.CURSOR_TYPE.NORMAL); } /** * Exit drawing mode * The first call sets currentKeyPointIndex to null and set keyPoint editable * The second call removes auxPoints and auxLines */ exitPenMode() { if (this.currentKeyPointIndex != null) { this.currentKeyPointIndex = null; this.isEdit = true; // set editable this.setCursor(CONST.CURSOR_TYPE.NORMAL); this.refreshEditPath(); } else { this.penModeOn = false; if (this.pathRealObject) { // remove auxPoint and auxLine let auxPointAndLines = this.objects.filter((object: any) => { return object.penType === CONST.OBJECT_TYPE.PEN_AUX; }) this.removeObjects(...auxPointAndLines); } this.setCursor(CONST.CURSOR_TYPE.DEFAULT); // reset params this.currentKeyPointIndex = null; this.isEdit = false; } this.refreshRender(); } /** * Set cursor style * @param type cursor type */ setCursor(type: string): void { if (type === CONST.CURSOR_TYPE.DEFAULT) { this.canvas.style.cursor = 'default'; } else { this.canvas.style.cursor = `url(${CURSOR_CONFIG[type]}), default`; } } /** * fire mousedown event */ _mouseDown(): void { this.canvas.addEventListener("mousedown", event => { if (this.penModeOn) { this._penMouseDown(event); } }) } /** * fire mouseMove event */ _mouseMove(): void { this.canvas.addEventListener("mousemove", event => { if (this.penModeOn) { if (this.penMouseDown) { this.setCursor(CONST.CURSOR_TYPE.MOVE); } this._penMouseMove(event); } }) } /** * fire mouseup event */ _mouseUp(): void { this.canvas.addEventListener("mouseup", event => { if (this.penModeOn) { this.setCursor(CONST.CURSOR_TYPE.NORMAL); this._penMouseUp(event); } }) } /** * fire path double click event */ _mouseDblclick(): void { this.canvas.addEventListener("dblclick", event => { if (this.penModeOn) { let target = this._getMouseOverTarget(event); if (target && target.penType === CONST.OBJECT_TYPE.PEN_AUX && target.handleName == null) { this.changeKeyPointType(target); this.refreshRender(); } } else { let point: IPoint = { x: event.offsetX, y: event.offsetY }, path: Path2D = new Path2D(this.realPathStr), isInPath: boolean = this.canvasCtx.isPointInPath(path, point.x, point.y); if (isInPath) { this.setCursor(CONST.CURSOR_TYPE.NORMAL); this.generateEditablePath(); } } }) } /** * fire keydown event * Support to press ESC to exit drawing mode */ _keydown(): void { // Set the tabIndex value of canvas so that canvas can get focus. Only in this way can canvas respond to keyboard events this.canvas.setAttribute("tabIndex", "0"); this.canvas.style.userSelect = "none"; this.canvas.addEventListener("keydown", event => { if (this.penModeOn) { if (event.keyCode === 27) { this.exitPenMode(); } } }) } /** * Implementation of MouseDown * @param event */ _penMouseDown(event: MouseEvent): void { let target = this._getMouseOverTarget(event), x = event.offsetX, y = event.offsetY, index: number; this.penMouseDown = true; this.mousedownTarget = target; this.keyPointDataCache = null; this.penMouseMoveFix = { x, y }; // update aux point fill color this._matchObjectsByProrerty("penType", CONST.OBJECT_TYPE.PEN_AUX, (object: any) => { object.fill = "#fff"; }) // checks if the target is aux point if (target !== null && target.penType === CONST.OBJECT_TYPE.PEN_AUX) { index = target.keyPointIndex; // fill the aux point target.fill = target.stroke; /** * When the first and the last keyPoint coincide, the path is closed. * Path is closed, set keyPoints editable. */ if (this.keyPointData.length > 1 && this.currentKeyPointIndex === this.keyPointData.length - 1 && index === 0) { this.closeState = true; } if (this.closeState || index !== this.keyPointData.length - 1) { this.isEdit = true; } this.currentKeyPointIndex = index; this.setMousedownOrigin(); this.refreshEditPath(); return; } /** * Normally, add keyPoint */ if (this.keyPointData.length === 0 || this.currentKeyPointIndex === this.keyPointData.length - 1 && !this.closeState) { let keyPoint: KeyPoint; // first keyPoint, set type 'M' if (this.keyPointData.length === 0) { keyPoint = new KeyPoint({ type: 'M', point: { x, y }, pointType: CONST.POINT_TYPE.STRAIGHT, relationPoints: [x, y], keyPointIndex: this.keyPointData.length }) } else { let preKeyPoint = this.keyPointData[this.keyPointData.length - 1], preLeft = preKeyPoint.point.x, preTop = preKeyPoint.point.y; if (preKeyPoint.pointType !== CONST.POINT_TYPE.STRAIGHT) { preLeft = preKeyPoint.controller2.x; preTop = preKeyPoint.controller2.y; } keyPoint = new KeyPoint({ type: 'C', point: { x, y }, pointType: CONST.POINT_TYPE.STRAIGHT, relationPoints: [preLeft, preTop, x, y, x, y], keyPointIndex: this.keyPointData.length }) } let circle = new PenCircle({ x: x, y: y, keyPointIndex: keyPoint.keyPointIndex, fill: this.options.circle.fill, stroke: this.options.circle.stroke }) this.addCanvasObjects(circle); this.keyPointData.push(keyPoint); this.currentKeyPointIndex = this.keyPointData.length - 1; this.refreshEditPath(); // add new keyPoint, set state this.keyPointState = CONST.PATH_STATE.NEW; } // clickoutside or 'ESC' keypress to exit penmode when editmode else if (this.currentKeyPointIndex == null) { this.exitPenMode(); } // first time: clickoutside or 'ESC' keypress set edit mode and reset currentKeyPointIndex else if (this.keyPointData.length > 0 && (this.closeState || this.currentKeyPointIndex !== this.keyPointData.length - 1)) { this.currentKeyPointIndex = null; this.isEdit = true; } this.refreshRender(); } /** * Implementation of MouseMove * @param event */ _penMouseMove(event: MouseEvent): void { let x = event.offsetX, y = event.offsetY, target = this._getMouseOverTarget(event); if (!this.isEdit) { // keep mousedown and mousemoving will draw a curve on canvas when current keyPoint is new if (this.keyPointState === CONST.PATH_STATE.NEW) { if (Math.abs(this.penMouseMoveFix.x - x) > 2 || Math.abs(this.penMouseMoveFix.y - y) > 2) { this.changeKeyPointPos(x, y, CONST.CONTROL_TYPE.RIGHT); } } else { /** * when target is keyPoint * 1. target is not start or * 2. the path is closed or * 3. target is start but currentkeyPointIndex is not the last keyPoint's index(otherwise the path is closed). */ if (target != null && target.penType === CONST.OBJECT_TYPE.PEN_AUX && (target.keyPointIndex !== 0 || this.closeState || (target.keyPointIndex === 0 && this.currentKeyPointIndex !== this.keyPointData.length - 1))) { if (!this.penMouseDown) { this.setCursor(CONST.CURSOR_TYPE.MOVE); } } else { this.setCursor(CONST.CURSOR_TYPE.NORMAL); if (this.currentKeyPointIndex === this.keyPointData.length - 1 && !this.closeState) { let keyPoint: KeyPoint, prev = this.keyPointData[this.currentKeyPointIndex], prevLeft: number, prevTop: number; if (this.keyPointDataCache == null) { this.keyPointDataCache = JSON.parse(JSON.stringify(this.keyPointData)); this.keyPointDataCache.push(new KeyPoint()); } else { this.cacheCloseState = false; } if (this.keyPointData[this.currentKeyPointIndex].type === "M") { prevLeft = prev.relationPoints[0]; prevTop = prev.relationPoints[1]; } else { prevLeft = prev.relationPoints[4]; prevTop = prev.relationPoints[5]; } if (prev.pointType !== CONST.POINT_TYPE.STRAIGHT) { prevLeft = prev.controller2.x; prevTop = prev.controller2.y; } keyPoint = new KeyPoint({ type: "C", point: { x, y }, pointType: CONST.POINT_TYPE.STRAIGHT, relationPoints: [prevLeft, prevTop, x, y, x, y], keyPointIndex: this.keyPointDataCache.length - 1 }) this.keyPointDataCache[this.keyPointDataCache.length - 1] = keyPoint; // path closed if (this.keyPointData.length > 1 && target !== null && target.penType === CONST.OBJECT_TYPE.PEN_AUX && target.keyPointIndex === 0) { this.cacheCloseState = true; this.setCursor(CONST.CURSOR_TYPE.CLOSE); } else { this.setCursor(CONST.CURSOR_TYPE.ADD); } this.refreshEditPath(true); } } } } /** * keyPoint moving * alt + handler keypoint moving: change path curve */ else if (this.mousedownTarget != null && this.mousedownTarget.penType === CONST.OBJECT_TYPE.PEN_AUX && this.penMouseDown) { let target = this.mousedownTarget; target.x = x; target.y = y; if (target.handleName === CONST.CONTROL_TYPE.LEFT) { if (event.altKey) { this.changeKeyPointType(target, CONST.POINT_TYPE.DISJOINTED); } else { this.changeKeyPointType(target); } this.changeKeyPointPos(x, y, CONST.CONTROL_TYPE.LEFT); } else if (target.handleName === CONST.CONTROL_TYPE.RIGHT) { if (event.altKey) { this.changeKeyPointType(target, CONST.POINT_TYPE.DISJOINTED); } else { this.changeKeyPointType(target); } this.changeKeyPointPos(x, y, CONST.CONTROL_TYPE.RIGHT); } else { this.changeKeyPointPos(x, y, CONST.CONTROL_TYPE.MAIN); } } this.refreshRender(); } /** * Implementation of MouseUp * @param event */ _penMouseUp(event: MouseEvent): void { this.penMouseDown = false; if (this.currentKeyPointIndex === this.keyPointData.length - 1 && !this.closeState && this.penMouseMoveFix && event.offsetX === this.penMouseMoveFix.x && event.offsetY === this.penMouseMoveFix.y) { this.isEdit = false; } // set main keyPoint fill this._matchObjectsByProrerty("penType", CONST.OBJECT_TYPE.PEN_AUX, (object: any) => { if (object.keyPointIndex === this.currentKeyPointIndex && object.handleName == null) { object.fill = object.stroke; } }) /** reset params */ this.keyPointState = null; this.penMouseMoveFix = null; this.penMouseDownOrigin = null; this.refreshRender(); } /** * update keyPoint or handle point position * @param x mouseOffsetX relative to canvas * @param y mouseOffsetY relative to canvas * @param type control point type */ changeKeyPointPos(x: number, y: number, type: string = CONST.CONTROL_TYPE.MAIN): void { let index = this.currentKeyPointIndex, curKeyPoint: KeyPoint = this.keyPointData[index], originPoint = curKeyPoint.point; if ((type === CONST.CONTROL_TYPE.LEFT || type === CONST.CONTROL_TYPE.RIGHT) && curKeyPoint.pointType == CONST.POINT_TYPE.STRAIGHT) { this.createPathCurveAux(curKeyPoint); } // keyPoint if (type === CONST.CONTROL_TYPE.MAIN) { let x1: number, x2: number, y1: number, y2: number, minulsX: number, minulsY: number; if (this.penMouseDownOrigin) { if (this.penMouseDownOrigin.x) { minulsX = this.penMouseDownOrigin.x - x; minulsY = this.penMouseDownOrigin.y - y; } if (this.penMouseDownOrigin.x1) { x1 = this.penMouseDownOrigin.x1 - minulsX; y1 = this.penMouseDownOrigin.y1 - minulsY; } if (this.penMouseDownOrigin.x2) { x2 = this.penMouseDownOrigin.x2 - minulsX; y2 = this.penMouseDownOrigin.y2 - minulsY; } this.updatePenPathControll(curKeyPoint, { x, y, x1, y1, x2, y2 }); } originPoint.x = x; originPoint.y = y; if (curKeyPoint.type === "M") { curKeyPoint.relationPoints[0] = x; curKeyPoint.relationPoints[1] = y; if (index + 1 <= this.keyPointData.length - 1) { let nextItem = this.keyPointData[index + 1]; if (curKeyPoint.pointType != CONST.POINT_TYPE.STRAIGHT) { nextItem.relationPoints[0] = x2; nextItem.relationPoints[1] = y2; } else { nextItem.relationPoints[0] = x; nextItem.relationPoints[1] = y; } } if (curKeyPoint.pointType != CONST.POINT_TYPE.STRAIGHT) { curKeyPoint.relationPoints[2] = x1; curKeyPoint.relationPoints[3] = y1; } curKeyPoint.point = { x, y }; } else { if (curKeyPoint.pointType != CONST.POINT_TYPE.STRAIGHT) { curKeyPoint.relationPoints[2] = x1; curKeyPoint.relationPoints[3] = y1; } else { curKeyPoint.relationPoints[2] = x; curKeyPoint.relationPoints[3] = y; } curKeyPoint.relationPoints[4] = x; curKeyPoint.relationPoints[5] = y; if (index + 1 <= this.keyPointData.length - 1) { let nextItem = this.keyPointData[index + 1]; if (curKeyPoint.pointType != CONST.POINT_TYPE.STRAIGHT) { nextItem.relationPoints[0] = x2; nextItem.relationPoints[1] = y2; } else { nextItem.relationPoints[0] = x; nextItem.relationPoints[1] = y; } } curKeyPoint.point = { x, y }; } } // handle aux keyPoint else if (type === CONST.CONTROL_TYPE.LEFT || type === CONST.CONTROL_TYPE.RIGHT) { if (curKeyPoint.pointType == CONST.POINT_TYPE.STRAIGHT) { curKeyPoint.pointType = CONST.POINT_TYPE.MIRRORED; } let x1: number, y1: number, x2: number, y2: number; let originX = curKeyPoint.relationPoints[4], originY = curKeyPoint.relationPoints[5]; if (curKeyPoint.type == "M") { originX = curKeyPoint.relationPoints[0]; originY = curKeyPoint.relationPoints[1]; } if (curKeyPoint.pointType == CONST.POINT_TYPE.MIRRORED) { if (type === CONST.CONTROL_TYPE.RIGHT) { x1 = originX * 2 - x; y1 = originY * 2 - y; x2 = x; y2 = y; } else { x2 = originX * 2 - x; y2 = originY * 2 - y; x1 = x; y1 = y; } this.updatePenPathControll(curKeyPoint, { x: originX, y: originY, x1, y1, x2, y2 }); if (curKeyPoint.type === "M") { if (index + 1 <= this.keyPointData.length - 1) { let nextItem = this.keyPointData[index + 1]; nextItem.relationPoints[0] = x2; nextItem.relationPoints[1] = y2; } if (curKeyPoint.pointType != CONST.POINT_TYPE.STRAIGHT) { curKeyPoint.relationPoints[2] = x1; curKeyPoint.relationPoints[3] = y1; } } else { curKeyPoint.relationPoints[2] = x1; curKeyPoint.relationPoints[3] = y1; if (index + 1 <= this.keyPointData.length - 1) { var nextItem = this.keyPointData[index + 1]; nextItem.relationPoints[0] = x2; nextItem.relationPoints[1] = y2; } } } else if (curKeyPoint.pointType == CONST.POINT_TYPE.DISJOINTED) { if (type === CONST.CONTROL_TYPE.RIGHT) { x2 = x; y2 = y; this.updatePenPathControll(curKeyPoint, { x: originX, y: originY, x2, y2 }, CONST.CONTROL_TYPE.RIGHT); if (curKeyPoint.type === "M") { if (index + 1 <= this.keyPointData.length - 1) { let nextItem = this.keyPointData[index + 1]; nextItem.relationPoints[0] = x2; nextItem.relationPoints[1] = y2; } } else { if (index + 1 <= this.keyPointData.length - 1) { let nextItem = this.keyPointData[index + 1]; nextItem.relationPoints[0] = x2; nextItem.relationPoints[1] = y2; } } } else { x1 = x; y1 = y; this.updatePenPathControll(curKeyPoint, { x: originX, y: originY, x1, y1 }, CONST.CONTROL_TYPE.LEFT); if (curKeyPoint.type === "M") { if (curKeyPoint.pointType != "straight") { curKeyPoint.relationPoints[2] = x1; curKeyPoint.relationPoints[3] = y1; } } else { curKeyPoint.relationPoints[2] = x1; curKeyPoint.relationPoints[3] = y1; } } } } this.refreshEditPath(); } /** * creating aux control handlers for curve * @param curKeyPoint the current operating keyPoint */ createPathCurveAux(curKeyPoint: KeyPoint): void { let originPoint = curKeyPoint.point, x = originPoint.x, y = originPoint.y; let circle1 = new PenCircle({ x, y, handleName: CONST.CONTROL_TYPE.LEFT, keyPointIndex: curKeyPoint.keyPointIndex, fill: this.options.circle.fill, stroke: this.options.circle.stroke, lineWidth: this.options.circle.lineWidth }), circle2 = new PenCircle({ x, y, handleName: CONST.CONTROL_TYPE.RIGHT, keyPointIndex: curKeyPoint.keyPointIndex, fill: this.options.circle.fill, stroke: this.options.circle.stroke, lineWidth: this.options.circle.lineWidth }), line1 = new PenLine({ x1: x, y1: y, x2: x, y2: y, stroke: this.options.line.stroke, lineWidth: this.options.line.lineWidth }), line2 = new PenLine({ x1: x, y1: y, x2: x, y2: y, stroke: this.options.line.stroke, lineWidth: this.options.line.lineWidth }); curKeyPoint.controller1 = circle1; curKeyPoint.controller2 = circle2; curKeyPoint.auxLine1 = line1; curKeyPoint.auxLine2 = line2; this.addCanvasObjects(circle1, circle2, line1, line2); } /** * update the handlers of the curve * @param item operating keyPoint * @param position the key coordinates. {x, y, x1, y1, x2, y2} * (x, y) is the main keyPoint's coordinates. (x1, y1) and (x2, y2) is the two controllers' coordinates. * @param type Indicates which auxLine and controller to update */ updatePenPathControll(item: KeyPoint, position: any, type?: string) { let x = position.x, y = position.y, x1 = position.x1, y1 = position.y1, x2 = position.x2, y2 = position.y2, { controller1, controller2, auxLine1, auxLine2 } = { ...item }; if (type == null || type === CONST.CONTROL_TYPE.LEFT) { if (controller1 != null) { controller1.x = x1; controller1.y = y1; } if (auxLine1 != null) { auxLine1.x1 = x1; auxLine1.y1 = y1; auxLine1.x2 = x; auxLine1.y2 = y; } } if (type == null || type === CONST.CONTROL_TYPE.RIGHT) { if (controller2 != null) { controller2.x = x2; controller2.y = y2; } if (auxLine2 != null) { auxLine2.x1 = x2; auxLine2.y1 = y2; auxLine2.x2 = x; auxLine2.y2 = y; } } } /** * save the coordinate informations when mousedown * (x, y) is the main keyPoint's coordinate * (x1, y1) and (x2, y2) is the controllers' coordinate */ setMousedownOrigin() { let curKeyPoint = this.keyPointData[this.currentKeyPointIndex], controller1 = curKeyPoint.controller1, controller2 = curKeyPoint.controller2, originPoint = curKeyPoint.point, origin: any = {}; if (controller1 != null) { origin.x1 = controller1.x; origin.y1 = controller1.y; } if (controller1 != null) { origin.x2 = controller2.x; origin.y2 = controller2.y; } if (originPoint != null) { origin.x = originPoint.x; origin.y = originPoint.y; } this.penMouseDownOrigin = origin; }; /** * update the pathObject when path is modified * @param isCashed whether update path with the keyPointDataCache */ refreshEditPath(isCashed: boolean = false): void { let keyPointData = this.keyPointData, closeState = this.closeState; if (keyPointData.length === 0) return; if (isCashed) { keyPointData = this.keyPointDataCache; closeState = this.cacheCloseState; } let pathStr: string = this._generatePathStr(keyPointData), fillColor: string = null, realPathStr = pathStr, auxPathStr = pathStr; if (closeState) { fillColor = this.options.pathFillColor; realPathStr += ' Z'; isCashed ? auxPathStr += ' Z' : ''; } if (this.realPathStr != null && this.realPathStr === pathStr && isCashed) { return; } else { this.realPathStr = realPathStr; // remove and redraw path let pathObjects = this.objects.filter(object => { return object.type === CONST.OBJECT_TYPE.PATH; }) this.removeObjects(...pathObjects); this.pathRealObject = { pathStr: this.realPathStr, type: CONST.OBJECT_TYPE.PATH, fill: fillColor || '#ebebeb', closeState: closeState, index: -Infinity // path's z-index keep lowest } this.addCanvasObjects(this.pathRealObject); } } /** * generate the pathStr according to keyPointData * @param keyPointData */ _generatePathStr(keyPointData: KeyPoint[]): string { let pathStr = ""; keyPointData.forEach(keyPoint => { let pathSection = ""; if (keyPoint.type === "M") { let str = `M ${keyPoint.relationPoints[0]} ${keyPoint.relationPoints[1]} `; pathSection += str; } else if (keyPoint.type === "C") { pathSection += "C "; keyPoint.relationPoints.forEach(value => { pathSection += value + " "; }) } pathStr += pathSection; }) if (this.closeState) { let firstKeyPoint = keyPointData[0], lastkeyPoint = keyPointData[keyPointData.length - 1]; pathStr += "C "; if (lastkeyPoint.pointType !== CONST.POINT_TYPE.STRAIGHT) { pathStr += `${lastkeyPoint.controller2.x} ${lastkeyPoint.controller2.y} `; } else { pathStr += `${lastkeyPoint.relationPoints[4]} ${lastkeyPoint.relationPoints[5]} `; } if (firstKeyPoint.pointType !== CONST.POINT_TYPE.STRAIGHT) { pathStr += `${firstKeyPoint.relationPoints[2]} ${firstKeyPoint.relationPoints[3]} `; } else { pathStr += `${firstKeyPoint.relationPoints[0]} ${firstKeyPoint.relationPoints[1]} `; } pathStr += `${firstKeyPoint.relationPoints[0]} ${firstKeyPoint.relationPoints[1]} `; } return pathStr; } /** * refresh and redraw the canvas */ refreshRender(): void { this.canvasCtx.clearRect(0, 0, this.canvas.width, this.canvas.height); this._matchObjectsByProrerty("penType", CONST.OBJECT_TYPE.PEN_AUX, (object: any) => { if (object.type === CONST.OBJECT_TYPE.CIRCLE) { this._bringToFront(object); } }) this.drawObjects(this.objects || []); } /** * drawing object on canvas * @param objects objects to be drawing */ drawObjects(objects: Array<any>): void { objects.forEach(object => { switch (object.type) { case CONST.OBJECT_TYPE.CIRCLE: this.drawCircle(object); break; case CONST.OBJECT_TYPE.LINE: this.drawLine(object); break; case CONST.OBJECT_TYPE.PATH: this.drawPath(object); break; default: break; } }) } /** * draw circle on canvas * @param options config of circle */ drawCircle(options: any) { this.canvasCtx.fillStyle = options.fill; this.canvasCtx.strokeStyle = options.stroke; this.canvasCtx.beginPath(); this.canvasCtx.arc( options.x, options.y, options.radius, 0, 2 * Math.PI ) this.canvasCtx.fill(); this.canvasCtx.stroke(); } /** * draw path on canvas * @param options config of path */ drawPath(options: any = {}) { this.canvasCtx.fillStyle = this.options.pathFillColor; this.canvasCtx.strokeStyle = this.options.pathColor; if (this.penModeOn) this.canvasCtx.strokeStyle = '#000'; this.canvasCtx.beginPath(); let path = new Path2D(this.realPathStr); this.canvasCtx.stroke(path); let isClosed = new RegExp('\\w*[zZ]{1}\\s*', 'g').test(this.realPathStr) if (options.closeState || isClosed) { /** * keyPointDataCache is null indicate that the drawing is completed. */ if (!this.keyPointDataCache && this.options.isFillPath) { this.canvasCtx.fill(path); } /** * when drawing uncomplete, the cache path closed, then fill */ else if (this.keyPointDataCache && this.keyPointData.length !== this.keyPointDataCache.length) { this.canvasCtx.fill(path); } } } /** * draw straight line on canvas * @param options config of line */ drawLine(options: any) { this.canvasCtx.fillStyle = options.fill; this.canvasCtx.strokeStyle = options.stroke; // this.canvasCtx.lineWidth = 5; this.canvasCtx.beginPath(); this.canvasCtx.moveTo(options.x1, options.y1); this.canvasCtx.lineTo(options.x2, options.y2); this.canvasCtx.stroke(); } /** * Add objects to Pen instance for rendering * @param objects objects for rendering * @returns returns adding objects */ addCanvasObjects(...objects: Array<any>): Array<any> { objects.forEach(object => { if (object.index == null) { object.index = this.objects.length; } this.objects.push(object); }) return objects; } /** * remove objects from Pen instance * @param objects objects to remove */ removeObjects(...objects: Array<any>): void { objects.forEach(object => { this.removeSingleObject(object) }) } /** * match currect object and remove it from instance * @param object object to remove */ removeSingleObject(object: any): void { for (let i = this.objects.length - 1; i >= 0; i--) { const item = this.objects[i]; if (item === object) { this.objects.splice(i, 1); break; } } } /** * Get the mouseover target * @param event */ _getMouseOverTarget(event: MouseEvent): any { let point: IPoint = { x: event.offsetX, y: event.offsetY }, target: any = null; // sort objects by index this.objects.sort((a, b) => { return a - b; }) for (let i = this.objects.length - 1; i >= 0; i--) { const object = this.objects[i]; if (this._containsPoint(point, object)) { target = object; break; } } return target; } /** * Checks if point is inside the object * @param point target point, always mouse position * @param object target object */ _containsPoint(point: IPoint, object: any): boolean { if (!object.type) return false; if (object.type === CONST.OBJECT_TYPE.CIRCLE) { let radius: number = object.radius, x: number = object.x, y: number = object.y; return point.x <= x + radius && point.x >= x - radius && point.y <= y + radius && point.y >= y - radius; } else if (object.type === CONST.OBJECT_TYPE.LINE) { // calculate the slope of line let slope: number = (object.y1 - object.y2) / (object.x1 - object.x2), slope2: number = (point.y - object.y1) / (point.x - object.x1); // slope is equal and the point coordinate is included in the line area indicate collinearity return slope === slope2 && (point.x >= object.x1 && point.x <= object.x2 && point.y >= object.y1 && point.y <= object.y2 || point.x >= object.x2 && point.x <= object.x1 && point.y >= object.y2 && point.y <= object.y1 ) } else if (object.type === CONST.OBJECT_TYPE.PATH) { let path = new Path2D(object.pathStr); return this.canvasCtx.isPointInStroke(path, point.x, point.y); } return false; } /** * Matches the object with the specified property name and value, and then performs the callback * @param key property name * @param value property value * @param callback callback function */ _matchObjectsByProrerty(key: string, value: string, callback: Function): void { let objects: Array<any> = this.objects; objects.forEach(object => { // match object if (object[key] === value) { callback(object); } }) } /** * Put the object at the end of the array to make canvas draw last * so as to achieve the purpose of the object at the top after drawing * @param object */ _bringToFront(object: any) { object.index = Infinity; // Make sure the index is the largest // resort objects and set index this.objects.sort((a, b) => { return a.index - b.index; }) this.objects.forEach((item, index) => { item.index = index; }) } /** * change the keyPoint type when dblclick on the keyPoint * when keyPoint is the straight line keyPoint, it will be a curve keyPoint after dblclick * when keyPoint is the curve keyPoint, it will be a straight line keyPoint after dblclick * @param target * @param pointType the pointType attribute of current operating keyPoint */ changeKeyPointType(target: KeyPoint, pointType?: string): void { let index = target.keyPointIndex, curPoint = this.keyPointData[index], typelist = { ...CONST.POINT_TYPE }; if (!(pointType == null || (curPoint.pointType === CONST.POINT_TYPE.STRAIGHT && pointType in typelist) || (pointType === CONST.POINT_TYPE.STRAIGHT && curPoint.pointType in typelist))) { curPoint.pointType = pointType; return; } if (curPoint.controller1 == null) { this.createPathCurveAux(curPoint); curPoint.pointType = pointType || CONST.POINT_TYPE.MIRRORED; let preItem: KeyPoint, // previous keyPoint to target nextItem: KeyPoint, // next keyPoint to target preX: number, // previous keyPoint's coordinate preY: number, // previous keyPoint's coordinate nextX: number, // next keyPoint's coordinate nextY: number, // next keyPoint's coordinate x: number, // current keyPoint's coordinate y: number, // current keyPoint's coordinate radian: number, // the radian corresponding to the inclination angle of the line between two points hypotenuse: number, // the hypotenuse of a right triangle made up of two points x1: number, x2: number, y1: number, y2: number; if (target.keyPointIndex === 0) { preItem = this.keyPointData[this.keyPointData.length - 1]; } else { preItem = this.keyPointData[target.keyPointIndex - 1]; } if (target.keyPointIndex === this.keyPointData.length - 1) { nextItem = this.keyPointData[0]; } else { nextItem = this.keyPointData[target.keyPointIndex + 1]; } preX = preItem.point.x, preY = preItem.point.y, nextX = nextItem.point.x, nextY = nextItem.point.y, x = curPoint.point.x, y = curPoint.point.y; radian = Math.atan2(nextY - preY, nextX - preX), // The half of the hypotenuse of the right triangle formed by the coordinates of the previous and next keyPoint is used as the base of the offset when calculating the coordinates of the control point hypotenuse = Math.sqrt(Math.pow(nextX - preX, 2) + Math.pow(nextY - preY, 2)) / 2; x1 = Math.round(x - hypotenuse * Math.cos(radian)), y1 = Math.round(y - hypotenuse * Math.sin(radian)), x2 = Math.round(x + hypotenuse * Math.cos(radian)), y2 = Math.round(y + hypotenuse * Math.sin(radian)); this.updatePenPathControll(curPoint, { x, y, x1, y1, x2, y2 }); if (index + 1 <= this.keyPointData.length - 1) { let nextItem = this.keyPointData[index + 1]; nextItem.relationPoints[0] = x2; nextItem.relationPoints[1] = y2; } curPoint.relationPoints[2] = x1; curPoint.relationPoints[3] = y1; } else { this.removeObjects(curPoint.controller1, curPoint.controller2, curPoint.auxLine1, curPoint.auxLine2); delete curPoint.controller1, delete curPoint.controller2, delete curPoint.auxLine1, delete curPoint.auxLine2; curPoint.pointType = CONST.POINT_TYPE.STRAIGHT; let x = curPoint.point.x, y = curPoint.point.y; if (curPoint.pointType === "M") { if (curPoint.relationPoints.length > 2) { curPoint.relationPoints.splice(-2, 2); } } else { curPoint.relationPoints[2] = x; curPoint.relationPoints[3] = y; } if (index + 1 <= this.keyPointData.length - 1) { let nextItem = this.keyPointData[index + 1]; nextItem.relationPoints[0] = x; nextItem.relationPoints[1] = y; } } this.refreshEditPath(); } /** * generate the path with keyPoints and handlers */ generateEditablePath() { this.penModeOn = true; // reset objects this.objects = []; // generate keyPoints and aux this.generateAuxPointLine(this.keyPointData); // generate pathstr this.refreshEditPath(); this.refreshRender(); } /** * generate the aux keyPoints and handlers to render * @param keyPointData collection of path's keyPoints */ generateAuxPointLine(keyPointData: KeyPoint[] = []) { if (keyPointData.length === 0) return; keyPointData.forEach((keyPoint) => { let x = keyPoint.point.x, y = keyPoint.point.y, circle = new PenCircle({ x, y, keyPointIndex: keyPoint.keyPointIndex, fill: this.options.circle.fill, stroke: this.options.circle.stroke }); this.addCanvasObjects(circle); // add keyPoint // when curve, add handlers if (keyPoint.pointType !== CONST.POINT_TYPE.STRAIGHT) { this.addCanvasObjects(keyPoint.auxLine1, keyPoint.auxLine2, keyPoint.controller1, keyPoint.controller2); } }) } } export default Pen;
the_stack
import 'jest' import createBistate, { mutate, watch, remove, isBistate, lock, unlock } from '../src/createBistate' describe('createBistate', () => { it('should throw error when createBistate got invalide arguments', () => { expect(() => { createBistate(undefined) }).toThrow() expect(() => { createBistate(1 as any) }).toThrow() expect(() => { createBistate('123' as any) }).toThrow() expect(() => { createBistate(null) }).toThrow() createBistate([]) createBistate({}) }) it('can be detected by isBistate', () => { expect(isBistate(1)).toBe(false) expect(isBistate('1')).toBe(false) expect(isBistate([])).toBe(false) expect(isBistate({})).toBe(false) expect(isBistate(null)).toBe(false) expect(isBistate(undefined)).toBe(false) expect(isBistate(() => {})).toBe(false) expect(isBistate(createBistate({}))).toBe(true) expect(isBistate(createBistate([]))).toBe(true) }) it('should not reuse or mutate state which is came from arguments', () => { let initialState = { a: 1 } let state0 = createBistate(initialState) expect(state0 !== initialState).toBe(true) let state1 = createBistate(state0) expect(state1 !== state0).toBe(true) expect(state1 !== initialState) expect(state1).toEqual({ a: 1 }) expect(state0).toEqual({ a: 1 }) expect(initialState).toEqual({ a: 1 }) }) it('can be watched', () => { let state = createBistate({ count: 0 }) let n = 0 watch(state, nextState => { expect(n).toBe(0) expect(nextState !== state).toBe(true) expect(state.count).toBe(0) expect(nextState.count).toBe(1) n += 1 }) mutate(() => { state.count += 1 }) expect(n).toBe(1) expect(state.count).toBe(0) }) it('can be unwatched', () => { let state = createBistate({ count: 0 }) let unwatch = watch(state, () => { throw new Error('unwatch failed') }) unwatch() mutate(() => { state.count += 1 }) expect(state.count).toBe(0) }) it('should detect object mutation', () => { let state = createBistate({ a: 1, b: 2, c: 3 } as { a: number b: number c: number d?: number }) let n = 0 watch(state, nextState => { expect(n).toBe(0) n += 1 expect(nextState).toEqual({ a: 2, c: 3, d: 1 }) expect(state).toEqual({ a: 1, b: 2, c: 3 }) }) mutate(() => { // replace state.a += 1 // delete delete state.b // add state.d = 1 }) expect(n).toBe(1) }) it('should detect list mutation', () => { let list = createBistate([1, 2, 3, 4, 5, 6]) let n = 0 watch(list, nextList => { expect(n).toBe(0) expect(nextList).toEqual([2, 3, 4, 5, 6, 3]) expect(list).toEqual([1, 2, 3, 4, 5, 6]) n += 1 }) mutate(() => { // replace list[0] = 2 // delete list.splice(1, 1) // add list.push(3) }) expect(n).toBe(1) }) it('should support deep update', () => { let state = createBistate([ { a: { b: { c: { d: [1, 2, 3], e: 2, f: 1 } } } } ]) let n = 0 watch(state, nextState => { expect(n).toBe(0) n += 1 expect(nextState).toEqual([ { a: { b: { c: { d: [2, 3, 4], e: 3 } } } } ]) }) mutate(() => { // add item state[0].a.b.c.d.push(4) // remove item state[0].a.b.c.d.shift() // replace property value state[0].a.b.c.e += 1 // delete delete state[0].a.b.c.f }) expect(n).toBe(1) }) it('should throw error when mutate(f) got async function or return promise', () => { expect(() => { // tslint:disable-next-line: no-floating-promises mutate(async () => { // }) }).toThrow() expect(() => { // tslint:disable-next-line: no-floating-promises mutate(() => { return Promise.resolve() }) }).toThrow() }) it('should throw error when mutate state out of mutate function', () => { let state = createBistate({ count: 0 }) expect(() => { state.count += 1 }).toThrow() }) it('should throw error when mutate state in watcher function', () => { let state = createBistate({ count: 0 }) let n = 0 watch(state, nextState => { expect(n).toBe(0) n += 1 expect(() => { state.count += 1 }).toThrow() expect(() => { nextState.count += 1 }).toThrow() }) mutate(() => { state.count += 1 }) expect(n).toBe(1) }) it('should throw error when watch a state twice', () => { let state = createBistate({ a: 1 }) let unwatch = watch(state, () => { // empty }) expect(() => { watch(state, () => { // empty }) }).toThrow() unwatch() watch(state, () => { // empty }) }) it('should throw error when watch a state which is not a bistate or watcher is not a function', () => { expect(() => { watch({}, () => { // }) }).toThrow() expect(() => { watch(createBistate({}), 1 as any) }) }) it('should batch all mutation into one update when mutate state', () => { let state = createBistate({ a: 1, b: 2, c: 3 }) let n = 0 watch(state, nextState => { expect(n).toBe(0) n += 1 expect(nextState).toEqual({ a: 2, b: 3 }) expect(state).toEqual({ a: 1, b: 2, c: 3 }) }) mutate(() => { state.a += 1 state.b += 1 delete state.c }) expect(n).toBe(1) }) it('can batch multiple states changed and trigger watcher in mutated order', () => { let state0 = createBistate({ a: 1 }) let state1 = createBistate({ a: 2 }) let n = 0 watch(state0, nextState0 => { expect(n).toBe(1) n += 1 expect(nextState0).toEqual({ a: 2 }) }) watch(state1, nextState0 => { expect(n).toBe(0) n += 1 expect(nextState0).toEqual({ a: 1 }) }) mutate(() => { state1.a -= 1 state0.a += 1 }) expect(n).toBe(2) }) it('mutate function can return value', () => { let state = createBistate({ count: 0 }) let n = mutate(() => { state.count += 1 return state.count }) expect(state.count).toBe(0) expect(n).toBe(1) }) it('mutate function can be nest', () => { let state = createBistate({ count: 0 }) let i = 0 watch(state, nextState => { expect(i).toBe(0) expect(nextState) }) let n = mutate(() => { state.count += 1 return mutate(() => { state.count += 1 return state.count }) }) expect(state.count).toBe(0) expect(n).toBe(2) }) it('can remove object property by remove function', () => { let state = createBistate({ a: { value: 1 } }) let n = 0 watch(state, nextState => { expect(n).toBe(0) n += 1 expect(nextState).toEqual({}) expect(state).toEqual({ a: { value: 1 } }) }) expect(() => { remove(state.a) }).toThrow() mutate(() => { remove(state.a) }) }) it('can remove list item by remove function', () => { let state = createBistate([{ value: 1 }, { value: 2 }, { value: 3 }]) let n = 0 watch(state, nextState => { expect(n).toBe(0) n += 1 expect(nextState).toEqual([{ value: 1 }, { value: 3 }]) expect(state).toEqual([{ value: 1 }, { value: 2 }, { value: 3 }]) expect(state[0] === nextState[0]).toBe(true) expect(state[2] === nextState[1]).toBe(true) }) mutate(() => { remove(state[1]) }) expect(n).toBe(1) }) it('should throw error when remove target is not a bistate', () => { expect(() => { remove({}) }).toThrow() }) it('should support structural sharing', () => { let state = createBistate({ a: [{ value: 1 }, { value: 2 }, { value: 3 }], b: [{ value: 1 }, { value: 2 }, { value: 3 }], c: [{ value: 1 }, { value: 2 }, { value: 3 }] } as { a: { value: number }[] b: { value: number }[] c: { value: number }[] d?: { value: number }[] }) let n = 0 watch(state, nextState => { expect(n).toBe(0) n += 1 expect(nextState).toEqual({ a: [{ value: 2 }, { value: 2 }, { value: 3 }], b: [{ value: 1 }, { value: 2 }, { value: 4 }], c: [{ value: 1 }, { value: 2 }, { value: 3 }], d: [{ value: 1 }, { value: 2 }, { value: 3 }] }) expect(state.c === nextState.c).toBe(true) expect(state.a[1] === nextState.a[1]).toBe(true) expect(state.a[2] === nextState.a[2]).toBe(true) expect(state.b[0] === nextState.b[0]).toBe(true) expect(state.b[1] === nextState.b[1]).toBe(true) expect(state.c[0] === nextState.c[0]).toBe(true) expect(state.c[1] === nextState.c[1]).toBe(true) expect(state.c[2] === nextState.c[2]).toBe(true) }) mutate(() => { state.a[0].value += 1 state.b[2].value += 1 state.d = [{ value: 1 }, { value: 2 }, { value: 3 }] }) expect(n).toBe(1) }) it('access state property should works correctly in mutate function', () => { let state = createBistate([{ a: 1, b: 2 }, { a: 1, b: 1 }] as { a: number b: number c?: number }[]) let n = 0 mutate(() => { n += 1 expect(state.length).toBe(2) state[0].a += 1 expect(state[0].a).toBe(2) state.pop() expect(state.length).toBe(1) expect('a' in state[0]).toBe(true) delete state[0].a expect('a' in state[0]).toBe(false) expect(Object.getOwnPropertyNames(state[0])).toEqual(['b']) state[0].c = 1 expect(Object.getOwnPropertyNames(state[0])).toEqual(['b', 'c']) expect(state[0].c).toBe(1) }) expect('a' in state[0]).toBe(true) expect('b' in state[0]).toBe(true) expect('c' in state[0]).toBe(false) expect(Object.getOwnPropertyNames(state[0])).toEqual(['a', 'b']) expect(n).toBe(1) }) it('should throw error when watcher is not a function', () => { let state = createBistate({ count: 1 }) expect(() => { watch(state, 1 as any) }).toThrow() }) it('should trigger watcher directly when state has been mutated', () => { let state = createBistate({ count: 1 }) let n = 0 mutate(() => { state.count += 1 }) watch(state, nextState => { expect(n).toBe(0) n += 1 expect(nextState).toEqual({ count: 2 }) }) expect(state).toEqual({ count: 1 }) expect(n).toBe(1) }) it('should throw error when mutate a state(which has been watched) more than once', () => { let state = createBistate({ count: 1 }) watch(state, nextState => { expect(nextState).toEqual({ count: 2 }) }) mutate(() => { state.count += 1 }) expect(() => { mutate(() => { state.count += 1 }) }).toThrow() }) it('should throw error when watch a non-root state', () => { let state = createBistate({ a: { value: 1 } }) expect(() => { watch(state.a, () => { // nothing }) }).toThrow() }) it('should throw error when mutate function got invalid arguments', () => { mutate(() => { // nothing }) expect(() => { mutate(1 as any) }).toThrow() }) it('should reuse object property correctly', () => { let state = createBistate({ a: { value: 1 }, b: { value: 2 } } as { a: { value: number } b: { value: number } c?: { value: number } }) let n = 0 watch(state, nextState => { expect(n).toBe(0) n += 1 expect(state.a === nextState.b).toBe(true) expect(state.b === nextState.a).toBe(true) // should state when the value already existed expect(state.a === nextState.c).toBe(false) expect(nextState).toEqual({ a: { value: 2 }, b: { value: 1 }, c: { value: 1 } }) }) mutate(() => { let { a, b } = state state.a = b state.b = a state.c = a expect(state.b === state.c).toEqual(true) }) expect(n).toBe(1) }) it('should reuse list item correctly', () => { let state = createBistate([{ value: 1 }, { value: 2 }, { value: 3 }]) let n = 0 watch(state, nextState => { expect(n).toBe(0) n += 1 expect(nextState).toEqual([{ value: 3 }, { value: 1 }, { value: 2 }, { value: 3 }]) expect(state).toEqual([{ value: 1 }, { value: 2 }, { value: 3 }]) expect(nextState[0] === state[2]).toBe(true) expect(nextState[1] === state[0]).toBe(true) expect(nextState[2] === state[1]).toBe(true) // should recreate state when the value already existed expect(nextState[3] !== state[2]).toBe(true) }) mutate(() => { let [a, b, c] = state state[0] = c state[1] = a state[2] = b state[3] = c }) expect(n).toBe(1) }) it('should only reuse state at the same layer', () => { let state = createBistate({ a: { count: 0 }, b: { value: { count: 1 } } }) let n = 0 watch(state, nextState => { expect(n).toBe(0) n += 1 expect(nextState).toEqual({ a: { count: 1 }, b: { value: { count: 0 } } }) expect(nextState.a === state.b.value).toBe(false) }) mutate(() => { let a = state.a state.a = state.b.value state.b.value = a }) expect(n).toBe(1) }) it('can lock and unlock state', () => { let state = createBistate({ count: 1 }) let n = 0 lock(state) watch(state, nextState => { expect(n).toBe(0) n += 1 expect(nextState).toEqual({ count: 3 }) }) mutate(() => { expect(state).toEqual({ count: 1 }) state.count += 1 }) expect(state).toEqual({ count: 1 }) mutate(() => { expect(state).toEqual({ count: 2 }) state.count += 1 }) expect(state).toEqual({ count: 1 }) unlock(state) expect(state).toEqual({ count: 1 }) expect(n).toBe(1) }) })
the_stack
import { BoundingBox, MathUtil, Rect, Vector2, Vector4 } from "@oasis-engine/math"; import { RefObject } from "../../asset/RefObject"; import { Engine } from "../../Engine"; import { Texture2D } from "../../texture/Texture2D"; /** * 2D sprite. */ export class Sprite extends RefObject { private static _rectangleTriangles: number[] = [0, 2, 1, 2, 0, 3]; /** The name of sprite. */ name: string; /** @internal */ _uv: Vector2[] = [new Vector2(), new Vector2(), new Vector2(), new Vector2()]; /** @internal */ _positions: Vector2[] = [new Vector2(), new Vector2(), new Vector2(), new Vector2()]; /** @internal */ _bounds: BoundingBox = new BoundingBox(); /** @internal */ _triangles: number[]; /** @internal temp solution. */ _assetID: number; private _pixelsPerUnit: number; private _texture: Texture2D = null; private _atlasRotated: boolean = false; private _region: Rect = new Rect(0, 0, 1, 1); private _pivot: Vector2 = new Vector2(0.5, 0.5); private _atlasRegion: Rect = new Rect(0, 0, 1, 1); private _atlasRegionOffset: Vector4 = new Vector4(0, 0, 0, 0); private _dirtyFlag: DirtyFlag = DirtyFlag.all; /** * The reference to the used texture. */ get texture(): Texture2D { return this._texture; } set texture(value: Texture2D) { if (this._texture !== value) { this._texture = value; this._setDirtyFlagTrue(DirtyFlag.positions); } } /** * Bounding volume of the sprite. * @remarks The returned bounds should be considered deep-read-only. */ get bounds(): Readonly<BoundingBox> { if (this._isContainDirtyFlag(DirtyFlag.positions) && this._texture) { this._updatePositionsAndBounds(); this._setDirtyFlagFalse(DirtyFlag.positions); } return this._bounds; } /** * Is it rotated 90 degrees clockwise when packing. */ get atlasRotated(): boolean { return this._atlasRotated; } set atlasRotated(value: boolean) { if (this._atlasRotated != value) { this._atlasRotated = value; this._setDirtyFlagTrue(DirtyFlag.positions | DirtyFlag.uv); } } /** * The rectangle region of the original texture on its atlas texture, specified in normalized. */ get atlasRegion(): Rect { return this._atlasRegion; } set atlasRegion(value: Rect) { const x = MathUtil.clamp(value.x, 0, 1); const y = MathUtil.clamp(value.y, 0, 1); this._atlasRegion.setValue(x, y, MathUtil.clamp(value.width, 0, 1 - x), MathUtil.clamp(value.height, 0, 1 - y)); this._setDirtyFlagTrue(DirtyFlag.positions | DirtyFlag.uv); } /** * The rectangle region offset of the original texture on its atlas texture, specified in normalized. */ get atlasRegionOffset(): Vector4 { return this._atlasRegionOffset; } set atlasRegionOffset(value: Vector4) { const x = MathUtil.clamp(value.x, 0, 1); const y = MathUtil.clamp(value.y, 0, 1); this._atlasRegionOffset.setValue(x, y, MathUtil.clamp(value.z, 0, 1 - x), MathUtil.clamp(value.w, 0, 1 - y)); this._setDirtyFlagTrue(DirtyFlag.positions | DirtyFlag.uv); } /** * Location of the sprite's center point in the rectangle region, specified in normalized. */ get pivot(): Vector2 { return this._pivot; } set pivot(value: Vector2) { const pivot = this._pivot; const x = MathUtil.clamp(value.x, 0, 1); const y = MathUtil.clamp(value.y, 0, 1); if (pivot === value || pivot.x !== x || pivot.y !== y) { pivot.setValue(x, y); this._setDirtyFlagTrue(DirtyFlag.positions); } } /** * The rectangle region of the sprite, specified in normalized. */ get region(): Rect { return this._region; } set region(value: Rect) { const region = this._region; const x = MathUtil.clamp(value.x, 0, 1); const y = MathUtil.clamp(value.y, 0, 1); region.setValue(x, y, MathUtil.clamp(value.width, 0, 1 - x), MathUtil.clamp(value.height, 0, 1 - y)); this._setDirtyFlagTrue(DirtyFlag.positions | DirtyFlag.uv); } /** * The number of pixels in the sprite that correspond to one unit in world space. */ get pixelsPerUnit(): number { return this._pixelsPerUnit; } set pixelsPerUnit(value: number) { if (this._pixelsPerUnit !== value) { this._pixelsPerUnit = value; this._setDirtyFlagTrue(DirtyFlag.positions); } } /** * Clone. * @returns Cloned sprite */ clone(): Sprite { const cloneSprite = new Sprite( this._engine, this._texture, this._region, this._pivot, this._pixelsPerUnit, this.name ); cloneSprite._assetID = this._assetID; cloneSprite._atlasRotated = this._atlasRotated; this._atlasRegion.cloneTo(cloneSprite._atlasRegion); this._atlasRegionOffset.cloneTo(cloneSprite._atlasRegionOffset); return cloneSprite; } /** * Constructor a Sprite. * @param engine - Engine to which the sprite belongs * @param texture - Texture from which to obtain the Sprite * @param region - Rectangle region of the texture to use for the Sprite, specified in normalized * @param pivot - Sprite's pivot point relative to its graphic rectangle, specified in normalized * @param pixelsPerUnit - The number of pixels in the Sprite that correspond to one unit in world space * @param name - The name of Sprite */ constructor( engine: Engine, texture: Texture2D = null, region: Rect = null, pivot: Vector2 = null, pixelsPerUnit: number = 128, name: string = null ) { super(engine); this.name = name; this._texture = texture; this._pixelsPerUnit = pixelsPerUnit; region && region.cloneTo(this._region); pivot && pivot.cloneTo(this._pivot); this._triangles = Sprite._rectangleTriangles; } /** * @override */ _onDestroy(): void { if (this._texture) { this._texture = null; } } /** * Update positions and bounds. */ private _updatePositionsAndBounds(): void { const { _texture: texture, _bounds: bounds } = this; if (texture) { const { _atlasRegion: atlasRegion, _pivot: pivot, _atlasRegionOffset: atlasRegionOffset } = this; const { x: regionX, y: regionY, width: regionW, height: regionH } = this._region; const pPUReciprocal = 1.0 / this._pixelsPerUnit; // Coordinates of the four boundaries. let lx: number, ty: number, rx: number, by: number; // TextureSize let textureW: number, textureH: number; if (this._atlasRotated) { textureW = texture.height * atlasRegion.height * pPUReciprocal; textureH = texture.width * atlasRegion.width * pPUReciprocal; } else { textureW = texture.width * atlasRegion.width * pPUReciprocal; textureH = texture.height * atlasRegion.height * pPUReciprocal; } // Determine whether it has been trimmed. if ( atlasRegionOffset.x == 0 && atlasRegionOffset.y == 0 && atlasRegionOffset.z == 0 && atlasRegionOffset.w == 0 ) { // Real rendering size. const realRenderW = textureW * regionW; const realRenderH = textureH * regionH; lx = -pivot.x * realRenderW; by = -pivot.y * realRenderH; rx = realRenderW + lx; ty = realRenderH + by; } else { const { x: blankLeft, y: blankTop, z: blankRight, w: blankBottom } = atlasRegionOffset; const oriWidth = textureW / (1 - blankRight - blankLeft); const oriHeight = textureH / (1 - blankBottom - blankTop); // The size of the real rendering. lx = (-pivot.x * regionW + Math.max(blankLeft, regionX) - regionX) * oriWidth; ty = (pivot.y * regionH - Math.max(blankTop, regionY) + regionY) * oriHeight; rx = (-pivot.x * regionW + Math.min(1 - blankRight, regionX + regionW) - regionX) * oriWidth; by = (pivot.y * regionH - Math.min(1 - blankBottom, regionY + regionH) + regionY) * oriHeight; } // Assign values ​​to _positions const positions = this._positions; // Top-left. positions[0].setValue(lx, ty); // Top-right. positions[1].setValue(rx, ty); // Bottom-right. positions[2].setValue(rx, by); // Bottom-left. positions[3].setValue(lx, by); // Update bounds. bounds.min.setValue(lx, by, 0); bounds.max.setValue(rx, ty, 0); } else { // Update bounds. bounds.min.setValue(0, 0, 0); bounds.max.setValue(0, 0, 0); } } /** * Update mesh. */ private _updateMesh(): void { if (this._isContainDirtyFlag(DirtyFlag.positions)) { this._updatePositionsAndBounds(); } if (this._isContainDirtyFlag(DirtyFlag.uv)) { const { _atlasRegion, _uv: uv, _region: region, _atlasRotated, _atlasRegionOffset: atlasRegionOffset } = this; let left: number, top: number, right: number, bottom: number; // Determine whether it has been trimmed. if ( atlasRegionOffset.x == 0 && atlasRegionOffset.y == 0 && atlasRegionOffset.z == 0 && atlasRegionOffset.w == 0 ) { const { width: atlasRegionW, height: atlasRegionH } = _atlasRegion; if (_atlasRotated) { left = atlasRegionW * (1 - region.y - region.height) + _atlasRegion.x; top = atlasRegionH * region.x + _atlasRegion.y; right = atlasRegionW * region.height + left; bottom = atlasRegionH * region.width + top; } else { left = atlasRegionW * region.x + _atlasRegion.x; top = atlasRegionH * region.y + _atlasRegion.y; right = atlasRegionW * region.width + left; bottom = atlasRegionH * region.height + top; } } else { const { x: regionX, y: regionY } = region; const { x: atlasRegionX, y: atlasRegionY } = _atlasRegion; const { x: blankLeft, y: blankTop, z: blankRight, w: blankBottom } = atlasRegionOffset; // Proportion of the original sprite size in the atlas. if (_atlasRotated) { const textureW = _atlasRegion.width / (1 - blankBottom - blankTop); const textureH = _atlasRegion.height / (1 - blankRight - blankLeft); left = (Math.max(blankBottom, 1 - regionY - region.height) - blankBottom) * textureW + atlasRegionX; top = (Math.max(blankLeft, regionX) - blankLeft) * textureH + atlasRegionY; right = (Math.min(1 - blankTop, 1 - regionY) - blankBottom) * textureW + atlasRegionX; bottom = (Math.min(1 - blankRight, regionX + region.width) - blankLeft) * textureH + atlasRegionY; } else { const textureW = _atlasRegion.width / (1 - blankRight - blankLeft); const textureH = _atlasRegion.height / (1 - blankBottom - blankTop); left = (Math.max(blankLeft, regionX) - blankLeft) * textureW + atlasRegionX; top = (Math.max(blankTop, regionY) - blankTop) * textureH + atlasRegionY; right = (Math.min(1 - blankRight, regionX + region.width) - blankLeft) * textureW + atlasRegionX; bottom = (Math.min(1 - blankBottom, regionY + region.height) - blankTop) * textureH + atlasRegionY; } } if (_atlasRotated) { // If it is rotated, we need to rotate the UV 90 degrees counterclockwise to correct it. // Top-right. uv[0].setValue(right, top); // Bottom-right. uv[1].setValue(right, bottom); // Bottom-left. uv[2].setValue(left, bottom); // Top-left. uv[3].setValue(left, top); } else { // Top-left. uv[0].setValue(left, top); // Top-right. uv[1].setValue(right, top); // Bottom-right. uv[2].setValue(right, bottom); // Bottom-left. uv[3].setValue(left, bottom); } } } /** * @internal * Update mesh data of the sprite. * @returns True if the data is refreshed, false otherwise. */ _updateMeshData(): boolean { if (this._isContainDirtyFlag(DirtyFlag.all)) { this._updateMesh(); this._setDirtyFlagFalse(DirtyFlag.all); return true; } return false; } private _isContainDirtyFlag(type: number): boolean { return (this._dirtyFlag & type) != 0; } private _setDirtyFlagTrue(type: number): void { this._dirtyFlag |= type; } private _setDirtyFlagFalse(type: number): void { this._dirtyFlag &= ~type; } } enum DirtyFlag { positions = 0x1, uv = 0x2, all = 0x3 }
the_stack
import { I, IOperatantType } from './vm/vm' import { getByteLengthFromInt32, concatBuffer, stringToArrayBuffer, createOperantBuffer, getOperatantByBuffer, getOperantName } from './utils' import { parseCode, parseAssembler, IParsedFunction } from './parser' import { optimizeCode } from './optimizer' /** * * MOV dest src 赋值给变量 * * ADD d s * SUB d s * DIV d s * MOD d s * EXP d power * NEG * INC * DEC * * * AND d s * OR .. * XOR .. * NOT d * SHL d count * SHR d count * * JMP label * JE op1 op1 label * JNE op1 op1 label * JG op1 op2 label * JL op1 op2 label * JGE op1 op2 label * JLE op1 op2 label * PUSH src * POP dest * CALL function numArgs * RET * * PAUSE ms * EXIT code */ /** * Func Add { * PARAM Y * PARAM X * VAR SUM * MOV SUM, X * ADD SUM, Y * MOV _RET_VAL, SUM * } * VAR * PUSH * POP * LABEL */ /** * * */ /** 函数调用的堆栈结构 * X * Y * Z * ARRAY... * - old frame pointer * - return instruction pointer * - num args * PARAM1 * PARAM2 */ interface IFuncInfo { name: string, symbols: Map<string, any>, codes: string[][], numArgs: number, localSize: number, globals: any, ip?: number, index?: number, bytecodes?: ArrayBuffer, labels?: any, } // tslint:disable-next-line: no-big-function export const parseCodeToProgram = (program: string): Buffer => { const funcsTable = {} const globalSymbols = new Map<string, any>() const stringTable: string[] = [] const stringIndex: any = {} const funcs = parseAssembler(optimizeCode(program)) // const funcs = parseAssembler(program) // program const _symbols = new Map<string, number>() let symbolsCounter = 0 const getSymbolIndex = (name: string): number => { if (_symbols.has(name)) { return _symbols.get(name)! } else { _symbols.set(name, symbolsCounter++) return _symbols.get(name)! } } // .trim() // .match(/func\s[\s\S]+?\}/g) || [] // console.log(funcs, '--->') // 1 pass const funcsInfo: any[] = [] let globalSize: number = 0 funcs.forEach((func: IParsedFunction): void => { if (!func) { return } const funcInfo = parseFunction(func) funcInfo.index = funcsInfo.length funcsInfo.push(funcInfo) funcsTable[funcInfo.name] = funcInfo funcInfo.globals.forEach((g: string): void => { globalSymbols[g] = globalSize++ }) }) // 2 pass funcsInfo.forEach((funcInfo: IFuncInfo): void => { const symbols = funcInfo.symbols // console.log(symbols) funcInfo.codes.forEach((code: any[]): void => { const op = code[0] code[0] = I[op] if (op === 'CALL' && op) { code[1] = { type: IOperatantType.FUNCTION_INDEX, value: funcsTable[code[1]].index, } code[2] = { type: IOperatantType.ARG_COUNT, value: +code[2], } } else { code.forEach((o: any, i: number): void => { if (i === 0) { return } if ( (op === 'TRY' && (i === 1 || i === 2)) || ['JMP'].includes(op) || (['JE', 'JNE', 'JG', 'JL', 'JGE', 'JLE'].includes(op) && i === 3) || (['JF', 'JIF'].includes(op) && i === 2) || (op === 'FORIN' && (i === 3 || i === 4)) ) { code[i] = { type: IOperatantType.ADDRESS, value: funcInfo.labels[code[i]], } return } if (['FUNC'].includes(op) && i === 2) { code[i] = { type: IOperatantType.FUNCTION_INDEX, value: funcsTable[code[i]].index, } return } // const namemap = { // '@': IOperatantType.CLOSURE_REGISTER, // '.': IOperatantType.PARAM_REGISTER, // '%': IOperatantType.REGISTER, // } if (!['VAR', 'CLS'].includes(op)) { /** 寄存器 */ let regIndex = symbols.get(o) if (regIndex !== undefined) { code[i] = { type: o[0] === IOperatantType.REGISTER, value: regIndex, } return } /** 全局 */ regIndex = globalSymbols.get(o) if (regIndex !== undefined) { code[i] = { type: IOperatantType.GLOBAL, value: regIndex + 1, // 留一位给 RET } return } if (o === 'true' || o === 'false') { code[i] = { type: IOperatantType.BOOLEAN, value: o === 'true' ? 1: 0, } return } if (o === 'null') { code[i] = { type: IOperatantType.NULL, } return } if (o === 'undefined') { code[i] = { type: IOperatantType.UNDEFINED, } return } /** 返回类型 */ if (o === '$RET') { code[i] = { type: IOperatantType.RETURN_VALUE, } return } /** 字符串 */ if (o.match(/^\"[\s\S]*\"$/) || o.match(/^\'[\s\S]*\'$/)) { const str = o.replace(/^[\'\"]|[\'\"]$/g, '') let index = stringIndex[str] index = typeof index === 'number' ? index : void 0 // 'toString' 不就挂了? code[i] = { type: IOperatantType.STRING, value: index === undefined ? stringTable.length : index, } if (index === undefined) { stringIndex[str] = stringTable.length stringTable.push(str) } return } /** Number */ if (!isNaN(+o)) { code[i] = { type: IOperatantType.NUMBER, value: +o, } return } } /** 普通变量或者闭包 */ const symbolIndex = getSymbolIndex(o.replace(/^@/, '')) code[i] = { type: o.startsWith('@') ? IOperatantType.CLOSURE_REGISTER : IOperatantType.VAR_SYMBOL, value: symbolIndex, } // console.log('symbol index -> ', symbolIndex, o) }) } }) }) // console.log('\n\n====================================') // funcsInfo[0].codes.forEach((c: any): void => { // console.log(I[c[0]], c.slice(1)) // }) // console.log('====================================\n\n') const stream = parseToStream(funcsInfo, stringTable, globalSize) return Buffer.from(stream) } /** * header * codes (op(1) operantType(1) value(??) oprantType value | ...) * functionTable (ip(1) | numArgs(2)) * stringTable (len(4) str | len(4) str) */ // tslint:disable-next-line: no-big-function const parseToStream = (funcsInfo: IFuncInfo[], strings: string[], globalsSize: number): ArrayBuffer => { const stringTable = parseStringTableToBuffer(strings) let buffer = new ArrayBuffer(0) let mainFunctionIndex: number = 0 // tslint:disable-next-line: no-big-function funcsInfo.forEach((funcInfo: IFuncInfo): void => { const currentFunctionAddress = funcInfo.ip = buffer.byteLength if (funcInfo.name === '@@main') { mainFunctionIndex = funcInfo.index! } let isAddressCodeByteChanged = true const DEFAULT_ADDRESS_LEN = 0 let codeAddress: number[] = [] let addressCandidates: { codeIndex: number, bufferIndex: number, addressByteLen: number }[] = [] let currentFuncBuffer: ArrayBuffer = new ArrayBuffer(0) const addressCodeByteMap: any = {} while(isAddressCodeByteChanged) { // console.log("////??/") isAddressCodeByteChanged = false currentFuncBuffer = funcInfo.bytecodes = new ArrayBuffer(0) codeAddress = [] addressCandidates = [] const appendBuffer = (buf: ArrayBuffer): void => { // buffer = concatBuffer(buffer, buf) currentFuncBuffer = funcInfo.bytecodes = concatBuffer(funcInfo.bytecodes!, buf) } funcInfo.codes.forEach((code: any, i): void => { const codeOffset = currentFunctionAddress + currentFuncBuffer.byteLength const addressByteLength: number = getByteLengthFromInt32(codeOffset) codeAddress.push(codeOffset) /* if byte length change should generate again */ if ((addressCodeByteMap[i] || DEFAULT_ADDRESS_LEN) !== addressByteLength){ isAddressCodeByteChanged = true addressCodeByteMap[i] = addressByteLength } /* append operator buffer */ const operator = code[0] appendBuffer(Uint8Array.from([operator]).buffer) /* loop operant */ code.forEach((o: { type: IOperatantType, value: any }, j: number): void => { if (j === 0) { return } if (o.type !== IOperatantType.ADDRESS) { const buf = createOperantBuffer(o.type, o.value) appendBuffer(buf) } else { const byteLength = addressCodeByteMap[o.value] || DEFAULT_ADDRESS_LEN const buf = createOperantBuffer(o.type, 0, byteLength) appendBuffer(buf) addressCandidates.push({ codeIndex: o.value, bufferIndex: currentFuncBuffer.byteLength - byteLength, addressByteLen: byteLength, }) } }) }) } addressCandidates.forEach(({ codeIndex, bufferIndex, addressByteLen }, i): void => { const address = codeAddress[codeIndex] const buf = new Uint8Array(Int32Array.from([address]).buffer) // console.log(i, '=====================================') // console.log('codeIndex -> ', codeIndex) // console.log('address -> ', address) // console.log('bufferIndex -> ', bufferIndex) // console.log('addressBytenLen -> ', addressByteLen) const functionBuffer = new Uint8Array(currentFuncBuffer) functionBuffer.set(buf.slice(0, addressByteLen), bufferIndex) }) // console.log(' current -----------------> ', new Uint8Array(currentFuncBuffer)[0]) buffer = concatBuffer(buffer, currentFuncBuffer) }) /** * Header: * * mainFunctionIndex: 4 * funcionTableBasicIndex: 4 * stringTableBasicIndex: 4 * globalsSize: 4 */ const FUNC_SIZE = 4 + 2 + 2 // ip + numArgs + localSize const funcionTableBasicIndex = 4 * 4 + buffer.byteLength const stringTableBasicIndex = funcionTableBasicIndex + FUNC_SIZE * funcsInfo.length const headerView = new Uint32Array(4) headerView[0] = mainFunctionIndex headerView[1] = funcionTableBasicIndex headerView[2] = stringTableBasicIndex headerView[3] = globalsSize buffer = concatBuffer(headerView.buffer, buffer) /** Function Table */ funcsInfo.forEach((funcInfo: IFuncInfo, i: number): void => { const ipBuf = new Uint32Array(1) const numArgsAndLocal = new Uint16Array(2) ipBuf[0] = funcInfo.ip! numArgsAndLocal[0] = funcInfo.numArgs numArgsAndLocal[1] = funcInfo.localSize const funcBuf = concatBuffer(ipBuf.buffer, numArgsAndLocal.buffer) buffer = concatBuffer(buffer, funcBuf) }) /** append string buffer */ buffer = concatBuffer(buffer, stringTable.buffer) return buffer } const parseStringTableToBuffer = (stringTable: string[]): { buffer: ArrayBuffer, indexes: { [x in number]: number }, } => { /** String Table */ let strBuf = new ArrayBuffer(0) const indexes: any = {} stringTable.forEach((str: string, i: number): void => { indexes[i] = strBuf.byteLength const lenBuf = new Uint32Array(1) lenBuf[0] = str.length strBuf = concatBuffer(strBuf, lenBuf.buffer) strBuf = concatBuffer(strBuf, stringToArrayBuffer(str)) }) return { buffer: strBuf, indexes, } } const parseFunction = (func: IParsedFunction): IFuncInfo => { const funcName = func.functionName const args = func.params const body = func.instructions const vars = body.filter((stat: string[]): boolean => stat[0] === 'REG') const globals = body .filter((stat: string[]): boolean => stat[0] === 'GLOBAL') .map((stat: string[]): string => stat[1]) const codes = body.filter((stat: string[]): boolean => stat[0] !== 'REG' && stat[0] !== 'GLOBAL') const symbols = new Map<string, any>() args.forEach((arg: string, i: number): void => { symbols.set(arg, -4 - i) }) let j = 0 vars.forEach((v: string[], i: number): void => { const reg = v[1] // if (reg.startsWith('@c')) { // symbols[reg] = -1 // } else { symbols.set(reg, j + 1) j++ // } }) if (funcName === '@@main') { codes.push(['EXIT']) } else if (codes.length === 0 || codes[codes.length - 1][0] !== 'RET') { codes.push(['RET']) } const labels: any = {} const codesWithoutLabel: string[][] = [] codes.forEach((code: string[]): void => { if (code[0] === 'LABEL') { labels[code[1]] = codesWithoutLabel.length } else { codesWithoutLabel.push(code) } }) // console.log('===>', funcName, codesWithoutLabel, labels) return { name: funcName, numArgs: args.length, symbols, codes: codesWithoutLabel, localSize: vars.length, globals, labels, } }
the_stack
import * as util from 'util'; import { CompletionItemKind, CancellationToken, Connection, CompletionItem, MarkupContent, MarkupKind } from 'vscode-languageserver/node'; import path from 'path'; import { signatures } from '@mongosh/shell-api'; import translator from '@mongosh/i18n'; import { Worker as WorkerThreads } from 'worker_threads'; import { CollectionItem } from '../types/collectionItemType'; import { ConnectionOptions } from '../types/connectionOptionsType'; import { ServerCommands } from './serverCommands'; import { ShellExecuteAllResult, PlaygroundExecuteParameters, ExportToLanguageMode, ExportToLanguageNamespace, PlaygroundTextAndSelection } from '../types/playgroundType'; import { Visitor } from './visitor'; export const languageServerWorkerFileName = 'languageServerWorker.js'; export type ShellCompletionItem = { [symbol: string]: CompletionItem[] | [] }; export default class MongoDBService { _connection: Connection; _connectionId?: string; _connectionString?: string; _connectionOptions?: ConnectionOptions; _cachedDatabases: CompletionItem[] | [] = []; _cachedFields: { [namespace: string]: CompletionItem[] } | {} = {}; _cachedCollections: { [database: string]: CollectionItem[] } | {} = {}; _cachedShellSymbols: ShellCompletionItem; _extensionPath?: string; _visitor: Visitor; constructor(connection: Connection) { this._connection = connection; this._cachedShellSymbols = this._getShellCompletionItems(); this._visitor = new Visitor(connection.console); } // ------ CONNECTION ------ // get connectionString(): string | undefined { return this._connectionString; } get connectionOptions(): ConnectionOptions | undefined { return this._connectionOptions; } setExtensionPath(extensionPath: string): void { if (!extensionPath) { this._connection.console.error('Set extensionPath error: extensionPath is undefined'); } else { this._extensionPath = extensionPath; } } async connectToServiceProvider(params: { connectionId: string; connectionString: string; connectionOptions: ConnectionOptions; }): Promise<boolean> { this._clearCurrentSessionConnection(); this._clearCurrentSessionFields(); this._clearCurrentSessionDatabases(); this._clearCurrentSessionCollections(); this._connectionId = params.connectionId; this._connectionString = params.connectionString; this._connectionOptions = params.connectionOptions; if (!this._connectionString) { return Promise.resolve(false); } try { this._getDatabasesCompletionItems(); return Promise.resolve(true); } catch (error) { this._connection.console.error( `MONGOSH connect error: ${util.inspect(error)}` ); return Promise.resolve(false); } } disconnectFromServiceProvider(): void { this._clearCurrentSessionConnection(); this._clearCurrentSessionFields(); this._clearCurrentSessionDatabases(); this._clearCurrentSessionCollections(); } // ------ EXECUTION ------ // executeAll( executionParameters: PlaygroundExecuteParameters, token: CancellationToken ): Promise<ShellExecuteAllResult | undefined> { this._clearCurrentSessionFields(); return new Promise((resolve) => { if (!this._extensionPath) { this._connection.console.error('MONGOSH execute all error: extensionPath is undefined'); return resolve(undefined); } if (this._connectionId !== executionParameters.connectionId) { this._connection.sendNotification( ServerCommands.SHOW_ERROR_MESSAGE, 'The playground\'s active connection does not match the extension\'s active connection. Please reconnect and try again.' ); return resolve(undefined); } try { // Use Node worker threads to run a playground to be able to cancel infinite loops. // // There is an issue with support for `.ts` files. // Trying to run a `.ts` file in a worker thread returns the error: // `The worker script extension must be “.js” or “.mjs”. Received “.ts”` // As a workaround require `.js` file from the out folder. // // TODO: After webpackifying the extension replace // the workaround with some similar 3rd-party plugin. const worker = new WorkerThreads( path.resolve(this._extensionPath, 'dist', languageServerWorkerFileName), { // The workerData parameter sends data to the created worker. workerData: { codeToEvaluate: executionParameters.codeToEvaluate, connectionString: this._connectionString, connectionOptions: this._connectionOptions } } ); this._connection.console.log( `MONGOSH execute all body: "${executionParameters.codeToEvaluate}"` ); // Evaluate runtime in the worker thread. worker.postMessage(ServerCommands.EXECUTE_ALL_FROM_PLAYGROUND); // Listen for results from the worker thread. worker.on('message', (response: [Error, ShellExecuteAllResult | undefined]) => { const [error, result] = response; if (error) { const printableError = error as { message: string }; this._connection.console.error( `MONGOSH execute all error: ${util.inspect(error)}` ); this._connection.sendNotification( ServerCommands.SHOW_ERROR_MESSAGE, printableError.message ); } void worker.terminate().then(() => { resolve(result); }); }); // Listen for cancellation request from the language server client. token.onCancellationRequested(async () => { this._connection.console.log('PLAYGROUND cancellation requested'); this._connection.sendNotification( ServerCommands.SHOW_INFO_MESSAGE, 'The running playground operation was canceled.' ); // If there is a situation that mongoClient is unresponsive, // try to close mongoClient after each runtime evaluation // and after the cancelation of the runtime // to make sure that all resources are free and can be used with a new request. // // (serviceProvider as any)?.mongoClient.close(false); // // The mongoClient.close method closes the underlying connector, // which in turn closes all open connections. // Once called, this mongodb instance can no longer be used. // // See: https://github.com/mongodb-js/vscode/pull/54 // Stop the worker and all JavaScript execution // in the worker thread as soon as possible. await worker.terminate(); return resolve(undefined); }); } catch (error) { this._connection.console.error( `MONGOSH execute all error: ${util.inspect(error)}` ); return resolve(undefined); } }); } // ------ GET DATA FOR COMPLETION ------ // _getDatabasesCompletionItems(): void { if (!this._extensionPath) { this._connection.console.error('MONGOSH get list databases error: extensionPath is undefined'); return; } try { const worker = new WorkerThreads( path.resolve(this._extensionPath, 'dist', languageServerWorkerFileName), { workerData: { connectionString: this._connectionString, connectionOptions: this._connectionOptions } } ); this._connection.console.log('MONGOSH get list databases...'); worker.postMessage(ServerCommands.GET_LIST_DATABASES); worker.on('message', (response: [Error, CompletionItem[] | []]) => { const [error, result] = response; if (error) { this._connection.console.error( `MONGOSH get list databases error: ${util.inspect(error)}` ); } void worker.terminate().then(() => { this._connection.console.log(`MONGOSH found ${result.length} databases`); this._updateCurrentSessionDatabases(result); }); }); } catch (error) { this._connection.console.error( `MONGOSH get list databases error: ${util.inspect(error)}` ); } } _getCollectionsCompletionItems(databaseName: string): Promise<boolean> { return new Promise((resolve) => { if (!this._extensionPath) { this._connection.console.log('MONGOSH get list collections error: extensionPath is undefined'); return resolve(false); } try { const worker = new WorkerThreads( path.resolve(this._extensionPath, 'dist', languageServerWorkerFileName), { workerData: { connectionString: this._connectionString, connectionOptions: this._connectionOptions, databaseName } } ); this._connection.console.log('MONGOSH get list collections...'); worker.postMessage(ServerCommands.GET_LIST_COLLECTIONS); worker.on('message', (response: [Error, CollectionItem[] | []]) => { const [error, result] = response; if (error) { this._connection.console.log( `MONGOSH get list collections error: ${util.inspect(error)}` ); } void worker.terminate().then(() => { this._connection.console.log( `MONGOSH found ${result.length} collections` ); this._updateCurrentSessionCollections(databaseName, result); return resolve(true); }); }); } catch (error) { this._connection.console.log( `MONGOSH get list collections error: ${util.inspect(error)}` ); return resolve(false); } }); } _getFieldsCompletionItems( databaseName: string, collectionName: string ): Promise<boolean> { return new Promise((resolve) => { if (!this._extensionPath) { this._connection.console.log('SCHEMA error: extensionPath is undefined'); return resolve(false); } try { const namespace = `${databaseName}.${collectionName}`; const worker = new WorkerThreads( path.resolve(this._extensionPath, 'dist', languageServerWorkerFileName), { workerData: { connectionString: this._connectionString, connectionOptions: this._connectionOptions, databaseName, collectionName } } ); this._connection.console.log(`SCHEMA for namespace: "${namespace}"`); worker.postMessage(ServerCommands.GET_FIELDS_FROM_SCHEMA); worker.on('message', (response: [Error, CompletionItem[] | []]) => { const [error, result] = response; if (error) { this._connection.console.log(`SCHEMA error: ${util.inspect(error)}`); } void worker.terminate().then(() => { this._connection.console.log(`SCHEMA found ${result.length} fields`); this._updateCurrentSessionFields(namespace, result); return resolve(true); }); }); } catch (error) { this._connection.console.log(`SCHEMA error: ${util.inspect(error)}`); return resolve(false); } }); } // Get shell API symbols/methods completion from mongosh. _getShellCompletionItems(): ShellCompletionItem { const shellSymbols = {}; Object.keys(signatures).map((symbol) => { shellSymbols[symbol] = Object.keys( signatures[symbol].attributes || {} ).map((item) => { const documentation = translator.translate(`shell-api.classes.${symbol}.help.attributes.${item}.description`) || ''; const link = translator.translate(`shell-api.classes.${symbol}.help.attributes.${item}.link`) || ''; const detail = translator.translate(`shell-api.classes.${symbol}.help.attributes.${item}.example`) || ''; const markdownDocumentation: MarkupContent = { kind: MarkupKind.Markdown, value: link ? `${documentation}\n\n[Read More](${link})` : documentation }; return { label: item, kind: CompletionItemKind.Method, documentation: markdownDocumentation, detail }; }); }); return shellSymbols; } // ------ COMPLETION ------ // // Check if a string is a valid property name. _isValidPropertyName(str: string): boolean { return /^(?![0-9])[a-zA-Z0-9$_]+$/.test(str); } _prepareCollectionsItems( textFromEditor: string, collections: Array<CollectionItem>, position: { line: number; character: number } ): CompletionItem[] { if (!collections) { return []; } this._connection.console.log(`collections: ${util.inspect(collections)}`); return collections.map((item) => { if (this._isValidPropertyName(item.name)) { return { label: item.name, kind: CompletionItemKind.Folder }; } // Convert invalid property names to array-like format const filterText = textFromEditor.split('\n')[position.line]; return { label: item.name, kind: CompletionItemKind.Folder, // Find the line with invalid property name filterText: [ filterText.slice(0, position.character), `.${item.name}`, filterText.slice(position.character, filterText.length) ].join(''), textEdit: { range: { start: { line: position.line, character: 0 }, end: { line: position.line, character: filterText.length } }, // Replace with array-like format newText: [ filterText.slice(0, position.character - 1), `['${item.name}']`, filterText.slice(position.character, filterText.length) ].join('') } }; }); } getExportToLanguageMode(params: PlaygroundTextAndSelection): ExportToLanguageMode { const state = this._visitor.parseAST(params); this._connection.console.log(`EXPORT TO LANGUAGE state: ${util.inspect(state)}`); if (state.isArray) { return ExportToLanguageMode.AGGREGATION; } if (state.isObject) { return ExportToLanguageMode.QUERY; } return ExportToLanguageMode.OTHER; } getNamespaceForSelection(params: PlaygroundTextAndSelection): ExportToLanguageNamespace { try { const state = this._visitor.parseAST(params); return { databaseName: state.databaseName, collectionName: state.collectionName }; } catch (error) { this._connection.console.error( `Get namespace for selection error: ${util.inspect(error)}` ); return { databaseName: null, collectionName: null }; } } // eslint-disable-next-line complexity async provideCompletionItems( textFromEditor: string, position: { line: number, character: number } ): Promise<CompletionItem[]> { // eslint-disable-next-line complexity this._connection.console.log( `LS text from editor: ${util.inspect(textFromEditor)}` ); this._connection.console.log( `LS current symbol position: ${util.inspect(position)}` ); const state = this._visitor.parseASTWithPlaceholder(textFromEditor, position); this._connection.console.log( `VISITOR completion state: ${util.inspect(state)}` ); if (this.connectionString && state.databaseName && !this._cachedCollections[state.databaseName]) { await this._getCollectionsCompletionItems(state.databaseName); } if (this.connectionString && state.databaseName && state.collectionName) { const namespace = `${state.databaseName}.${state.collectionName}`; if (!this._cachedFields[namespace]) { await this._getFieldsCompletionItems( state.databaseName, state.collectionName ); } if (state.isObjectKey) { this._connection.console.log('VISITOR found field names completion'); return this._cachedFields[namespace] as CompletionItem[]; } } if (state.isShellMethod) { this._connection.console.log( 'VISITOR found shell collection methods completion' ); return this._cachedShellSymbols.Collection; } if (state.isAggregationCursor) { this._connection.console.log( 'VISITOR found shell aggregation cursor methods completion' ); return this._cachedShellSymbols.AggregationCursor; } if (state.isFindCursor) { this._connection.console.log( 'VISITOR found shell cursor methods completion' ); return this._cachedShellSymbols.Cursor; } if (state.isDbCallExpression) { let dbCompletions: CompletionItem[] = [...this._cachedShellSymbols.Database]; if (state.databaseName) { this._connection.console.log( 'VISITOR found shell db methods and collection names completion' ); const collectionCompletions = this._prepareCollectionsItems( textFromEditor, this._cachedCollections[state.databaseName], position ); dbCompletions = dbCompletions.concat(collectionCompletions); } else { this._connection.console.log( 'VISITOR found shell db methods completion' ); } return dbCompletions; } if (state.isCollectionName && state.databaseName) { this._connection.console.log('VISITOR found collection names completion'); const collectionCompletions = this._prepareCollectionsItems( textFromEditor, this._cachedCollections[state.databaseName], position ); return collectionCompletions; } if (state.isUseCallExpression) { this._connection.console.log('VISITOR found database names completion'); return this._cachedDatabases; } this._connection.console.log('VISITOR no completions'); return []; } // ------ CURRENT SESSION ------ // _clearCurrentSessionFields(): void { this._cachedFields = {}; } _updateCurrentSessionFields(namespace: string, fields: CompletionItem[]): void { if (namespace) { this._cachedFields[namespace] = fields ? fields : []; } } _clearCurrentSessionDatabases(): void { this._cachedDatabases = []; } _updateCurrentSessionDatabases(databases: CompletionItem[]): void { this._cachedDatabases = databases ? databases : []; } _clearCurrentSessionCollections(): void { this._cachedCollections = {}; } _updateCurrentSessionCollections(database: string, collections: CollectionItem[]): void { if (database) { this._cachedCollections[database] = collections ? collections : []; } } _clearCurrentSessionConnection(): void { this._connectionString = undefined; this._connectionOptions = undefined; } }
the_stack
'use strict'; /*jshint loopfunc: true */ import * as utils from './utils'; const async = require('async'); const { debug, info, warn, error } = require('portal-env').Logger('kong-adapter:sync'); import * as wicked from 'wicked-sdk'; import { kong } from './kong'; import { portal } from './portal'; import { ErrorCallback, KongApiConfig } from 'wicked-sdk'; import { ApiDescriptionCollection, KongApiConfigCollection, ApiDescription, UpdateApiItem, AddApiItem, DeleteApiItem, ApiTodos, PluginTodos, AddPluginItem, UpdatePluginItem, DeletePluginItem, ConsumerInfo, UpdateConsumerItem, DeleteConsumerItem, AddConsumerItem, ConsumerTodos, ConsumerApiPluginTodos, ConsumerApiPluginAddItem, ConsumerApiPluginPatchItem, ConsumerApiPluginDeleteItem } from './types'; const MAX_ASYNC_CALLS = 10; // ========= INTERFACE FUNCTIONS ======== export const sync = { syncApis: function (done: ErrorCallback) { debug('syncApis()'); async.parallel({ portalApis: function (callback) { portal.getPortalApis(callback); }, kongApis: function (callback) { kong.getKongApis(callback); } }, function (err, results) { if (err) return done(err); const portalApis = results.portalApis as ApiDescriptionCollection; const kongApis = results.kongApis as KongApiConfigCollection; const todoLists = assembleApiTodoLists(portalApis, kongApis); debug('Infos on sync APIs todo list:'); debug(' add items: ' + todoLists.addList.length); debug(' update items: ' + todoLists.updateList.length); debug(' delete items: ' + todoLists.deleteList.length); //debug(utils.getText(todoLists)); async.series({ updateApis: function (callback) { // Will call syncPlugins kong.updateKongApis(sync, todoLists.updateList, callback); }, deleteApis: function (callback) { kong.deleteKongApis(todoLists.deleteList, callback); }, addApis: function (callback) { kong.addKongApis(todoLists.addList, callback); } }, function (err) { if (err) return done(err); debug("syncApis() finished."); return done(null); }); }); }, syncPlugins: function (portalApi: ApiDescription, kongApi: KongApiConfig, callback: ErrorCallback): void { debug('syncPlugins()'); const todoLists = assemblePluginTodoLists(portalApi, kongApi); //debug(utils.getText(todoLists)); debug('Infos on sync API Plugins todo list:'); debug(' add items: ' + todoLists.addList.length); debug(' update items: ' + todoLists.updateList.length); debug(' delete items: ' + todoLists.deleteList.length); /* debug('portalApi'); debug(portalApi); debug('kongApi'); debug(kongApi); */ async.series({ addPlugins: function (callback) { kong.addKongPlugins(todoLists.addList, callback); }, updatePlugins: function (callback) { kong.updateKongPlugins(todoLists.updateList, callback); }, deletePlugins: function (callback) { kong.deleteKongPlugins(todoLists.deleteList, callback); } }, function (err) { if (err) return callback(err); debug("sync.syncPlugins() done."); return callback(null); }); }, // =========== CONSUMERS ============ syncAllConsumers: function (callback) { debug('syncAllConsumers()'); async.parallel({ portalConsumers: callback => portal.getAllPortalConsumers(callback), kongConsumers: callback => kong.getAllKongConsumers(callback) }, function (err, result) { if (err) return callback(err); info(`Syncing ${result.portalConsumers.length} portal consumers with ${result.kongConsumers.length} Kong consumers.`); syncConsumers(result.portalConsumers, result.kongConsumers, callback); }); }, syncAppConsumers: function (appId, callback) { debug('syncAppConsumers(): ' + appId); async.waterfall([ callback => portal.getAppConsumers(appId, callback), // One app may result in multiple consumers (one per subscription) (appConsumers, callback) => syncAppConsumers(appConsumers, callback) ], function (err) { if (err) return callback(err); // We're fine. debug('syncAppConsumers() succeeded for app ' + appId); callback(null); }); }, /* If we delete an application, we also need to know which subscriptions it has, as the consumers in kong are not per application, but rather per subscription. I.e., we cannot deduce which Kong consumers belong to a registered application in the API Portal. See below what needs to be in the subscriptionList. */ deleteAppConsumers: function (appId, subscriptionList, callback) { debug('deleteAppConsumers(): ' + appId); async.mapLimit(subscriptionList, MAX_ASYNC_CALLS, function (subsInfo, callback) { sync.deleteAppSubscriptionConsumer(subsInfo, callback); }, function (err, results) { if (err) return callback(err); debug('deleteAppConsumers() for app ' + appId + ' succeeded.'); callback(null); }); }, /* At least the following is needed subsInfo: { application: <...>, api: <...>, auth: <auth method> (one of key-auth, oauth2) plan: <...>, // optional userId: <...> // optional } */ deleteAppSubscriptionConsumer: function (subsInfo, callback) { debug('deleteAppSubscriptionConsumer() appId: ' + subsInfo.application + ', api: ' + subsInfo.api); kong.deleteConsumerWithUsername(utils.makeUserName(subsInfo.application, subsInfo.api), callback); }, syncConsumerApiPlugins: function (portalConsumer, kongConsumer, done) { debug('syncConsumerApiPlugins()'); const todoLists = assembleConsumerApiPluginsTodoLists(portalConsumer, kongConsumer); async.series([ function (callback) { kong.addKongConsumerApiPlugins(todoLists.addList, kongConsumer.consumer.id, callback); }, function (callback) { kong.patchKongConsumerApiPlugins(todoLists.patchList, callback); }, function (callback) { kong.deleteKongConsumerApiPlugins(todoLists.deleteList, callback); } ], function (err) { if (err) return done(err); debug('syncConsumerApiPlugins() finished.'); return done(null); }); }, wipeAllConsumers: function (done) { debug('wipeAllConsumers()'); kong.wipeAllConsumers(done); }, addPrometheusPlugin: function (callback) { debug('addPrometheusPlugin()'); utils.kongGetPluginsByName('prometheus', function (err, plugins) { if (err) return callback(err); const globalPlugins = plugins.data.filter(p => !p.api_id && !p.route_id && !p.service_id); if (globalPlugins.length === 0) { info('Adding prometheus global plugin.'); return utils.kongPostGlobalPlugin({ name: 'prometheus', enabled: true }, callback); } else if (globalPlugins.length === 1) { info('Detected global prometheus plugin. Leaving as is.'); return callback(null); } error(JSON.stringify(globalPlugins, null, 2)); return callback(new Error('Detected multiple global prometheus plugins.')); }); }, deleteLegacyApis: function (callback) { debug('deleteLegacyApis()'); utils.kongGetLegacyApis(function (err, legacyApis) { if (err) return callback(err); async.eachSeries(legacyApis.data, (legacyApi, callback) => { info(`Deleting Legacy Kong API ${legacyApi.name}.`); utils.kongDeleteLegacyApi(legacyApi.name, callback); }, callback); }); } }; function syncAppConsumers(portalConsumers: ConsumerInfo[], callback: ErrorCallback): void { if (portalConsumers.length === 0) { debug('syncAppConsumers() - nothing to do (empty consumer list).'); setTimeout(callback, 0); return; } debug('syncAppConsumers()'); // Get the corresponding Kong consumers kong.getKongConsumers(portalConsumers, function (err, resultConsumers) { if (err) return callback(err); const kongConsumers = [] as ConsumerInfo[]; for (let i = 0; i < resultConsumers.length; ++i) { if (resultConsumers[i]) kongConsumers.push(resultConsumers[i]); } syncConsumers(portalConsumers, kongConsumers, callback); }); } function syncConsumers(portalConsumers: ConsumerInfo[], kongConsumers: ConsumerInfo[], callback: ErrorCallback) { if (portalConsumers.length === 0 && kongConsumers.length === 0) { debug('syncConsumers() - nothing to do (empty consumer lists).'); setTimeout(callback, 0); return; } debug('syncConsumers()'); debug('syncConsumers(): Creating Todo lists.'); const todoLists = assembleConsumerTodoLists(portalConsumers, kongConsumers); debug('Infos on sync consumers todo list:'); debug(' add items: ' + todoLists.addList.length); debug(' update items: ' + todoLists.updateList.length); debug(' delete items: ' + todoLists.deleteList.length); async.series({ addConsumers: callback => kong.addKongConsumers(todoLists.addList, callback), updateConsumers: callback => kong.updateKongConsumers(sync, todoLists.updateList, callback), // Will call syncConsumerApiPlugins deleteConsumers: callback => kong.deleteKongConsumers(todoLists.deleteList, callback) }, function (err, results) { if (err) return callback(err); info('syncConsumers() done.'); return callback(null); }); } // ========= INTERNALS =========== function assembleApiTodoLists(portalApis: ApiDescriptionCollection, kongApis: KongApiConfigCollection): ApiTodos { debug('assembleApiTodoLists()'); const updateList: UpdateApiItem[] = []; const addList: AddApiItem[] = []; const deleteList: DeleteApiItem[] = []; const handledKongApis = {}; for (let i = 0; i < portalApis.apis.length; ++i) { let portalApi = portalApis.apis[i]; let kongApi = kongApis.apis.find(function (thisApi) { return thisApi.api.name == portalApi.id; }); if (kongApi) { // Found in both Portal and Kong, check for updates updateList.push({ portalApi: portalApi, kongApi: kongApi }); handledKongApis[kongApi.api.name] = true; } else { debug('Did not find API ' + portalApi.id + ' in Kong, will add.'); // Api not known in Kong, we need to add this addList.push({ portalApi: portalApi }); } } // Now do the mop up, clean up APIs in Kong but not in the Portal; // these we want to delete. for (let i = 0; i < kongApis.apis.length; ++i) { let kongApi = kongApis.apis[i]; if (!handledKongApis[kongApi.api.name]) { debug('API ' + kongApi.api.name + ' not found in portal definition, will delete.'); deleteList.push({ kongApi: kongApi }); } } return { addList: addList, updateList: updateList, deleteList: deleteList }; } function shouldIgnore(name) { const ignoreList = wicked.getKongAdapterIgnoreList(); if (ignoreList.length === 0) { return false; } if (!name) { return false; } for (let i = 0; i < ignoreList.length; ++i) { if (ignoreList[i] === name) { return true; } } return false; } function assemblePluginTodoLists(portalApi: ApiDescription, kongApi: KongApiConfig): PluginTodos { debug('assemblePluginTodoLists()'); const addList = [] as AddPluginItem[]; const updateList = [] as UpdatePluginItem[]; const deleteList = [] as DeletePluginItem[]; const handledKongPlugins = {}; for (let i = 0; i < portalApi.config.plugins.length; ++i) { let portalPlugin = portalApi.config.plugins[i]; let kongPluginIndex = utils.getIndexBy(kongApi.plugins, function (plugin) { return plugin.name == portalPlugin.name; }); if (kongPluginIndex < 0) { addList.push({ portalApi: portalApi, portalPlugin: portalPlugin, kongApi: kongApi }); } else { let kongPlugin = kongApi.plugins[kongPluginIndex]; if (!utils.matchObjects(portalPlugin, kongPlugin) && !shouldIgnore(kongPlugin.name)) { updateList.push({ portalApi: portalApi, portalPlugin: portalPlugin, kongApi: kongApi, kongPlugin: kongPlugin }); } // Else: Matches, all is good handledKongPlugins[kongPlugin.name] = true; } } // Mop up needed? for (let i = 0; i < kongApi.plugins.length; ++i) { let kongPlugin = kongApi.plugins[i]; if (!handledKongPlugins[kongPlugin.name] && !shouldIgnore(kongPlugin.name)) { deleteList.push({ kongApi: kongApi, kongPlugin: kongPlugin }); } } return { addList: addList, updateList: updateList, deleteList: deleteList }; } function assembleConsumerTodoLists(portalConsumers: ConsumerInfo[], kongConsumers: ConsumerInfo[]): ConsumerTodos { debug('assembleConsumerTodoLists()'); const addList = [] as AddConsumerItem[]; const updateList = [] as UpdateConsumerItem[]; const deleteList = [] as DeleteConsumerItem[]; const handledKongConsumers = {}; const kongConsumerMap = new Map<string, ConsumerInfo>(); // Speed up consumer checking to O(n) instead of O(n^2) for (let i = 0; i < kongConsumers.length; ++i) { const c = kongConsumers[i]; kongConsumerMap.set(c.consumer.username, c); } for (let i = 0; i < portalConsumers.length; ++i) { let portalConsumer = portalConsumers[i]; let kongConsumer; const u = portalConsumer.consumer.username; if (kongConsumerMap.has(u)) kongConsumer = kongConsumerMap.get(u); if (!kongConsumer) { debug('Username "' + portalConsumer.consumer.username + '" in portal, but not in Kong, add needed.'); // Not found addList.push({ portalConsumer: portalConsumer }); continue; } // We have the consumer in both the Portal and Kong debug('Found username "' + kongConsumer.consumer.username + '" in portal and Kong, check for update.'); updateList.push({ portalConsumer: portalConsumer, kongConsumer: kongConsumer }); handledKongConsumers[kongConsumer.consumer.username] = true; } // Mop up? for (let i = 0; i < kongConsumers.length; ++i) { let kongConsumer = kongConsumers[i]; if (!handledKongConsumers[kongConsumer.consumer.username]) { debug('Username "' + kongConsumer.consumer.username + "' found in Kong, but not in portal, delete needed."); // Superfluous consumer; we control them deleteList.push({ kongConsumer: kongConsumer }); } } return { addList: addList, updateList: updateList, deleteList: deleteList }; } function assembleConsumerApiPluginsTodoLists(portalConsumer: ConsumerInfo, kongConsumer: ConsumerInfo): ConsumerApiPluginTodos { debug('assembleConsumerApiPluginsTodoLists()'); const addList = [] as ConsumerApiPluginAddItem[]; const patchList = [] as ConsumerApiPluginPatchItem[]; const deleteList = [] as ConsumerApiPluginDeleteItem[]; const handledPlugins = {}; for (let i = 0; i < portalConsumer.apiPlugins.length; ++i) { let portalApiPlugin = portalConsumer.apiPlugins[i]; let kongApiPlugin = kongConsumer.apiPlugins.find(function (p) { return p.name == portalApiPlugin.name; }); if (!kongApiPlugin) { // not found, add it addList.push({ portalConsumer: portalConsumer, portalApiPlugin: portalApiPlugin }); continue; } if (kongApiPlugin && !utils.matchObjects(portalApiPlugin, kongApiPlugin) && !shouldIgnore(kongApiPlugin.name)) { patchList.push({ portalConsumer: portalConsumer, portalApiPlugin: portalApiPlugin, kongConsumer: kongConsumer, kongApiPlugin: kongApiPlugin }); } handledPlugins[portalApiPlugin.name] = true; } // Mop up for (let i = 0; i < kongConsumer.apiPlugins.length; ++i) { let kongApiPlugin = kongConsumer.apiPlugins[i]; if (!handledPlugins[kongApiPlugin.name] && !shouldIgnore(kongApiPlugin.name)) { deleteList.push({ kongConsumer: kongConsumer, kongApiPlugin: kongApiPlugin }); } } return { addList: addList, patchList: patchList, deleteList: deleteList }; }
the_stack
import { Constants, Maths, Models, Types } from '@tosios/common'; import { Container, Graphics, Sprite, Texture, utils } from 'pixi.js'; import { Effects, PlayerLivesSprite, TextSprite } from '../sprites'; import { PlayerTextures, WeaponTextures } from '../assets/images'; import { SmokeConfig, SmokeTexture } from '../assets/particles'; import { BaseEntity } from '.'; import { Emitter } from 'pixi-particles'; const NAME_OFFSET = 4; const LIVES_OFFSET = 10; const HURT_COLOR = 0xff0000; const HEAL_COLOR = 0x00ff00; const BULLET_DELAY_FACTOR = 1.1; // Add 10% to delay as server may lag behind sometimes (rarely) const SMOKE_DELAY = 500; const DEAD_ALPHA = 0.2; const ZINDEXES = { SHADOW: 0, WEAPON_BACK: 1, PLAYER: 2, WEAPON_FRONT: 3, INFOS: 4, }; export type PlayerDirection = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; export class Player extends BaseEntity { private _playerId: string = ''; private _name: string = ''; private _lives: number = 0; private _maxLives: number = 0; public team?: Types.Teams; private _color: string = '#FFFFFF'; private _kills: number = 0; private _rotation: number = 0; // Computed private _isGhost: boolean = false; private _direction: PlayerDirection = 'bottom-right'; private _lastShootAt: number = 0; private _toX: number = 0; private _toY: number = 0; private _weaponSprite: Sprite; private _nameTextSprite: TextSprite; private _livesSprite: PlayerLivesSprite; public ack?: number; private _shadow: Graphics; private _particlesContainer?: Container; private _lastSmokeAt: number = 0; // Init constructor(player: Models.PlayerJSON, isGhost: boolean, particlesContainer?: Container) { super({ x: player.x, y: player.y, radius: player.radius, textures: getTexture(player.lives), zIndex: ZINDEXES.PLAYER, }); // Weapon this._weaponSprite = new Sprite(WeaponTextures.staff); this._weaponSprite.anchor.set(0, 0.5); this._weaponSprite.position.set(player.radius, player.radius); this._weaponSprite.zIndex = ZINDEXES.WEAPON_BACK; this.container.addChild(this._weaponSprite); // Name this._nameTextSprite = new TextSprite(player.name, 8, 0.5, 1); this._nameTextSprite.position.set(player.radius, -NAME_OFFSET); this._nameTextSprite.zIndex = ZINDEXES.INFOS; this.container.addChild(this._nameTextSprite); // Lives this._livesSprite = new PlayerLivesSprite(0.5, 1, 8, player.maxLives, player.lives); this._livesSprite.position.set( player.radius, this._nameTextSprite.y - this._nameTextSprite.height - LIVES_OFFSET, ); this._livesSprite.anchorX = 0.5; this._livesSprite.zIndex = ZINDEXES.INFOS; this.container.addChild(this._livesSprite); // Shadow this._shadow = new Graphics(); this._shadow.zIndex = ZINDEXES.SHADOW; this._shadow.pivot.set(0.5); this._shadow.beginFill(0x000000, 0.3); this._shadow.drawEllipse(player.radius, player.radius * 2, player.radius * 0.7, player.radius * 0.3); this._shadow.endFill(); this.container.addChild(this._shadow); // Sort rendering order this.container.sortChildren(); // Reference to the particles container this._particlesContainer = particlesContainer; // Player this.playerId = player.playerId; this.toX = player.x; this.toY = player.y; this.rotation = player.rotation; this.name = player.name; this.color = player.color; this.lives = player.lives; this.maxLives = player.maxLives; this.kills = player.kills; this.team = player.team; this.isGhost = isGhost; // Ghost if (isGhost) { this.visible = Constants.DEBUG; } } // Methods move(dirX: number, dirY: number, speed: number) { const magnitude = Maths.normalize2D(dirX, dirY); const speedX = Math.round(Maths.round2Digits(dirX * (speed / magnitude))); const speedY = Math.round(Maths.round2Digits(dirY * (speed / magnitude))); this.x += speedX; this.y += speedY; } hurt() { Effects.flash(this.sprite, HURT_COLOR, utils.string2hex(this.color)); } heal() { Effects.flash(this.sprite, HEAL_COLOR, utils.string2hex(this.color)); } updateTextures() { const isAlive = this.lives > 0; // Player this.sprite.alpha = isAlive ? 1 : DEAD_ALPHA; this.sprite.textures = isAlive ? PlayerTextures.playerIdleTextures : PlayerTextures.playerDeadTextures; this.sprite.anchor.set(0.5); this.sprite.width = this.body.width; this.sprite.height = this.body.height; this.sprite.play(); // Weapon this._weaponSprite.visible = this.isGhost ? isAlive && Constants.DEBUG : isAlive; // Name this._nameTextSprite.alpha = isAlive ? 1 : DEAD_ALPHA; // Lives this._livesSprite.alpha = isAlive ? 1 : DEAD_ALPHA; // Shadow this._shadow.alpha = isAlive ? 1 : DEAD_ALPHA; } canShoot(): boolean { if (!this.isAlive) { return false; } const now: number = Date.now(); if (now - this.lastShootAt < Constants.BULLET_RATE * BULLET_DELAY_FACTOR) { return false; } this.lastShootAt = now; return true; } canBulletHurt(otherPlayerId: string, team?: string): boolean { if (!this.isAlive) { return false; } if (this.isGhost) { return false; } if (this.playerId === otherPlayerId) { return false; } if (!!team && team === this.team) { return false; } return true; } spawnSmoke() { if (!this._particlesContainer) { return; } if (!this.isAlive) { return; } const timeSinceLastSmoke = Date.now() - this._lastSmokeAt; if (timeSinceLastSmoke < SMOKE_DELAY) { return; } new Emitter(this._particlesContainer, [SmokeTexture], { ...SmokeConfig, pos: { x: this.body.x, y: this.body.y + this.body.radius / 2, }, }).playOnceAndDestroy(); this._lastSmokeAt = Date.now(); } // Setters set x(x: number) { this.container.x = x; this.body.x = x; this.spawnSmoke(); } set y(y: number) { this.container.y = y; this.body.y = y; this.spawnSmoke(); } set toX(toX: number) { this._toX = toX; } set toY(toY: number) { this._toY = toY; } set playerId(playerId: string) { this._playerId = playerId; } set name(name: string) { this._name = name; this._nameTextSprite.text = name; } set lives(lives: number) { if (this._lives === lives) { return; } if (lives > this._lives) { this.heal(); } this._lives = lives; this._livesSprite.lives = this._lives; this.updateTextures(); } set maxLives(maxLives: number) { if (this._maxLives === maxLives) { return; } this._maxLives = maxLives; this._livesSprite.maxLives = this._maxLives; this.updateTextures(); } set color(color: string) { if (this._color === color) { return; } this._color = color; // FIXME: Tints seem not to be apliable directly on a AnimatedSprite. // Therefore, adding a delay fixes the problem for now. setTimeout(() => { this.sprite.tint = utils.string2hex(color); this._weaponSprite.tint = utils.string2hex(color); }, 300); } set kills(kills: number) { if (this._kills === kills) { return; } this._kills = kills; } set rotation(rotation: number) { this._direction = getDirection(rotation); switch (this._direction) { case 'top-left': this.sprite.scale.x = -2; this._weaponSprite.zIndex = ZINDEXES.WEAPON_BACK; break; case 'top-right': this.sprite.scale.x = 2; this._weaponSprite.zIndex = ZINDEXES.WEAPON_BACK; break; case 'bottom-left': this.sprite.scale.x = -2; this._weaponSprite.zIndex = ZINDEXES.WEAPON_FRONT; break; case 'bottom-right': this.sprite.scale.x = 2; this._weaponSprite.zIndex = ZINDEXES.WEAPON_FRONT; break; default: break; } this._rotation = rotation; this._weaponSprite.rotation = rotation; this.container.sortChildren(); } set isGhost(isGhost: boolean) { this._isGhost = isGhost; } set lastShootAt(lastShootAt: number) { this._lastShootAt = lastShootAt; } // Getters get x(): number { return this.body.x; } get y(): number { return this.body.y; } get toX(): number { return this._toX; } get toY(): number { return this._toY; } get playerId() { return this._playerId; } get name() { return this._name; } get lives() { return this._lives; } get maxLives() { return this._maxLives; } get color() { return this._color; } get kills() { return this._kills; } get rotation() { return this._rotation; } get isGhost() { return this._isGhost; } get lastShootAt() { return this._lastShootAt; } get isAlive() { return this._lives > 0; } } /** * Return a texture depending on the number of lives. */ const getTexture = (lives: number): Texture[] => { return lives > 0 ? PlayerTextures.playerIdleTextures : PlayerTextures.playerDeadTextures; }; /** * Get a direction given a rotation. */ function getDirection(rotation: number): PlayerDirection { const top = -(Math.PI / 2); const right = 0; const bottom = Math.PI / 2; // Top if (rotation < right) { if (rotation > top) { return 'top-right'; } return 'top-left'; } // Bottom if (rotation < bottom) { return 'bottom-right'; } return 'bottom-left'; }
the_stack
import { getMemoryStore } from "@connext/store"; import { Address, EventNames, IStoreService, MethodNames, MethodParams, ProtocolNames, StateChannelJSON, } from "@connext/types"; import { deBigNumberifyJson, ChannelSigner, bigNumberifyJson } from "@connext/utils"; import { utils } from "ethers"; import { EventEmitter } from "events"; import { env } from "../setup"; import { CFCore } from "../../cfCore"; import { constructInstallRpc, constructTakeActionRpc, constructUninstallRpc, createChannel, getContractAddresses, installApp, makeAndSendProposeCall, makeInstallCall, makeProposeCall, uninstallApp, } from "../utils"; import { MemoryMessagingServiceWithLimits } from "../services/memory-messaging-service-limits"; import { A_PRIVATE_KEY, B_PRIVATE_KEY } from "../test-constants.jest"; import { MemoryLockService } from "../services"; import { Logger } from "../logger"; import { validAction } from "../tic-tac-toe"; import { expect } from "../assertions"; import { StateChannel } from "../../models"; const { isHexString } = utils; describe("Sync", () => { let multisigAddress: string; let nodeA: CFCore; let nodeB: CFCore; let storeServiceA: IStoreService; let storeServiceB: IStoreService; let sharedEventEmitter: EventEmitter; let ethUrl: string; let lockService: MemoryLockService; let channelSignerA: ChannelSigner; let channelSignerB: ChannelSigner; let expectedChannel: StateChannelJSON | undefined; let messagingServiceA: MemoryMessagingServiceWithLimits; let messagingServiceB: MemoryMessagingServiceWithLimits; let TicTacToeApp: Address; const log = new Logger("SyncTest", env.logLevel, true); afterEach(async () => { // cleanup sharedEventEmitter.removeAllListeners(); }); beforeEach(async () => { // test global fixtures sharedEventEmitter = new EventEmitter(); ethUrl = global["wallet"]["provider"].connection.url; TicTacToeApp = getContractAddresses().TicTacToeApp; log.info(`TicTacToeApp: ${TicTacToeApp}`); lockService = new MemoryLockService(); // create nodeA values channelSignerA = new ChannelSigner(A_PRIVATE_KEY, ethUrl); storeServiceA = getMemoryStore({ prefix: channelSignerA.publicIdentifier }); await storeServiceA.init(); // create nodeB values messagingServiceB = new MemoryMessagingServiceWithLimits( sharedEventEmitter, undefined, undefined, undefined, "NodeB", ); channelSignerB = new ChannelSigner(B_PRIVATE_KEY, ethUrl); storeServiceB = getMemoryStore({ prefix: channelSignerB.publicIdentifier }); await storeServiceB.init(); nodeB = await CFCore.create( messagingServiceB, storeServiceB, global["networks"], channelSignerB, lockService, 0, new Logger("CreateClient", env.logLevel, true, "B-initial"), ); }); describe("Sync::propose", () => { let identityHash: string; beforeEach(async () => { // propose-specific setup messagingServiceA = new MemoryMessagingServiceWithLimits(sharedEventEmitter, 0, "propose"); nodeA = await CFCore.create( messagingServiceA, storeServiceA, global["networks"], channelSignerA, lockService, 0, new Logger("CreateClient", env.logLevel, true, "A-initial"), ); // create channel multisigAddress = await createChannel(nodeA, nodeB); // load stores with proposal const rpc = makeProposeCall(nodeA, TicTacToeApp, multisigAddress); await new Promise(async (res) => { nodeB.once(EventNames.SYNC_FAILED_EVENT, res); try { await nodeB.rpcRouter.dispatch({ ...rpc, parameters: deBigNumberifyJson(rpc.parameters), }); } catch (e) { log.info(`Caught error sending rpc: ${e.message}`); } }); // get expected channel from nodeB expect(isHexString(multisigAddress)).to.eq(true); expectedChannel = await storeServiceA.getStateChannel(multisigAddress); identityHash = expectedChannel!.proposedAppInstances[0][0]; const unsynced = await storeServiceB.getStateChannel(multisigAddress); expect(expectedChannel).to.be.ok; expect(expectedChannel!.proposedAppInstances.length).to.eq(1); expect(unsynced?.proposedAppInstances.length).to.eq(0); }); it("sync protocol responder is missing a proposal held by the protocol initiator, sync on startup", async () => { const newNodeA = await CFCore.create( new MemoryMessagingServiceWithLimits(sharedEventEmitter), storeServiceA, global["networks"], channelSignerA, lockService, 0, new Logger("CreateClient", env.logLevel, true, "A-Recreated"), false, ); const syncedChannel = await storeServiceA.getStateChannel(multisigAddress); await (newNodeA as CFCore).rpcRouter.dispatch( constructInstallRpc(identityHash, multisigAddress), ); expect(syncedChannel).to.containSubset(expectedChannel!); const newAppInstanceA = await storeServiceA.getAppInstance(identityHash); const newAppInstanceB = await storeServiceB.getAppInstance(identityHash); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newAppInstanceA!).to.containSubset(newAppInstanceB!); expect(newAppInstanceA!.identityHash).to.eq(identityHash); expect(newAppInstanceA!.appSeqNo).to.eq(2); expect(newAppInstanceA!.latestVersionNumber).to.eq(1); expect(newChannelA!.freeBalanceAppInstance!.latestVersionNumber).to.eq(2); expect(newChannelA!.monotonicNumProposedApps).to.eq(2); expect(newChannelA!.appInstances.length).to.eq(1); }); it("sync protocol initiator is missing a proposal held by the protocol responder, sync on startup", async () => { messagingServiceA.clearLimits(); await messagingServiceB.disconnect(); const [eventData, newNodeB] = await Promise.all([ new Promise(async (resolve, reject) => { nodeA.on(EventNames.SYNC, (data) => resolve(data)); nodeA.on(EventNames.SYNC_FAILED_EVENT, (msg) => reject(`Sync failed. ${msg.data.error}`)); }), CFCore.create( new MemoryMessagingServiceWithLimits(sharedEventEmitter), storeServiceB, global["networks"], channelSignerB, lockService, 0, new Logger("CreateClient", env.logLevel, true, "B-recreated"), ), ]); const syncedChannel = await storeServiceA.getStateChannel(multisigAddress); expect(bigNumberifyJson(eventData)).to.deep.include({ from: nodeB.publicIdentifier, type: EventNames.SYNC, data: { syncedChannel: bigNumberifyJson(expectedChannel) }, }); expect(syncedChannel).to.containSubset(expectedChannel!); await (newNodeB as CFCore).rpcRouter.dispatch( constructInstallRpc(identityHash, multisigAddress), ); const newAppInstanceA = await storeServiceA.getAppInstance(identityHash); const newAppInstanceB = await storeServiceB.getAppInstance(identityHash); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newAppInstanceA!).to.containSubset(newAppInstanceB!); expect(newAppInstanceB!.identityHash).to.eq(identityHash); expect(newAppInstanceB!.appSeqNo).to.eq(2); expect(newAppInstanceB!.latestVersionNumber).to.eq(1); expect(newChannelB!.freeBalanceAppInstance!.latestVersionNumber).to.eq(2); expect(newChannelB!.monotonicNumProposedApps).to.eq(2); expect(newChannelB!.appInstances.length).to.eq(1); }); it("sync protocol responder is missing a proposal held by the protocol initiator, sync on error", async () => { messagingServiceA.clearLimits(); await nodeA.rpcRouter.dispatch(constructInstallRpc(identityHash, multisigAddress)); const newAppInstanceA = await storeServiceA.getAppInstance(identityHash); const newAppInstanceB = await storeServiceB.getAppInstance(identityHash); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newAppInstanceA!).to.containSubset(newAppInstanceB!); expect(newAppInstanceA!.identityHash).to.eq(identityHash); expect(newAppInstanceA!.appSeqNo).to.eq(2); expect(newAppInstanceA!.latestVersionNumber).to.eq(1); expect(newChannelA!.freeBalanceAppInstance!.latestVersionNumber).to.eq(2); expect(newChannelA!.monotonicNumProposedApps).to.eq(2); expect(newChannelA!.appInstances.length).to.eq(1); }); it("sync protocol initiator is missing a proposal held by the protocol responder, sync on error", async () => { messagingServiceA.clearLimits(); await nodeB.rpcRouter.dispatch(constructInstallRpc(identityHash, multisigAddress)); const newAppInstanceA = await storeServiceA.getAppInstance(identityHash); const newAppInstanceB = await storeServiceB.getAppInstance(identityHash); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newAppInstanceA!).to.containSubset(newAppInstanceB!); expect(newAppInstanceB!.identityHash).to.eq(identityHash); expect(newAppInstanceB!.appSeqNo).to.eq(2); expect(newAppInstanceB!.latestVersionNumber).to.eq(1); expect(newChannelB!.freeBalanceAppInstance!.latestVersionNumber).to.eq(2); expect(newChannelB!.monotonicNumProposedApps).to.eq(2); expect(newChannelB!.appInstances.length).to.eq(1); }); }); describe("Sync::propose + rejectInstall", () => { beforeEach(async () => { // propose-specific setup messagingServiceA = new MemoryMessagingServiceWithLimits( sharedEventEmitter, 0, "propose", undefined, "A-Initial", ); nodeA = await CFCore.create( messagingServiceA, storeServiceA, global["networks"], channelSignerA, lockService, 0, new Logger("CreateClient", env.logLevel, true, "A"), ); // create channel multisigAddress = await createChannel(nodeA, nodeB); // load stores with proposal const rpc = makeProposeCall(nodeA, TicTacToeApp, multisigAddress); await new Promise(async (res) => { nodeB.once(EventNames.SYNC_FAILED_EVENT, res); try { await nodeB.rpcRouter.dispatch({ ...rpc, parameters: deBigNumberifyJson(rpc.parameters), }); } catch (e) { log.info(`Caught error sending rpc: ${e.message}`); } }); // get expected channel from nodeB expect(isHexString(multisigAddress)).to.eq(true); expectedChannel = await storeServiceA.getStateChannel(multisigAddress); const unsynced = await storeServiceB.getStateChannel(multisigAddress); expect(expectedChannel).to.be.ok; expect(expectedChannel!.proposedAppInstances.length).to.eq(1); expect(unsynced?.proposedAppInstances.length).to.eq(0); await nodeA.rpcRouter.dispatch({ methodName: MethodNames.chan_rejectInstall, parameters: { appIdentityHash: expectedChannel!.proposedAppInstances[0][0], multisigAddress, } as MethodParams.RejectInstall, }); expectedChannel = await storeServiceA.getStateChannel(multisigAddress); expect(expectedChannel!.proposedAppInstances.length).to.eq(0); }); it("sync protocol responder is missing a proposal held by the protocol initiator, sync on startup", async function () { const [eventData, newNodeA] = await Promise.all([ new Promise(async (resolve, reject) => { nodeB.on(EventNames.SYNC, (data) => resolve(data)); nodeB.on(EventNames.SYNC_FAILED_EVENT, () => reject(`Sync failed`)); }), CFCore.create( new MemoryMessagingServiceWithLimits( sharedEventEmitter, undefined, undefined, undefined, "A-Recreated", ), storeServiceA, global["networks"], channelSignerA, lockService, 0, new Logger("CreateClient", env.logLevel, true, "A-Recreated"), ), ]); const syncedChannel = await storeServiceA.getStateChannel(multisigAddress); expect(bigNumberifyJson(eventData)).to.containSubset({ from: nodeA.publicIdentifier, type: EventNames.SYNC, data: { syncedChannel: bigNumberifyJson(expectedChannel) }, }); expect(syncedChannel).to.containSubset(expectedChannel!); const rpc = makeProposeCall(newNodeA as CFCore, TicTacToeApp, multisigAddress); const res: any = await new Promise(async (resolve) => { nodeB.once(EventNames.PROPOSE_INSTALL_EVENT, resolve); try { await nodeB.rpcRouter.dispatch({ ...rpc, parameters: deBigNumberifyJson(rpc.parameters), }); } catch (e) { log.info(`Caught error sending rpc: ${e.message}`); } }); const newAppInstanceA = await storeServiceA.getAppProposal(res.data.appInstanceId); const newAppInstanceB = await storeServiceB.getAppProposal(res.data.appInstanceId); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newAppInstanceA!).to.containSubset(newAppInstanceB!); expect(newAppInstanceB!.identityHash).to.eq(res.data.appInstanceId); expect(newAppInstanceB!.appSeqNo).to.eq(3); expect(newAppInstanceB!.latestVersionNumber).to.eq(1); expect(newChannelB!.freeBalanceAppInstance!.latestVersionNumber).to.eq(1); expect(newChannelB!.monotonicNumProposedApps).to.eq(3); expect(newChannelB!.proposedAppInstances.length).to.eq(1); }); it("sync protocol initiator is missing a proposal held by the protocol responder, sync on startup", async () => { messagingServiceA.clearLimits(); await messagingServiceB.disconnect(); const [eventData, newNodeB] = await Promise.all([ new Promise(async (resolve, reject) => { nodeA.on(EventNames.SYNC, (data) => resolve(data)); nodeA.on(EventNames.SYNC_FAILED_EVENT, (data) => reject(`Sync failed`)); }), CFCore.create( new MemoryMessagingServiceWithLimits(sharedEventEmitter), storeServiceB, global["networks"], channelSignerB, lockService, 0, new Logger("CreateClient", env.logLevel, true, "B-recreated"), ), ]); const syncedChannel = await storeServiceA.getStateChannel(multisigAddress); expect(bigNumberifyJson(eventData)).to.containSubset({ from: (newNodeB as CFCore).publicIdentifier, type: EventNames.SYNC, data: { syncedChannel: bigNumberifyJson(expectedChannel) }, }); expect(syncedChannel).to.containSubset(expectedChannel!); const rpc = makeProposeCall(nodeA, TicTacToeApp, multisigAddress); const res: any = await new Promise(async (resolve) => { nodeA.once(EventNames.PROPOSE_INSTALL_EVENT, resolve); try { await (newNodeB as CFCore).rpcRouter.dispatch({ ...rpc, parameters: deBigNumberifyJson(rpc.parameters), }); } catch (e) { log.info(`Caught error sending rpc: ${e.message}`); } }); const newAppInstanceA = await storeServiceA.getAppProposal(res.data.appInstanceId); const newAppInstanceB = await storeServiceB.getAppProposal(res.data.appInstanceId); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newAppInstanceA!).to.containSubset(newAppInstanceB!); expect(newAppInstanceB!.identityHash).to.eq(res.data.appInstanceId); expect(newAppInstanceB!.appSeqNo).to.eq(3); expect(newAppInstanceB!.latestVersionNumber).to.eq(1); expect(newChannelB!.freeBalanceAppInstance!.latestVersionNumber).to.eq(1); expect(newChannelB!.monotonicNumProposedApps).to.eq(3); expect(newChannelB!.proposedAppInstances.length).to.eq(1); }); it("sync protocol responder is missing a proposal held by the protocol initiator, sync on error", async () => { messagingServiceA.clearLimits(); const rpc = makeProposeCall(nodeB, TicTacToeApp, multisigAddress); const res: any = await new Promise(async (resolve) => { nodeB.once("PROPOSE_INSTALL_EVENT", resolve); try { await nodeA.rpcRouter.dispatch({ ...rpc, parameters: deBigNumberifyJson(rpc.parameters), }); } catch (e) { log.info(`Caught error sending rpc: ${e.message}`); } }); const newAppInstanceA = await storeServiceA.getAppProposal(res.data.appInstanceId); const newAppInstanceB = await storeServiceB.getAppProposal(res.data.appInstanceId); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newAppInstanceA!).to.containSubset(newAppInstanceB!); expect(newAppInstanceB!.identityHash).to.eq(res.data.appInstanceId); expect(newAppInstanceB!.appSeqNo).to.eq(3); expect(newAppInstanceB!.latestVersionNumber).to.eq(1); expect(newChannelB!.freeBalanceAppInstance!.latestVersionNumber).to.eq(1); expect(newChannelB!.monotonicNumProposedApps).to.eq(3); expect(newChannelB!.proposedAppInstances.length).to.eq(1); }); it("sync protocol initiator is missing a proposal held by the protocol responder, sync on error", async () => { messagingServiceA.clearLimits(); const rpc = makeProposeCall(nodeA, TicTacToeApp, multisigAddress); const res: any = await new Promise(async (resolve) => { nodeA.once("PROPOSE_INSTALL_EVENT", resolve); try { await nodeB.rpcRouter.dispatch({ ...rpc, parameters: deBigNumberifyJson(rpc.parameters), }); } catch (e) { log.info(`Caught error sending rpc: ${e.message}`); } }); const newAppInstanceA = await storeServiceA.getAppProposal(res.data.appInstanceId); const newAppInstanceB = await storeServiceB.getAppProposal(res.data.appInstanceId); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newAppInstanceA!).to.containSubset(newAppInstanceB!); expect(newAppInstanceB!.identityHash).to.eq(res.data.appInstanceId); expect(newAppInstanceB!.appSeqNo).to.eq(3); expect(newAppInstanceB!.latestVersionNumber).to.eq(1); expect(newChannelB!.freeBalanceAppInstance!.latestVersionNumber).to.eq(1); expect(newChannelB!.monotonicNumProposedApps).to.eq(3); expect(newChannelB!.proposedAppInstances.length).to.eq(1); }); }); describe("Sync::rejectInstall", () => { let identityHash: string; beforeEach(async () => { // create nodeA messagingServiceA = new MemoryMessagingServiceWithLimits( sharedEventEmitter, undefined, undefined, undefined, "NodeA", ); nodeA = await CFCore.create( messagingServiceA, storeServiceA, global["networks"], channelSignerA, lockService, 0, new Logger("CreateClient", env.logLevel, true, "A-initial"), ); // create channel multisigAddress = await createChannel(nodeA, nodeB); // load stores with proposal await makeAndSendProposeCall(nodeA, nodeB, TicTacToeApp, multisigAddress); // verify channel in stores are in sync post-proposal const postProposalA = await storeServiceA.getStateChannel(multisigAddress); const unsynced = await storeServiceB.getStateChannel(multisigAddress); expect(postProposalA!.proposedAppInstances.length).to.eq(1); expect(unsynced!.proposedAppInstances.length).to.eq(1); expect(unsynced!.monotonicNumProposedApps).to.eq(postProposalA!.monotonicNumProposedApps); identityHash = postProposalA!.proposedAppInstances[0][0]; // remove proposal from storeA await storeServiceA.removeAppProposal( multisigAddress, identityHash, StateChannel.fromJson(postProposalA!).removeProposal(identityHash).toJson(), ); expectedChannel = await storeServiceA.getStateChannel(multisigAddress); expect(expectedChannel!.proposedAppInstances.length).to.eq(0); }); it("sync protocol -- initiator has rejected a proposal responder has record of, sync on startup", async () => { // recreate nodeA (unsynced, missing proposal) await messagingServiceA.disconnect(); const [eventData, newNodeA] = await Promise.all([ new Promise(async (resolve) => { nodeB.on(EventNames.SYNC, (data) => resolve(data)); }), CFCore.create( new MemoryMessagingServiceWithLimits(sharedEventEmitter), storeServiceA, global["networks"], channelSignerA, lockService, 0, new Logger("CreateClient", env.logLevel, true, "A-recreated"), ), ]); const syncedChannel = await storeServiceA.getStateChannel(multisigAddress); expect(eventData).to.containSubset({ from: nodeA.publicIdentifier, type: EventNames.SYNC, data: { syncedChannel: expectedChannel }, }); expect(syncedChannel).to.containSubset(expectedChannel!); // propose new app await installApp(newNodeA, nodeB, multisigAddress, TicTacToeApp); }); it("sync protocol -- responder has rejected a proposal initiator has record of, sync on startup", async () => { // recreate nodeA (unsynced, missing proposal) await messagingServiceB.disconnect(); const [eventData, newNodeB] = await Promise.all([ new Promise(async (resolve) => { nodeA.on(EventNames.SYNC, (data) => resolve(data)); }), CFCore.create( new MemoryMessagingServiceWithLimits(sharedEventEmitter), storeServiceB, global["networks"], channelSignerB, lockService, 0, new Logger("CreateClient", env.logLevel, true, "B"), ), ]); const syncedChannel = await storeServiceA.getStateChannel(multisigAddress); expect(eventData).to.containSubset({ from: nodeB.publicIdentifier, type: EventNames.SYNC, data: { syncedChannel: expectedChannel }, }); expect(syncedChannel).to.containSubset(expectedChannel!); // propose new app await installApp(newNodeB, nodeA, multisigAddress, TicTacToeApp); }); it("sync protocol -- initiator has rejected a proposal responder has record of, sync on error", async () => { // There are only two ways a channel in this state will error from being // out of sync in this way. either: // - reject is called -- channel gets back in sync without going // through protocol // - install is called -- call fails after channel is synced. only person // with out of sync channel can call this try { await makeInstallCall(nodeA, identityHash, multisigAddress); } catch (e) {} const updatedChannelA = await storeServiceA.getStateChannel(multisigAddress); const updatedChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(updatedChannelA?.proposedAppInstances.length).to.be.eq(0); expect(updatedChannelB?.proposedAppInstances.length).to.be.eq(0); }); }); describe("Sync::install", () => { let appIdentityHash: string; let unsynced: StateChannelJSON | undefined; // TODO: figure out how to fast-forward IO_SEND_AND_WAIT beforeEach(async () => { // install-specific setup messagingServiceA = new MemoryMessagingServiceWithLimits( sharedEventEmitter, 0, ProtocolNames.install, "send", ); nodeA = await CFCore.create( messagingServiceA, storeServiceA, global["networks"], channelSignerA, lockService, 0, new Logger("CreateClient", env.logLevel, true, "A"), ); // create channel multisigAddress = await createChannel(nodeA, nodeB); // create proposal const [ret] = await Promise.all([ makeAndSendProposeCall(nodeA, nodeB, TicTacToeApp, multisigAddress), new Promise((resolve) => { nodeB.once(EventNames.PROPOSE_INSTALL_EVENT, resolve); }), ]); appIdentityHash = (ret as any).appIdentityHash; await new Promise(async (res, rej) => { nodeB.once(EventNames.SYNC_FAILED_EVENT, res); try { await nodeB.rpcRouter.dispatch(constructInstallRpc(appIdentityHash, multisigAddress)); rej(`Node B should not complete installation`); } catch (e) { log.info(`Caught error sending rpc: ${e.message}`); } }); // get expected channel from nodeB expectedChannel = (await storeServiceA.getStateChannel(multisigAddress))!; unsynced = await storeServiceB.getStateChannel(multisigAddress); expect(unsynced?.appInstances.length).to.eq(0); expect(expectedChannel.appInstances.length).to.eq(1); expect(expectedChannel.freeBalanceAppInstance!.latestVersionNumber).to.eq( unsynced!.freeBalanceAppInstance!.latestVersionNumber + 1, ); }); it("sync protocol -- initiator is missing an app held by responder", async () => { messagingServiceA.clearLimits(); await messagingServiceB.disconnect(); const [eventData, newNodeB] = await Promise.all([ new Promise(async (resolve) => { nodeA.on(EventNames.SYNC, (data) => resolve(data)); }), CFCore.create( new MemoryMessagingServiceWithLimits(sharedEventEmitter), storeServiceB, global["networks"], channelSignerB, lockService, 0, new Logger("CreateClient", env.logLevel, true, "B"), ), ]); const syncedChannel = await storeServiceA.getStateChannel(multisigAddress); expect(eventData).to.containSubset({ from: nodeB.publicIdentifier, type: EventNames.SYNC, data: { syncedChannel: expectedChannel }, }); expect(syncedChannel).to.containSubset(expectedChannel!); await uninstallApp(newNodeB as CFCore, nodeA, appIdentityHash, multisigAddress); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newChannelA!.appInstances.length).to.eq(0); expect(newChannelA!.freeBalanceAppInstance!.latestVersionNumber).to.eq(3); expect(newChannelA!.monotonicNumProposedApps).to.eq(2); }); it("sync protocol -- responder is missing an app held by initiator", async () => { const [eventData, newNodeA] = await Promise.all([ new Promise(async (resolve) => { nodeB.on(EventNames.SYNC, (data) => resolve(data)); }), CFCore.create( new MemoryMessagingServiceWithLimits(sharedEventEmitter), storeServiceA, global["networks"], channelSignerA, lockService, 0, new Logger("CreateClient", env.logLevel, true, "A"), ), ]); const syncedChannel = await storeServiceA.getStateChannel(multisigAddress); expect(eventData).to.containSubset({ from: nodeA.publicIdentifier, type: EventNames.SYNC, data: { syncedChannel: expectedChannel }, }); expect(syncedChannel).to.containSubset(expectedChannel!); await uninstallApp(nodeB, newNodeA as CFCore, appIdentityHash, multisigAddress); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newChannelB!.appInstances.length).to.eq(0); expect(newChannelB!.freeBalanceAppInstance!.latestVersionNumber).to.eq(3); expect(newChannelB!.monotonicNumProposedApps).to.eq(2); }); // NOTE: same test for initiator/responder ordering would fail bc storeB // does not have installed app it("sync protocol -- responder is missing an app held by initiator, sync on error", async () => { messagingServiceA.clearLimits(); await uninstallApp(nodeA, nodeB, appIdentityHash, multisigAddress); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newChannelA!.appInstances.length).to.eq(0); expect(newChannelA!.freeBalanceAppInstance!.latestVersionNumber).to.eq(3); expect(newChannelA!.monotonicNumProposedApps).to.eq(2); }); }); describe("Sync::install + rejectInstall", () => { let appIdentityHash: string; let unsynced: StateChannelJSON | undefined; // TODO: figure out how to fast-forward IO_SEND_AND_WAIT beforeEach(async () => { // install-specific setup messagingServiceA = new MemoryMessagingServiceWithLimits( sharedEventEmitter, 0, ProtocolNames.install, "send", ); nodeA = await CFCore.create( messagingServiceA, storeServiceA, global["networks"], channelSignerA, lockService, 0, new Logger("CreateClient", env.logLevel, true, "A"), ); // create channel multisigAddress = await createChannel(nodeA, nodeB); // create proposal const [ret] = await Promise.all([ makeAndSendProposeCall(nodeA, nodeB, TicTacToeApp, multisigAddress), new Promise((resolve) => { nodeB.once(EventNames.PROPOSE_INSTALL_EVENT, () => { resolve(); }); }), ]); appIdentityHash = (ret as any).appIdentityHash; await new Promise(async (res, rej) => { nodeA.once(EventNames.INSTALL_EVENT, res); try { await nodeB.rpcRouter.dispatch(constructInstallRpc(appIdentityHash, multisigAddress)); rej(`Node B should not complete installation`); } catch (e) { log.info(`Caught error sending rpc: ${e.message}`); } }); // get expected channel from nodeB expectedChannel = (await storeServiceA.getStateChannel(multisigAddress))!; unsynced = await storeServiceB.getStateChannel(multisigAddress); expect(unsynced?.appInstances.length).to.eq(0); expect(unsynced!.proposedAppInstances.length).to.eq(1); expect(expectedChannel?.appInstances.length).to.eq(1); // nodeB rejects proposal await nodeB.rpcRouter.dispatch({ methodName: MethodNames.chan_rejectInstall, parameters: { appIdentityHash, multisigAddress, } as MethodParams.RejectInstall, }); const postRejectChannel = await storeServiceB.getStateChannel(multisigAddress); expect(postRejectChannel!.proposedAppInstances.length).to.eq(0); }); it("sync protocol -- initiator is missing an app held by responder, sync on startup", async () => { messagingServiceA.clearLimits(); await messagingServiceB.disconnect(); const [eventData, newNodeB] = await Promise.all([ new Promise(async (resolve) => { nodeA.on(EventNames.SYNC, (data) => resolve(data)); }), CFCore.create( new MemoryMessagingServiceWithLimits(sharedEventEmitter), storeServiceB, global["networks"], channelSignerB, lockService, 0, new Logger("CreateClient", env.logLevel, true, "B"), ), ]); const syncedChannel = await storeServiceA.getStateChannel(multisigAddress); expect(eventData).to.containSubset({ from: nodeB.publicIdentifier, type: EventNames.SYNC, data: { syncedChannel: expectedChannel }, }); expect(syncedChannel).to.containSubset(expectedChannel!); await uninstallApp(newNodeB as CFCore, nodeA, appIdentityHash, multisigAddress); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newChannelA!.appInstances.length).to.eq(0); expect(newChannelA!.freeBalanceAppInstance!.latestVersionNumber).to.eq(3); expect(newChannelA!.monotonicNumProposedApps).to.eq(2); }); it("sync protocol -- responder is missing an app held by initiator, sync on startup", async () => { const [eventData, newNodeA] = await Promise.all([ new Promise(async (resolve) => { nodeB.on(EventNames.SYNC, (data) => resolve(data)); }), CFCore.create( new MemoryMessagingServiceWithLimits(sharedEventEmitter), storeServiceA, global["networks"], channelSignerA, lockService, 0, new Logger("CreateClient", env.logLevel, true, "A"), ), ]); const syncedChannel = await storeServiceA.getStateChannel(multisigAddress); expect(eventData).to.containSubset({ from: nodeA.publicIdentifier, type: EventNames.SYNC, data: { syncedChannel: expectedChannel }, }); expect(syncedChannel).to.containSubset(expectedChannel!); await uninstallApp(nodeB, newNodeA as CFCore, appIdentityHash, multisigAddress); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newChannelB!.appInstances.length).to.eq(0); expect(newChannelB!.freeBalanceAppInstance!.latestVersionNumber).to.eq(3); expect(newChannelB!.monotonicNumProposedApps).to.eq(2); }); // NOTE: same test for initiator/responder ordering would fail bc storeB // does not have installed app it("sync protocol -- responder is missing an app held by initiator, sync on error", async () => { messagingServiceA.clearLimits(); await uninstallApp(nodeA, nodeB, appIdentityHash, multisigAddress); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newChannelA!.appInstances.length).to.eq(0); expect(newChannelA!.freeBalanceAppInstance!.latestVersionNumber).to.eq(3); expect(newChannelA!.monotonicNumProposedApps).to.eq(2); }); }); describe("Sync::uninstall", () => { let identityHash: string; beforeEach(async () => { // uninstall-specific setup messagingServiceA = new MemoryMessagingServiceWithLimits( sharedEventEmitter, 0, ProtocolNames.uninstall, "send", ); nodeA = await CFCore.create( messagingServiceA, storeServiceA, global["networks"], channelSignerA, lockService, 0, new Logger("CreateClient", env.logLevel, true, "A"), ); // create channel multisigAddress = await createChannel(nodeA, nodeB); // create app [identityHash] = await installApp(nodeA, nodeB, multisigAddress, TicTacToeApp); // nodeB should respond to the uninstall, nodeA will not get the // message, but nodeB thinks its sent await new Promise(async (resolve, reject) => { nodeB.once(EventNames.SYNC_FAILED_EVENT, () => resolve); try { await nodeB.rpcRouter.dispatch(constructUninstallRpc(identityHash, multisigAddress)); return reject(`Node B should be able to complete uninstall`); } catch (e) { return resolve(); } }); // get expected channel from nodeB expectedChannel = (await storeServiceA.getStateChannel(multisigAddress))!; const unsynced = await storeServiceB.getStateChannel(multisigAddress); expect(expectedChannel.appInstances.length).to.eq(0); expect(unsynced?.appInstances.length).to.eq(1); }); it("sync protocol -- initiator has an app uninstalled by responder, sync on startup", async () => { await messagingServiceB.disconnect(); messagingServiceA.clearLimits(); const [eventData, newNodeB] = await Promise.all([ new Promise(async (resolve) => { nodeA.on(EventNames.SYNC, (data) => resolve(data)); }), CFCore.create( new MemoryMessagingServiceWithLimits(sharedEventEmitter), storeServiceB, global["networks"], channelSignerB, lockService, 0, new Logger("CreateClient", env.logLevel, true, "B"), ), ]); const syncedChannel = await storeServiceA.getStateChannel(multisigAddress); expect(eventData).to.containSubset({ from: nodeB.publicIdentifier, type: EventNames.SYNC, data: { syncedChannel: expectedChannel }, }); expect(syncedChannel).to.containSubset(expectedChannel!); // create new app [identityHash] = await installApp(newNodeB as CFCore, nodeA, multisigAddress, TicTacToeApp); const [newAppInstanceA, newAppInstanceB] = await Promise.all([ storeServiceA.getAppInstance(identityHash), storeServiceB.getAppInstance(identityHash), ]); const [newChannelA, newChannelB] = await Promise.all([ storeServiceA.getStateChannel(multisigAddress), storeServiceB.getStateChannel(multisigAddress), ]); expect(newChannelA!).to.containSubset(newChannelB!); expect(newAppInstanceA!).to.containSubset(newAppInstanceB!); expect(newAppInstanceA!.identityHash).to.eq(identityHash); expect(newAppInstanceA!.appSeqNo).to.eq(3); expect(newAppInstanceA!.latestVersionNumber).to.eq(1); expect(newChannelA!.freeBalanceAppInstance!.latestVersionNumber).to.eq(4); expect(newChannelA!.monotonicNumProposedApps).to.eq(3); expect(newChannelA!.appInstances.length).to.eq(1); }); it("sync protocol -- responder has an app uninstalled by initiator, sync on startup", async () => { await messagingServiceA.disconnect(); const [eventData, newNodeA] = await Promise.all([ new Promise(async (resolve) => { nodeB.on(EventNames.SYNC, (data) => resolve(data)); }), CFCore.create( new MemoryMessagingServiceWithLimits(sharedEventEmitter), storeServiceA, global["networks"], channelSignerA, lockService, 0, new Logger("CreateClient", env.logLevel, true, "A"), ), ]); const syncedChannel = await storeServiceA.getStateChannel(multisigAddress); expect(eventData).to.containSubset({ from: nodeA.publicIdentifier, type: EventNames.SYNC, data: { syncedChannel: expectedChannel }, }); expect(syncedChannel).to.containSubset(expectedChannel!); // create new app [identityHash] = await installApp(nodeB, newNodeA as CFCore, multisigAddress, TicTacToeApp); const [newAppInstanceA, newAppInstanceB] = await Promise.all([ storeServiceA.getAppInstance(identityHash), storeServiceB.getAppInstance(identityHash), ]); const [newChannelA, newChannelB] = await Promise.all([ storeServiceA.getStateChannel(multisigAddress), storeServiceB.getStateChannel(multisigAddress), ]); expect(newChannelA!).to.containSubset(newChannelB!); expect(newAppInstanceA!).to.containSubset(newAppInstanceB!); expect(newAppInstanceB!.identityHash).to.eq(identityHash); expect(newAppInstanceB!.appSeqNo).to.eq(3); expect(newAppInstanceB!.latestVersionNumber).to.eq(1); expect(newChannelB!.freeBalanceAppInstance!.latestVersionNumber).to.eq(4); expect(newChannelB!.monotonicNumProposedApps).to.eq(3); expect(newChannelB!.appInstances.length).to.eq(1); }); it("sync protocol -- initiator has an app uninstalled by responder, sync on error", async () => { messagingServiceA.clearLimits(); // create new app [identityHash] = await installApp(nodeA, nodeB, multisigAddress, TicTacToeApp); const [newAppInstanceA, newAppInstanceB] = await Promise.all([ storeServiceA.getAppInstance(identityHash), storeServiceB.getAppInstance(identityHash), ]); const [newChannelA, newChannelB] = await Promise.all([ storeServiceA.getStateChannel(multisigAddress), storeServiceB.getStateChannel(multisigAddress), ]); expect(newChannelA!).to.containSubset(newChannelB!); expect(newAppInstanceA!).to.containSubset(newAppInstanceB!); expect(newAppInstanceA!.identityHash).to.eq(identityHash); expect(newAppInstanceA!.appSeqNo).to.eq(3); expect(newAppInstanceA!.latestVersionNumber).to.eq(1); expect(newChannelA!.freeBalanceAppInstance!.latestVersionNumber).to.eq(4); expect(newChannelA!.monotonicNumProposedApps).to.eq(3); expect(newChannelA!.appInstances.length).to.eq(1); }); it("sync protocol -- responder has an app uninstalled by initiator, sync on error", async () => { messagingServiceA.clearLimits(); // create new app [identityHash] = await installApp(nodeB, nodeA, multisigAddress, TicTacToeApp); const [newAppInstanceA, newAppInstanceB] = await Promise.all([ storeServiceA.getAppInstance(identityHash), storeServiceB.getAppInstance(identityHash), ]); const [newChannelA, newChannelB] = await Promise.all([ storeServiceA.getStateChannel(multisigAddress), storeServiceB.getStateChannel(multisigAddress), ]); expect(newChannelA!).to.containSubset(newChannelB!); expect(newAppInstanceA!).to.containSubset(newAppInstanceB!); expect(newAppInstanceB!.identityHash).to.eq(identityHash); expect(newAppInstanceB!.appSeqNo).to.eq(3); expect(newAppInstanceB!.latestVersionNumber).to.eq(1); expect(newChannelB!.freeBalanceAppInstance!.latestVersionNumber).to.eq(4); expect(newChannelB!.monotonicNumProposedApps).to.eq(3); expect(newChannelB!.appInstances.length).to.eq(1); }); }); describe("Sync::takeAction", () => { let appIdentityHash: string; beforeEach(async () => { // uninstall-specific setup messagingServiceA = new MemoryMessagingServiceWithLimits( sharedEventEmitter, 0, ProtocolNames.takeAction, ); nodeA = await CFCore.create( messagingServiceA, storeServiceA, global["networks"], channelSignerA, lockService, 0, new Logger("CreateClient", env.logLevel, true, "A"), ); // create channel multisigAddress = await createChannel(nodeA, nodeB); // create app [appIdentityHash] = await installApp(nodeA, nodeB, multisigAddress, TicTacToeApp); await new Promise(async (resolve, reject) => { nodeB.once(EventNames.SYNC_FAILED_EVENT, () => resolve()); try { await nodeB.rpcRouter.dispatch( constructTakeActionRpc(appIdentityHash, multisigAddress, validAction), ); reject(`Should not be able to complete protocol`); } catch (e) { log.info(`Caught error sending rpc: ${e.message}`); } }); // get expected channel from nodeB expectedChannel = (await storeServiceA.getStateChannel(multisigAddress))!; expect(expectedChannel.appInstances.length).to.eq(1); const aheadApp = expectedChannel.appInstances.find(([id, app]) => id === appIdentityHash); expect(aheadApp).to.be.ok; const expectedAppInstance = aheadApp![1]; expect(expectedAppInstance.latestVersionNumber).to.eq(2); const unsynced = (await storeServiceB.getStateChannel(multisigAddress))!; expect(unsynced.appInstances.length).to.eq(1); const behindApp = unsynced.appInstances.find(([id, app]) => id === appIdentityHash); expect(behindApp).to.be.ok; const unsyncedAppInstance = behindApp![1]; expect(unsyncedAppInstance.latestVersionNumber).to.eq(1); }); it("initiator has an app that has a single signed update that the responder does not have, sync on error", async () => { messagingServiceA.clearLimits(); // attempt to uninstall await uninstallApp(nodeA, nodeB, appIdentityHash, multisigAddress); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newChannelB!.appInstances.length).to.eq(0); expect(newChannelB!.freeBalanceAppInstance!.latestVersionNumber).to.eq(3); expect(newChannelB!.monotonicNumProposedApps).to.eq(2); }); it("responder has an app that has a single signed update that the initiator does not have, sync on error", async () => { messagingServiceA.clearLimits(); //attempt to uninstall await uninstallApp(nodeB, nodeA, appIdentityHash, multisigAddress); const newChannelA = await storeServiceA.getStateChannel(multisigAddress); const newChannelB = await storeServiceB.getStateChannel(multisigAddress); expect(newChannelA!).to.containSubset(newChannelB!); expect(newChannelB!.appInstances.length).to.eq(0); expect(newChannelB!.freeBalanceAppInstance!.latestVersionNumber).to.eq(3); expect(newChannelB!.monotonicNumProposedApps).to.eq(2); }); }); });
the_stack
import Path from 'path'; import Util from 'util'; import { Db, MongoClient, ObjectId } from 'mongodb'; import { BadRequest, NotFound } from '../../errors'; import { BaseMedia, Configuration, Media, MediaPlaylist, Playlist, PlaylistCreate, PlaylistEntryUpdate, PlaylistUpdate, SubsetConstraints, SubsetFields, UpdateMedia, } from '@vimtur/common'; import { Database } from '../../types'; import { Insights } from '../../insights'; import { Validator } from '../../utils/validator'; import Config from '../../config'; import { Updater } from './updater'; import { createArrayFilter, createBooleanFilter, createNumberFilter, createStringFilter, } from './utils'; interface Actor { name: string; } interface Tag { name: string; } const MEDIA_VALIDATOR = Validator.load('BaseMedia'); export class MongoConnector extends Database { private server: MongoClient; private db: Db; public static async init(): Promise<Database> { const server = await MongoConnector.connect(); const connector = new MongoConnector(server); await Updater.apply(connector.db); return connector; } private static async connect(): Promise<MongoClient> { const config = Config.get().database; if (!config) { throw new Error('database config missing'); } // eslint-disable-next-line no-constant-condition while (true) { try { return await MongoClient.connect(config.uri, { useNewUrlParser: true, useUnifiedTopology: true, }); break; } catch (err) { console.warn('Failed to connect to database, retrying in 10 seconds', err.message); await new Promise((resolve) => setTimeout(resolve, 10000)); } } } private constructor(server: MongoClient) { super(); this.server = server; const dbName = Config.get().database?.db; if (!dbName) { throw new Error('missing database config'); } console.log(`Using database: ${dbName}`); this.db = this.server.db(dbName); } public async getUserConfig(): Promise<Configuration.Partial> { const meta = this.db.collection('config'); const row = await meta.findOne({ _id: 'userconfig' }); if (!row) { return {}; } // The projection doesn't seem to remove _id so do it manually. delete row._id; return row; } public async saveUserConfig(config: Configuration.Partial): Promise<void> { const meta = this.db.collection('config'); await meta.updateOne({ _id: 'userconfig' }, { $set: config }, { upsert: true }); } public async getTags(): Promise<string[]> { const tags = this.db.collection<Tag>('tags'); const rows = await tags.find({}).toArray(); return rows.map((el) => el.name).sort(); } public async addTag(tag: string): Promise<void> { const tags = this.db.collection<Tag>('tags'); try { await tags.insertOne({ name: tag }); } catch (err) { if (err.message.startsWith('E11000 duplicate key')) { throw new BadRequest('Tag already exists'); } else { throw err; } } } public async removeTag(tag: string): Promise<void> { const media = this.db.collection<BaseMedia>('media'); await media.updateMany({}, { $pull: { tags: tag } }); const tags = this.db.collection<Tag>('tags'); await tags.deleteOne({ name: tag }); } public async getActors(): Promise<string[]> { const actors = this.db.collection<Actor>('actors'); const rows = await actors.find({}).toArray(); return rows.map((el) => el.name).sort(); } public async addActor(actor: string): Promise<void> { const actors = this.db.collection<Actor>('actors'); try { await actors.insertOne({ name: actor }); } catch (err) { if (err.message.startsWith('E11000 duplicate key')) { throw new BadRequest('Actor already exists'); } else { throw err; } } } public async removeActor(actor: string): Promise<void> { const media = this.db.collection<BaseMedia>('media'); await Util.promisify(media.updateMany.bind(media))({}, { $pull: { actors: actor } }); const actors = this.db.collection<Actor>('actors'); await actors.deleteOne({ name: actor }); } public async addPlaylist(request: PlaylistCreate): Promise<Playlist> { const playlists = this.db.collection('playlists'); const result = await playlists.insertOne({ ...request, size: 0 }); const fetched = await this.getPlaylist(result.insertedId.toHexString()); if (!fetched) { throw new Error('Error adding playlist'); } if (request.hashes) { for (const hash of request.hashes) { await this.addMediaToPlaylist(hash, fetched.id); } } return fetched; } public async removePlaylist(id: string): Promise<void> { const media = this.db.collection('media'); await media.updateMany( { 'playlists._id': new ObjectId(id), }, { $pull: { playlists: { _id: new ObjectId(id) }, }, }, ); const playlists = this.db.collection('playlists'); await playlists.deleteOne({ _id: new ObjectId(id) }); } public async updatePlaylist(id: string, request: PlaylistUpdate): Promise<void> { const playlists = this.db.collection('playlists'); await playlists.updateOne({ _id: new ObjectId(id) }, { $set: request }); } public getPlaylists(): Promise<Playlist[]> { const playlists = this.db.collection('playlists'); return playlists .aggregate([ { $addFields: { id: { $convert: { input: '$_id', to: 'string', }, }, }, }, { $project: { _id: 0, }, }, ]) .toArray(); } public async getPlaylist(id: string): Promise<Playlist | undefined> { const playlists = this.db.collection('playlists'); const raw = await playlists.findOne({ _id: new ObjectId(id) }); if (!raw) { return undefined; } raw.id = raw._id.toHexString(); delete raw._id; return raw; } public async addMediaToPlaylist(hash: string, playlistId: string): Promise<MediaPlaylist> { const media = await this.getMedia(hash); if (!media) { throw new NotFound(`Media not found: ${hash}`); } const existingEntry = media.playlists && media.playlists.find((playlist) => playlist.id === playlistId); if (existingEntry) { // If already in the playlist, then ignore. return existingEntry; } const playlistCollection = this.db.collection('playlists'); const updateResult = await playlistCollection.findOneAndUpdate( { _id: new ObjectId(playlistId), }, { $inc: { size: 1, }, }, ); if (!updateResult.value || !updateResult.ok) { throw new NotFound(`Playlist not found: ${playlistId}`); } const order = updateResult.value.size; const mediaCollection = this.db.collection('media'); // If the update failed attempt a rollback, this may include ones // that have been added to the set after this one. const updateRollback = async (): Promise<void> => { // In an ideal world these need to be done in parallel, atomically. // Doing this one first at least means worse case is a gap of 1. await mediaCollection.updateMany( { 'playlists._id': new ObjectId(playlistId), }, { $inc: { 'playlists.$[playlist].order': -1, }, }, { arrayFilters: [ { 'playlist.order': { $gt: order }, 'playlist._id': new ObjectId(playlistId) }, ], }, ); await playlistCollection.updateOne( { _id: new ObjectId(playlistId), }, { $inc: { size: -1, }, }, ); }; try { const mediaUpdateResult = await mediaCollection.updateOne( { hash, 'playlists._id': { $ne: new ObjectId(playlistId) }, }, { $push: { playlists: { _id: new ObjectId(playlistId), order, }, }, }, ); // If it's been added sometime between the initial check and now, rollback. if (mediaUpdateResult.modifiedCount === 0) { await updateRollback(); } await playlistCollection.updateOne( { _id: new ObjectId(playlistId), thumbnail: { $exists: false }, }, { $set: { thumbnail: hash }, }, ); return { order, id: playlistId, }; } catch (err) { console.warn('Add to playlist failed', hash, playlistId, err); await updateRollback(); throw err; } } public async removeMediaFromPlaylist(hash: string, playlistId: string): Promise<void> { const mediaCollection = this.db.collection('media'); const result = await mediaCollection.findOneAndUpdate( { hash, 'playlists._id': new ObjectId(playlistId), }, { $pull: { playlists: { _id: new ObjectId(playlistId) }, }, }, ); if (result.ok && result.value) { const mediaPlaylist = result.value.playlists.find( (pl: any) => pl._id.toHexString() === playlistId, ); if (!mediaPlaylist) { throw new Error( `Media playlist fetched and updated with no matching playlist (${hash}/${playlistId})`, ); } await mediaCollection.updateMany( { 'playlists._id': new ObjectId(playlistId), }, { $inc: { 'playlists.$[playlist].order': -1, }, }, { arrayFilters: [ { 'playlist.order': { $gt: mediaPlaylist.order }, 'playlist._id': new ObjectId(playlistId), }, ], }, ); const playlistCollection = this.db.collection('playlists'); await playlistCollection.updateOne( { _id: new ObjectId(playlistId), }, { $inc: { size: -1, }, }, ); await playlistCollection.updateOne( { _id: new ObjectId(playlistId), thumbnail: hash, }, { $unset: { hash: '' }, }, ); } } public async updateMediaPlaylistOrder( hash: string, playlistId: string, update: PlaylistEntryUpdate, ): Promise<void> { const mediaCollection = this.db.collection('media'); const matchedMedia = await this.subsetFields( { playlist: playlistId, hash: { equalsAll: [hash] }, }, { order: 1, hash: 1 }, ); const media = matchedMedia[0]; if (!media) { throw new NotFound(`No media found: ${hash} that has playlist ${playlistId}`); } const playlist = await this.getPlaylist(playlistId); if (!playlist) { throw new NotFound(`No playlist found with id ${playlistId}`); } if (update.order >= playlist.size) { throw new BadRequest( `Requested location (${update.order}) is >= playlist size (${playlist.size})`, ); } const newLocation = update.order; if (newLocation < 0) { throw new BadRequest(`Requested location (${update.order}) is less than 0`); } const existingLocation = media.order; if (existingLocation === undefined) { throw new Error('Could not retrieve existing location for media in playlist'); } if (newLocation === existingLocation) { return; } if (newLocation > existingLocation) { await mediaCollection.updateMany( { 'playlists._id': new ObjectId(playlistId), }, { $inc: { 'playlists.$[playlist].order': -1, }, }, { arrayFilters: [ { 'playlist.order': { $gt: existingLocation, $lte: newLocation }, 'playlist._id': new ObjectId(playlistId), }, ], }, ); } else { await mediaCollection.updateMany( { 'playlists._id': new ObjectId(playlistId), }, { $inc: { 'playlists.$[playlist].order': 1, }, }, { arrayFilters: [ { 'playlist.order': { $lt: existingLocation, $gte: newLocation }, 'playlist._id': new ObjectId(playlistId), }, ], }, ); } await mediaCollection.updateOne( { hash, 'playlists._id': new ObjectId(playlistId), }, { $set: { 'playlists.$.order': newLocation, }, }, ); } public async getMedia(hash: string): Promise<Media | undefined> { const media = this.db.collection<BaseMedia>('media'); const result = await media.findOne({ hash }); if (result) { return { ...result, absolutePath: Path.resolve(Config.get().libraryPath, result.path), ...(result.playlists ? { playlists: result.playlists.map((playlist) => ({ id: (playlist as any)._id.toHexString(), order: playlist.order, })), } : {}), }; } return undefined; } public async resetClones(age: number): Promise<void> { const collection = this.db.collection<BaseMedia>('media'); const result = await collection.updateMany( { cloneDate: { $lt: age } }, { $unset: { clones: '' } }, ); console.log(`resetClones: ${result.matchedCount} reset`); } public async resetAutoTags(): Promise<void> { const collection = this.db.collection<BaseMedia>('media'); const result = await collection.updateMany( { autoTags: { $exists: true } }, { $unset: { autoTags: '' } }, ); console.log(`resetAutoTags: ${result.matchedCount} cleared`); } public async saveBulkMedia(constraints: SubsetConstraints, media: UpdateMedia): Promise<number> { console.log('Save Bulk', constraints, media); const collection = this.db.collection('media'); // Filter out various old fields we no longer require. // This one is generated on get media and may be accidentally passed back. const oldMedia = media as any; if (oldMedia.absolutePath !== undefined) { delete oldMedia.absolutePath; } if (oldMedia.transcode !== undefined) { delete oldMedia.transcode; } if (oldMedia.cached !== undefined) { delete oldMedia.cached; } // Map all metadata keys to avoid over-writes, if the media already exists. if (media.metadata) { for (const key of Object.keys(media.metadata)) { (media as any)[`metadata.${key}`] = (media.metadata as any)[key]; } delete media.metadata; } const result = await collection.updateMany(this.buildMediaMatch(constraints), { $set: media }); return result.matchedCount; } public async saveMedia(hash: string, media: UpdateMedia | BaseMedia): Promise<Media> { // Filter out various old fields we no longer require. // This one is generated on get media and may be accidentally passed back. const oldMedia = media as any; if (oldMedia.absolutePath !== undefined) { delete oldMedia.absolutePath; } if (oldMedia.transcode !== undefined) { delete oldMedia.transcode; } if (oldMedia.cached !== undefined) { delete oldMedia.cached; } const collection = this.db.collection<BaseMedia>('media'); if (await this.getMedia(hash)) { // Map all metadata keys to avoid over-writes, if the media already exists. if (media.metadata) { for (const key of Object.keys(media.metadata)) { (media as any)[`metadata.${key}`] = (media.metadata as any)[key]; } delete media.metadata; } await collection.updateOne({ hash }, { $set: media as any }); } else { (media as BaseMedia).hash = hash; // If it's a new one then pre-validate it to show better errors. const result = MEDIA_VALIDATOR.validate(media); if (!result.success) { throw new BadRequest(result.errorText!); } await collection.insertOne(media as any); } return (await this.getMedia(hash))!; } public async removeMedia(hash: string): Promise<void> { const mediaCollection = this.db.collection<BaseMedia>('media'); const media = await this.getMedia(hash); if (media?.playlists) { for (const playlist of media.playlists) { await this.removeMediaFromPlaylist(hash, playlist.id); } } if (media) { await this.db.collection<BaseMedia>('media.deleted').insertOne(media); } await mediaCollection.deleteOne({ hash }); } public async addMediaTag(hash: string, tag: string): Promise<void> { await this.db.collection<BaseMedia>('media').updateOne({ hash }, { $addToSet: { tags: tag } }); } public async removeMediaTag(hash: string, tag: string): Promise<void> { await this.db.collection<BaseMedia>('media').updateOne({ hash }, { $pull: { tags: tag } }); } public async addMediaActor(hash: string, actor: string): Promise<void> { await this.db .collection<BaseMedia>('media') .updateOne({ hash }, { $addToSet: { actors: actor } }); } public async removeMediaActor(hash: string, actor: string): Promise<void> { await this.db.collection<BaseMedia>('media').updateOne({ hash }, { $pull: { actors: actor } }); } public async subsetFields( constraints: SubsetConstraints, fields?: SubsetFields, ): Promise<BaseMedia[]> { const mediaCollection = this.db.collection<BaseMedia>('media'); const pipeline: object[] = [{ $match: this.buildMediaMatch(constraints) }]; if (constraints.sample) { pipeline.push({ $sample: { size: constraints.sample } }); } if (constraints.playlist) { if (!constraints.sortBy) { constraints.sortBy = 'order'; } pipeline.push({ $addFields: { playlist: { $arrayElemAt: [ { $filter: { input: '$playlists', as: 'playlist', cond: { $eq: ['$$playlist._id', new ObjectId(constraints.playlist)] }, }, }, 0, ], }, }, }); pipeline.push({ $addFields: { order: '$playlist.order', playlist: { $convert: { input: '$playlist._id', to: 'string', }, }, }, }); } const sort: object = {}; if (constraints.sortBy) { switch (constraints.sortBy) { case 'hashDate': // Fallthrough case 'rating': Object.assign(sort, { [constraints.sortBy]: -1 }); break; case 'order': // Fallthrough case 'path': Object.assign(sort, { [constraints.sortBy]: 1 }); break; case 'length': // Fallthrough case 'createdAt': Object.assign(sort, { [`metadata.${constraints.sortBy}`]: -1 }); break; case 'recommended': // Skip, handled by subset wrapper. break; default: throw new Error(`Unknown sortBy - ${constraints.sortBy}`); } } if (constraints.keywordSearch) { pipeline.push({ $addFields: { score: { $meta: 'textScore' } } }); pipeline.push({ $sort: { score: { $meta: 'textScore', }, ...sort, }, }); } else if (Object.keys(sort).length > 0) { pipeline.push({ $sort: sort, }); } pipeline.push({ $project: fields ?? { hash: 1, }, }); return mediaCollection.aggregate(pipeline).toArray(); } public async subset(constraints: SubsetConstraints): Promise<string[]> { const result = await this.subsetFields(constraints); const mapped = result.map((media) => media.hash); if (constraints.sortBy === 'recommended') { const insights = new Insights(this); console.time('Generating analytics'); const metadata = await insights.analyse(); console.timeEnd('Generating analytics'); console.time('Scoring and sorting recommendations'); const scored = await insights.getRecommendations(mapped, metadata); console.timeEnd('Scoring and sorting recommendations'); return scored.map((el) => el.hash); } else { return mapped; } } public async close(): Promise<void> { await this.server.close(); } private buildMediaMatch(constraints: SubsetConstraints): object { const filters: object[] = []; if (constraints.keywordSearch) { filters.push({ $text: { $search: constraints.keywordSearch } }); } if (constraints.playlist) { filters.push({ playlists: { $elemMatch: { _id: new ObjectId(constraints.playlist), }, }, }); } filters.push(createArrayFilter('tags', constraints.tags)); filters.push(createArrayFilter('autoTags', constraints.autoTags)); filters.push(createArrayFilter('actors', constraints.actors)); filters.push(createArrayFilter('type', constraints.type)); filters.push(createStringFilter('metadata.artist', constraints.artist)); filters.push(createStringFilter('metadata.album', constraints.album)); filters.push(createStringFilter('metadata.title', constraints.title)); filters.push(createStringFilter('hash', constraints.hash)); filters.push(createStringFilter('dir', constraints.dir)); filters.push(createStringFilter('path', constraints.path)); filters.push(createStringFilter('duplicateOf', constraints.duplicateOf)); filters.push(createNumberFilter('metadata.height', constraints.quality)); filters.push(createNumberFilter('rating', constraints.rating)); filters.push(createNumberFilter('metadata.length', constraints.length)); filters.push(createBooleanFilter('corrupted', constraints.corrupted)); filters.push(createBooleanFilter('thumbnail', constraints.thumbnail)); filters.push(createBooleanFilter('thumbnailOptimised', constraints.thumbnailOptimised)); filters.push(createBooleanFilter('preview', constraints.preview)); filters.push(createBooleanFilter('previewOptimised', constraints.previewOptimised)); if (constraints.phashed !== undefined) { filters.push({ phash: { $exists: constraints.phashed } }); } if (constraints.cached !== undefined) { if (constraints.cached) { filters.push({ $or: [{ 'metadata.qualityCache.0': { $exists: true } }, { type: { $ne: 'video' } }], }); } else { filters.push({ $and: [{ 'metadata.qualityCache.0': { $exists: false } }, { type: 'video' }], }); } } if (constraints.indexed !== undefined) { filters.push({ metadata: { $exists: constraints.indexed } }); } if (constraints.hasClones !== undefined) { filters.push({ 'clones.0': { $exists: constraints.hasClones } }); } const filteredFilters = filters.filter((filter) => Object.keys(filter).length > 0); if (filteredFilters.length === 0) { return {}; } return { $and: filteredFilters, }; } }
the_stack
import {action} from '@storybook/addon-actions'; import {ActionBar, ActionBarContainer} from '../../actionbar'; import {ActionButton} from '@react-spectrum/button'; import {ActionGroup} from '@react-spectrum/actiongroup'; import {ActionMenu} from '@react-spectrum/menu'; import Add from '@spectrum-icons/workflow/Add'; import {Content} from '@react-spectrum/view'; import Copy from '@spectrum-icons/workflow/Copy'; import Delete from '@spectrum-icons/workflow/Delete'; import {Droppable} from '@react-aria/dnd/stories/dnd.stories'; import Edit from '@spectrum-icons/workflow/Edit'; import FileTxt from '@spectrum-icons/workflow/FileTxt'; import {Flex} from '@react-spectrum/layout'; import Folder from '@spectrum-icons/workflow/Folder'; import {Heading, Text} from '@react-spectrum/text'; import {IllustratedMessage} from '@react-spectrum/illustratedmessage'; import {Image} from '@react-spectrum/image'; import Info from '@spectrum-icons/workflow/Info'; import {Item, ListView} from '../'; import {ItemDropTarget} from '@react-types/shared'; import {Link} from '@react-spectrum/link'; import NoSearchResults from '@spectrum-icons/illustrations/src/NoSearchResults'; import React, {useEffect, useState} from 'react'; import {storiesOf} from '@storybook/react'; import {useAsyncList, useListData} from '@react-stately/data'; import {useDragHooks, useDropHooks} from '@react-spectrum/dnd'; const items = [ {key: 'a', name: 'Adobe Photoshop', type: 'file'}, {key: 'b', name: 'Adobe XD', type: 'file'}, {key: 'c', name: 'Documents', type: 'folder'}, {key: 'd', name: 'Adobe InDesign', type: 'file'}, {key: 'e', name: 'Utilities', type: 'folder'}, {key: 'f', name: 'Adobe AfterEffects', type: 'file'}, {key: 'g', name: 'Adobe Illustrator', type: 'file'}, {key: 'h', name: 'Adobe Lightroom', type: 'file'}, {key: 'i', name: 'Adobe Premiere Pro', type: 'file'}, {key: 'j', name: 'Adobe Fresco', type: 'file'}, {key: 'k', name: 'Adobe Dreamweaver', type: 'file'}, {key: 'l', name: 'Adobe Connect', type: 'file'}, {key: 'm', name: 'Pictures', type: 'folder'}, {key: 'n', name: 'Adobe Acrobat', type: 'file'} ]; // taken from https://random.dog/ const itemsWithThumbs = [ {key: '1', title: 'swimmer', url: 'https://random.dog/b2fe2172-cf11-43f4-9c7f-29bd19601712.jpg'}, {key: '2', title: 'chocolate', url: 'https://random.dog/2032518a-eec8-4102-9d48-3dca5a26eb23.png'}, {key: '3', title: 'good boi', url: 'https://random.dog/191091b2-7d69-47af-9f52-6605063f1a47.jpg'}, {key: '4', title: 'polar bear', url: 'https://random.dog/c22c077e-a009-486f-834c-a19edcc36a17.jpg'}, {key: '5', title: 'cold boi', url: 'https://random.dog/093a41da-e2c0-4535-a366-9ef3f2013f73.jpg'}, {key: '6', title: 'pilot', url: 'https://random.dog/09f8ecf4-c22b-49f4-af24-29fb5c8dbb2d.jpg'}, {key: '7', title: 'nerd', url: 'https://random.dog/1a0535a6-ca89-4059-9b3a-04a554c0587b.jpg'}, {key: '8', title: 'audiophile', url: 'https://random.dog/32367-2062-4347.jpg'} ]; function renderEmptyState() { return ( <IllustratedMessage> <svg width="150" height="103" viewBox="0 0 150 103"> <path d="M133.7,8.5h-118c-1.9,0-3.5,1.6-3.5,3.5v27c0,0.8,0.7,1.5,1.5,1.5s1.5-0.7,1.5-1.5V23.5h119V92c0,0.3-0.2,0.5-0.5,0.5h-118c-0.3,0-0.5-0.2-0.5-0.5V69c0-0.8-0.7-1.5-1.5-1.5s-1.5,0.7-1.5,1.5v23c0,1.9,1.6,3.5,3.5,3.5h118c1.9,0,3.5-1.6,3.5-3.5V12C137.2,10.1,135.6,8.5,133.7,8.5z M15.2,21.5V12c0-0.3,0.2-0.5,0.5-0.5h118c0.3,0,0.5,0.2,0.5,0.5v9.5H15.2z M32.6,16.5c0,0.6-0.4,1-1,1h-10c-0.6,0-1-0.4-1-1s0.4-1,1-1h10C32.2,15.5,32.6,15.9,32.6,16.5z M13.6,56.1l-8.6,8.5C4.8,65,4.4,65.1,4,65.1c-0.4,0-0.8-0.1-1.1-0.4c-0.6-0.6-0.6-1.5,0-2.1l8.6-8.5l-8.6-8.5c-0.6-0.6-0.6-1.5,0-2.1c0.6-0.6,1.5-0.6,2.1,0l8.6,8.5l8.6-8.5c0.6-0.6,1.5-0.6,2.1,0c0.6,0.6,0.6,1.5,0,2.1L15.8,54l8.6,8.5c0.6,0.6,0.6,1.5,0,2.1c-0.3,0.3-0.7,0.4-1.1,0.4c-0.4,0-0.8-0.1-1.1-0.4L13.6,56.1z" /> </svg> <Heading>No results</Heading> <Content>No results found</Content> </IllustratedMessage> ); } let decorator = (storyFn, context) => { let omittedStories = ['draggable rows', 'dynamic items + renderEmptyState']; return window.screen.width <= 700 || omittedStories.some(omittedName => context.name.includes(omittedName)) ? storyFn() : ( <> <span style={{paddingInline: '10px'}}> <label htmlFor="focus-before">Focus before</label> <input id="focus-before" /> </span> {storyFn()} <span style={{paddingInline: '10px'}}> <label htmlFor="focus-after">Focus after</label> <input id="focus-after" /> </span> </> ); }; storiesOf('ListView', module) .addDecorator(decorator) .add('default', () => ( <ListView width="250px"> <Item textValue="Adobe Photoshop">Adobe Photoshop</Item> <Item textValue="Adobe Illustrator">Adobe Illustrator</Item> <Item textValue="Adobe XD">Adobe XD</Item> </ListView> )) .add('isQuiet', () => ( <ListView width="250px" isQuiet> <Item textValue="Adobe Photoshop">Adobe Photoshop</Item> <Item textValue="Adobe Illustrator">Adobe Illustrator</Item> <Item textValue="Adobe XD">Adobe XD</Item> </ListView> )) .add('with buttons', () => ( <ListView width="300px"> <Item textValue="Adobe Photoshop"> <Content>Adobe Photoshop</Content> <ActionButton>Edit</ActionButton> </Item> <Item textValue="Adobe Illustrator"> <Content>Adobe Illustrator</Content> <ActionButton>Edit</ActionButton> </Item> <Item textValue="Adobe XD"> <Content>Adobe XD</Content> <ActionButton>Edit</ActionButton> </Item> </ListView> )) .add('dynamic items', () => ( <ListView items={items} width="300px" height="250px"> {(item) => ( <Item key={item.key} textValue={item.name}> <Content> {item.name} </Content> <ActionGroup buttonLabelBehavior="hide"> <Item key="edit"> <Edit /> <Text>Edit</Text> </Item> <Item key="delete"> <Delete /> <Text>Delete</Text> </Item> </ActionGroup> </Item> )} </ListView> ) ) .add('dynamic items - small viewport', () => ( <ListView items={items} width="100px" height="250px"> {(item) => ( <Item key={item.key} textValue={item.name}> <Content> {item.name} </Content> <ActionGroup buttonLabelBehavior="hide"> <Item key="edit"> <Edit /> <Text>Edit</Text> </Item> <Item key="delete"> <Delete /> <Text>Delete</Text> </Item> </ActionGroup> </Item> )} </ListView> ) ) .add('falsy ids as keys', () => ( <FalsyIds /> )) .add('empty list', () => ( <ListView width="300px" height="300px" renderEmptyState={renderEmptyState}> {[]} </ListView> )) .add('loading', () => ( <ListView width="300px" height="300px" loadingState="loading"> {[]} </ListView> )) .add('loadingMore', () => ( <ListView width="300px" height="300px" loadingState="loadingMore"> <Item textValue="Adobe Photoshop">Adobe Photoshop</Item> <Item textValue="Adobe Illustrator">Adobe Illustrator</Item> <Item textValue="Adobe XD">Adobe XD</Item> </ListView> )) .add('async listview loading', () => ( <AsyncList /> )) .add('async listview loading with actions', () => ( <AsyncList withActions /> )) .add('density: compact', () => ( <ListView width="250px" density="compact"> <Item textValue="Adobe Photoshop">Adobe Photoshop</Item> <Item textValue="Adobe Illustrator">Adobe Illustrator</Item> <Item textValue="Adobe XD">Adobe XD</Item> </ListView> )) .add('density: spacious', () => ( <ListView width="250px" density="spacious"> <Item textValue="Adobe Photoshop">Adobe Photoshop</Item> <Item textValue="Adobe Illustrator">Adobe Illustrator</Item> <Item textValue="Adobe XD">Adobe XD</Item> </ListView> )) .add('selection: none', () => ( <Example selectionMode="none" /> )) .add('selection: single, checkbox', () => ( <Example selectionMode="single" /> )) .add('selection: single, checkbox, first row disabled', () => ( <Example selectionMode="single" disabledKeys={['Utilities']} /> )) .add('selection: single, checkbox, isQuiet', () => ( <Example selectionMode="single" isQuiet /> )) .add('selection: multiple, checkbox', () => ( <Example selectionMode="multiple" /> )) .add('selection: multiple, checkbox, isQuiet', () => ( <Example selectionMode="multiple" isQuiet /> )) .add('parent folder example', () => ( <Example2 selectionMode="multiple" /> )) .add('actions: ActionButton', () => renderActionsExample(props => <ActionButton {...props}><Copy /></ActionButton>)) .add('actions: ActionGroup', () => renderActionsExample(props => ( <ActionGroup buttonLabelBehavior="hide" {...props}> <Item key="add"> <Add /> <Text>Add</Text> </Item> <Item key="delete"> <Delete /> <Text>Delete</Text> </Item> </ActionGroup> ))) .add('actions: ActionMenu', () => renderActionsExample(props => ( <ActionMenu {...props}> <Item key="add"> <Add /> <Text>Add</Text> </Item> <Item key="delete"> <Delete /> <Text>Delete</Text> </Item> </ActionMenu> ))) .add('actions: ActionGroup + ActionMenu', () => renderActionsExample(props => ( <> <ActionGroup buttonLabelBehavior="hide" {...props}> <Item key="info"> <Info /> <Text>Info</Text> </Item> </ActionGroup> <ActionMenu {...props}> <Item key="add"> <Add /> <Text>Add</Text> </Item> <Item key="delete"> <Delete /> <Text>Delete</Text> </Item> </ActionMenu> </> ))) .add('dynamic items + renderEmptyState', () => (<EmptyTest />)) .add('selectionStyle: highlight', () => ( <ListView width="250px" height={400} onSelectionChange={action('onSelectionChange')} selectionStyle="highlight" selectionMode="multiple" items={items}> {item => <Item>{item.name}</Item>} </ListView> )) .add('isQuiet, selectionStyle: highlight', () => ( <ListView width="250px" isQuiet selectionMode="single" selectionStyle="highlight"> <Item textValue="Home">Home</Item> <Item textValue="Apps">Apps</Item> <Item textValue="Document Cloud">Document Cloud</Item> <Item textValue="Creative Cloud">Creative Cloud</Item> <Item textValue="Send & Track">Send & Track</Item> <Item textValue="Reviews">Reviews</Item> </ListView> )) .add('isQuiet, selectionStyle: highlight, multiple', () => ( <ListView width="250px" isQuiet selectionMode="multiple" selectionStyle="highlight"> <Item textValue="Home">Home</Item> <Item textValue="Apps">Apps</Item> <Item textValue="Document Cloud">Document Cloud</Item> <Item textValue="Creative Cloud">Creative Cloud</Item> <Item textValue="Send & Track">Send & Track</Item> <Item textValue="Reviews">Reviews</Item> </ListView> )) .add('selectionStyle: highlight, onAction', () => ( <ListView width="250px" height={400} onSelectionChange={action('onSelectionChange')} selectionStyle="highlight" selectionMode="multiple" items={items} onAction={action('onAction')}> {item => <Item>{item.name}</Item>} </ListView> )) .add('selectionMode: none, onAction', () => ( <ListView width="250px" height={400} onSelectionChange={action('onSelectionChange')} selectionMode="none" items={items} onAction={action('onAction')}> {item => <Item>{item.name}</Item>} </ListView> )) .add('selectionStyle: checkbox, onAction', () => ( <ListView width="250px" height={400} onSelectionChange={action('onSelectionChange')} selectionMode="multiple" selectionStyle="checkbox" items={[...Array(20).keys()].map(k => ({key: k, name: `Item ${k}`}))} onAction={action('onAction')}> {item => <Item>{item.name}</Item>} </ListView> )) .add('with ActionBar', () => <ActionBarExample />) .add('with emphasized ActionBar', () => <ActionBarExample isEmphasized />) .add('thumbnails', () => ( <ListView width="250px" items={itemsWithThumbs}> { (item) => <Item textValue={item.title}><Image src={item.url} /><Content>{item.title}</Content><Text slot="description">JPG</Text></Item> } </ListView> )); storiesOf('ListView/Drag and Drop', module) .add( 'Drag out of list', () => ( <Flex direction="row" wrap alignItems="center"> <input /> <Droppable /> <DragExample dragHookOptions={{onDragStart: action('dragStart'), onDragEnd: action('dragEnd')}} /> </Flex> ) ) .add( 'Drag within list (Reorder)', () => ( <Flex direction="row" wrap alignItems="center"> <ReorderExample /> </Flex> ) ) .add( 'Drag into folder', () => ( <Flex direction="row" wrap alignItems="center"> <DragIntoItemExample /> </Flex> ) ) .add( 'Drag between lists', () => ( <Flex direction="row" wrap alignItems="center"> <DragBetweenListsExample /> </Flex> ) ) .add( 'Drag between lists (Root only)', () => ( <Flex direction="row" wrap alignItems="center"> <DragBetweenListsRootOnlyExample /> </Flex> ), {description: {data: 'Folders are non-draggable.'}} ) .add( 'draggable rows, onAction', () => ( <Flex direction="row" wrap alignItems="center"> <input /> <Droppable /> <DragExample listViewProps={{onAction: action('onAction')}} dragHookOptions={{onDragStart: action('dragStart'), onDragEnd: action('dragEnd')}} /> </Flex> ), {description: {data: 'Folders are non-draggable.'}} ) .add( 'draggable rows, selectionStyle: highlight, onAction', () => ( <Flex direction="row" wrap alignItems="center"> <input /> <Droppable /> <DragExample listViewProps={{selectionStyle: 'highlight', onAction: action('onAction')}} dragHookOptions={{onDragStart: action('dragStart'), onDragEnd: action('dragEnd')}} /> </Flex> ), {description: {data: 'Folders are non-draggable.'}}) .add('overflowMode="truncate" (default)', () => ( <ListView width="250px" overflowMode="truncate"> <Item textValue="row 1">row 1 with a very very very very very long title</Item> <Item textValue="row 2"> <Text>Text slot with a really really really long name</Text> <Text slot="description">Description slot with a really really long name</Text> </Item> <Item textValue="row 3"> <Content>Content slot with really really long name</Content> </Item> <Item textValue="row 4"> <Link >Link slot with a very very very very long name</Link> </Item> </ListView> )) .add('overflowMode="wrap"', () => ( <ListView width="250px" overflowMode="wrap"> <Item textValue="row 1">row 1 with a very very very very very long title</Item> <Item textValue="row 2"> <Text>Text slot with a really really really long name</Text> <Text slot="description">Description slot with a really really long name</Text> </Item> <Item textValue="row 3"> <Content>Content slot with really really long name</Content> </Item> <Item textValue="row 4"> <Link >Link slot with a very very very very long name</Link> </Item> </ListView> )); function Example(props?) { return ( <ListView width="250px" onSelectionChange={action('onSelectionChange')} {...props}> <Item key="Utilities" textValue="Utilities" hasChildItems> <Content>Utilities</Content> </Item> <Item textValue="Adobe Photoshop">Adobe Photoshop</Item> <Item textValue="Adobe Illustrator">Adobe Illustrator</Item> <Item textValue="Adobe XD">Adobe XD</Item> </ListView> ); } function Example2(props?) { return ( <ListView width="250px" onSelectionChange={action('onSelectionChange')} onAction={action('onAction')} {...props}> <Item key="Utilities" hasChildItems>Utilities</Item> <Item textValue="Adobe Photoshop">Adobe Photoshop</Item> <Item textValue="Adobe Illustrator">Adobe Illustrator</Item> <Item textValue="Adobe XD">Adobe XD</Item> </ListView> ); } function renderActionsExample(renderActions, props?) { return ( <ListView width="300px" selectionMode="single" {...props} onAction={action('onAction')} onSelectionChange={keys => console.log('sel', keys)}> <Item key="a" textValue="Utilities" hasChildItems> <Folder /> <Content>Utilities</Content> <Text slot="description">16 items</Text> {renderActions({onPress: action('actionPress')})} </Item> <Item key="b" textValue="Adobe Photoshop"> <Content>Adobe Photoshop</Content> <Text slot="description">Application</Text> {renderActions({onPress: action('actionPress')})} </Item> <Item key="c" textValue="Adobe Illustrator"> <Content>Adobe Illustrator</Content> <Text slot="description">Application</Text> {renderActions({onPress: action('actionPress')})} </Item> <Item key="d" textValue="Adobe XD"> <Content>Adobe XD</Content> <Text slot="description">Application</Text> {renderActions({onPress: action('actionPress')})} </Item> </ListView> ); } let i = 0; function EmptyTest() { const [items, setItems] = useState([]); const [divProps, setDivProps] = useState({}); useEffect(() => { let newItems = []; for (i = 0; i < 20; i++) { newItems.push({key: i, name: `Item ${i}`}); } setItems(newItems); }, []); const renderEmpty = () => ( <IllustratedMessage> <NoSearchResults /> <Heading>No items</Heading> </IllustratedMessage> ); let hasDivProps = Object.keys(divProps).length > 0; return ( <div> <Flex direction="row"> <div {...divProps}> <ListView items={items} width="250px" height={hasDivProps ? null : '500px'} renderEmptyState={renderEmpty}> { item => ( <Item key={item.key}> <Content>{item.name}</Content> </Item> ) } </ListView> </div> <div style={{paddingLeft: '10px'}}> <ActionButton isDisabled={hasDivProps} onPress={() => setDivProps({style: {display: 'flex', flexGrow: 1, minWidth: '200px', maxHeight: '500px'}})}> Use flex div wrapper (no set height) </ActionButton> <Flex gap={10} marginTop={10}> <ActionButton onPress={() => setItems([])}> Clear All </ActionButton> <ActionButton onPress={() => { let newArr = [...items]; newArr.push({key: i++, name: `Item ${i}`}); setItems(newArr); }}> Add 1 </ActionButton> <ActionButton onPress={() => { let newItems = [...items]; setItems(newItems.slice(0, 4)); }}> Slice (0, 4) </ActionButton> </Flex> </div> </Flex> </div> ); } export function DragExample(props?) { let {listViewProps, dragHookOptions} = props; let getItems = (keys) => [...keys].map(key => { let item = items.find(item => item.key === key); return { 'text/plain': item.name }; }); let dragHooks = useDragHooks({ getItems, ...dragHookOptions }); return ( <ListView aria-label="draggable list view" width="300px" selectionMode="multiple" items={items} disabledKeys={['f']} dragHooks={dragHooks} {...listViewProps}> {(item: any) => ( <Item key={item.key} textValue={item.name} hasChildItems={item.type === 'folder'}> {item.type === 'folder' && <Folder />} {item.key === 'a' && <FileTxt />} <Content> {item.name} </Content> {item.key === 'b' && <Text slot="description">Beta</Text>} <ActionMenu onAction={action('onAction')}> <Item key="edit" textValue="Edit"> <Edit /> <Text>Edit</Text> </Item> <Item key="delete" textValue="Delete"> <Delete /> <Text>Delete</Text> </Item> </ActionMenu> </Item> )} </ListView> ); } export function ReorderExample() { let onDropAction = action('onDrop'); let list = useListData({ initialItems: [ {id: '1', type: 'item', textValue: 'One'}, {id: '2', type: 'item', textValue: 'Two'}, {id: '3', type: 'item', textValue: 'Three'}, {id: '4', type: 'item', textValue: 'Four'}, {id: '5', type: 'item', textValue: 'Five'}, {id: '6', type: 'item', textValue: 'Six'} ] }); // Use a random drag type so the items can only be reordered within this list and not dragged elsewhere. let dragType = React.useMemo(() => `keys-${Math.random().toString(36).slice(2)}`, []); let onMove = (keys: React.Key[], target: ItemDropTarget) => { if (target.dropPosition === 'before') { list.moveBefore(target.key, keys); } else { list.moveAfter(target.key, keys); } }; let dragHooks = useDragHooks({ getItems(keys) { return [...keys].map(key => ({ [dragType]: JSON.stringify(key) })); }, onDragStart: action('dragStart'), onDragEnd: action('dragEnd') }); let dropHooks = useDropHooks({ async onDrop(e) { if (e.target.type !== 'root' && e.target.dropPosition !== 'on') { let keys = []; for (let item of e.items) { if (item.kind === 'text' && item.types.has(dragType)) { let key = JSON.parse(await item.getText(dragType)); keys.push(key); } } onDropAction(e); onMove(keys, e.target); } }, getDropOperation(target) { if (target.type === 'root' || target.dropPosition === 'on') { return 'cancel'; } return 'move'; } }); return ( <ListView aria-label="reorderable list view" selectionMode="multiple" width="300px" items={list.items} disabledKeys={['2']} dragHooks={dragHooks} dropHooks={dropHooks}> {(item: any) => ( <Item key={item.id} textValue={item.textValue}> Item {item.id} </Item> )} </ListView> ); } export function DragIntoItemExample() { let onDropAction = action('onDrop'); let list = useListData({ initialItems: [ {id: '0', type: 'folder', textValue: 'Folder', childNodes: []}, {id: '1', type: 'item', textValue: 'One'}, {id: '2', type: 'item', textValue: 'Two'}, {id: '3', type: 'item', textValue: 'Three'}, {id: '4', type: 'item', textValue: 'Four'}, {id: '5', type: 'item', textValue: 'Five'}, {id: '6', type: 'item', textValue: 'Six'} ] }); // Use a random drag type so the items can only be reordered within this list and not dragged elsewhere. let dragType = React.useMemo(() => `keys-${Math.random().toString(36).slice(2)}`, []); let onMove = (keys: React.Key[], target: ItemDropTarget) => { let folderItem = list.getItem(target.key); let draggedItems = keys.map((key) => list.getItem(key)); list.update(target.key, {...folderItem, childNodes: [...folderItem.childNodes, ...draggedItems]}); list.remove(...keys); }; let dragHooks = useDragHooks({ getItems(keys) { return [...keys].map(key => ({ [dragType]: JSON.stringify(key) })); }, onDragStart: action('dragStart'), onDragEnd: action('dragEnd') }); let dropHooks = useDropHooks({ onDrop: async e => { if (e.target.type !== 'root' && e.target.dropPosition === 'on') { let keys = []; for (let item of e.items) { if (item.kind === 'text' && item.types.has(dragType)) { let key = JSON.parse(await item.getText(dragType)); keys.push(key); } } onDropAction(e); if (!keys.includes(e.target.key)) { onMove(keys, e.target); } } }, getDropOperation(target) { if (target.type === 'root' || target.dropPosition !== 'on' || !list.getItem(target.key).childNodes) { return 'cancel'; } return 'move'; } }); return ( <ListView aria-label="Drop into list view item example" selectionMode="multiple" width="300px" items={list.items} disabledKeys={['2']} dragHooks={dragHooks} dropHooks={dropHooks}> {(item: any) => ( <Item key={item.id} textValue={item.textValue} hasChildItems={item.type === 'folder'}> <Text>{item.type === 'folder' ? 'Drop items here' : `Item ${item.textValue}`}</Text> {item.type === 'folder' && <> <Folder /> <Text slot="description">contains {item.childNodes.length} dropped item(s)</Text> </> } </Item> )} </ListView> ); } export function DragBetweenListsExample() { let onDropAction = action('onDrop'); let list1 = useListData({ initialItems: [ {id: '1', type: 'item', textValue: 'One'}, {id: '2', type: 'item', textValue: 'Two'}, {id: '3', type: 'item', textValue: 'Three'}, {id: '4', type: 'item', textValue: 'Four'}, {id: '5', type: 'item', textValue: 'Five'}, {id: '6', type: 'item', textValue: 'Six'} ] }); let list2 = useListData({ initialItems: [ {id: '7', type: 'item', textValue: 'Seven'}, {id: '8', type: 'item', textValue: 'Eight'}, {id: '9', type: 'item', textValue: 'Nine'}, {id: '10', type: 'item', textValue: 'Ten'}, {id: '11', type: 'item', textValue: 'Eleven'}, {id: '12', type: 'item', textValue: 'Twelve'} ] }); let onMove = (keys: React.Key[], target: ItemDropTarget) => { let sourceList = list1.getItem(keys[0]) ? list1 : list2; let destinationList = list1.getItem(target.key) ? list1 : list2; if (sourceList === destinationList) { // Handle dragging within same list if (target.dropPosition === 'before') { sourceList.moveBefore(target.key, keys); } else { sourceList.moveAfter(target.key, keys); } } else { // Handle dragging between lists if (target.dropPosition === 'before') { destinationList.insertBefore(target.key, ...keys.map(key => sourceList.getItem(key))); } else { destinationList.insertAfter(target.key, ...keys.map(key => sourceList.getItem(key))); } sourceList.remove(...keys); } }; let dragHooks = useDragHooks({ getItems(keys) { return [...keys].map(key => ({ [dragType]: JSON.stringify(key) })); }, onDragStart: action('dragStart'), onDragEnd: action('dragEnd') }); // Use a random drag type so the items can only be reordered within the two lists and not dragged elsewhere. let dragType = React.useMemo(() => `keys-${Math.random().toString(36).slice(2)}`, []); let dropHooks = useDropHooks({ onDrop: async e => { if (e.target.type !== 'root' && e.target.dropPosition !== 'on') { let keys = []; for (let item of e.items) { if (item.kind === 'text' && item.types.has(dragType)) { let key = JSON.parse(await item.getText(dragType)); keys.push(key); } } onDropAction(e); onMove(keys, e.target); } }, getDropOperation(target) { if (target.type === 'root' || target.dropPosition === 'on') { return 'cancel'; } return 'move'; } }); return ( <> <Flex direction="column" margin="size-100"> <Text alignSelf="center">List 1</Text> <ListView aria-label="First list view" selectionMode="multiple" width="300px" items={list1.items} disabledKeys={['2']} dragHooks={dragHooks} dropHooks={dropHooks}> {(item: any) => ( <Item key={item.id} textValue={item.textValue}> Item {item.textValue} </Item> )} </ListView> </Flex> <Flex direction="column" margin="size-100"> <Text alignSelf="center">List 2</Text> <ListView aria-label="Second list view" selectionMode="multiple" width="300px" items={list2.items} disabledKeys={['2']} dragHooks={dragHooks} dropHooks={dropHooks}> {(item: any) => ( <Item key={item.id} textValue={item.textValue}> Item {item.textValue} </Item> )} </ListView> </Flex> </> ); } export function DragBetweenListsRootOnlyExample() { let onDropAction = action('onDrop'); let list1 = useListData({ initialItems: [ {id: '1', type: 'item', textValue: 'One'}, {id: '2', type: 'item', textValue: 'Two'}, {id: '3', type: 'item', textValue: 'Three'}, {id: '4', type: 'item', textValue: 'Four'}, {id: '5', type: 'item', textValue: 'Five'}, {id: '6', type: 'item', textValue: 'Six'} ] }); let list2 = useListData({ initialItems: [ {id: '7', type: 'item', textValue: 'Seven'}, {id: '8', type: 'item', textValue: 'Eight'}, {id: '9', type: 'item', textValue: 'Nine'}, {id: '10', type: 'item', textValue: 'Ten'}, {id: '11', type: 'item', textValue: 'Eleven'}, {id: '12', type: 'item', textValue: 'Twelve'} ] }); let onMove = (keys: React.Key[]) => { let sourceList = list1.getItem(keys[0]) ? list1 : list2; let destinationList = sourceList === list1 ? list2 : list1; destinationList.append(...keys.map(key => sourceList.getItem(key))); sourceList.remove(...keys); }; let dragHooksFirst = useDragHooks({ getItems(keys) { return [...keys].map(key => ({ 'list1': JSON.stringify(key) })); }, onDragStart: action('dragStart'), onDragEnd: action('dragEnd') }); let dragHooksSecond = useDragHooks({ getItems(keys) { return [...keys].map(key => ({ 'list2': JSON.stringify(key) })); }, onDragStart: action('dragStart'), onDragEnd: action('dragEnd') }); let dropHooksFirst = useDropHooks({ onDrop: async e => { if (e.target.type === 'root') { let keys = []; for (let item of e.items) { if (item.kind === 'text' && item.types.has('list2')) { let key = JSON.parse(await item.getText('list2')); keys.push(key); } } onDropAction(e); onMove(keys); } }, getDropOperation(target, types) { if (target.type === 'root' && types.has('list2')) { return 'move'; } return 'cancel'; } }); let dropHooksSecond = useDropHooks({ onDrop: async e => { if (e.target.type === 'root') { let keys = []; for (let item of e.items) { if (item.kind === 'text' && item.types.has('list1')) { let key = JSON.parse(await item.getText('list1')); keys.push(key); } } onDropAction(e); onMove(keys); } }, getDropOperation(target, types) { if (target.type === 'root' && types.has('list1')) { return 'move'; } return 'cancel'; } }); return ( <> <Flex direction="column" margin="size-100"> <Text alignSelf="center">List 1</Text> <ListView aria-label="First list view" selectionMode="multiple" width="300px" items={list1.items} disabledKeys={['2']} dragHooks={dragHooksFirst} dropHooks={dropHooksFirst}> {(item: any) => ( <Item key={item.id} textValue={item.textValue}> Item {item.textValue} </Item> )} </ListView> </Flex> <Flex direction="column" margin="size-100"> <Text alignSelf="center">List 2</Text> <ListView aria-label="Second list view" selectionMode="multiple" width="300px" items={list2.items} disabledKeys={['2']} dragHooks={dragHooksSecond} dropHooks={dropHooksSecond}> {(item: any) => ( <Item key={item.id} textValue={item.textValue}> Item {item.textValue} </Item> )} </ListView> </Flex> </> ); } function AsyncList(props) { interface StarWarsChar { name: string, url: string } let list = useAsyncList<StarWarsChar>({ async load({signal, cursor}) { if (cursor) { cursor = cursor.replace(/^http:\/\//i, 'https://'); } // Slow down load so progress circle can appear await new Promise(resolve => setTimeout(resolve, 1500)); let res = await fetch(cursor || 'https://swapi.py4e.com/api/people/?search=', {signal}); let json = await res.json(); return { items: json.results, cursor: json.next }; } }); return ( <ListView selectionMode="multiple" aria-label="example async loading list" width="size-6000" height="size-3000" items={list.items} loadingState={list.loadingState} onLoadMore={list.loadMore}> {(item) => { if (props.withActions) { return <Item key={item.name} textValue={item.name}><Content>{item.name}</Content><ActionButton>Edit</ActionButton></Item>; } return <Item key={item.name} textValue={item.name}>{item.name}</Item>; }} </ListView> ); } function FalsyIds() { let items = [ {id: 1, name: 'key=1'}, {id: 0, name: 'key=0'} ]; return ( <ListView width="250px" height={400} selectionMode="multiple" onSelectionChange={action('onSelectionChange')} items={items} onAction={action('onAction')}> {item => <Item>{item.name}</Item>} </ListView> ); } function ActionBarExample(props?) { let list = useListData({ initialItems: [ {key: 0, name: 'Adobe Photoshop'}, {key: 1, name: 'Adobe Illustrator'}, {key: 2, name: 'Adobe XD'} ], initialSelectedKeys: [0] }); return ( <ActionBarContainer height={300}> <ListView selectionMode="multiple" selectedKeys={list.selectedKeys} onSelectionChange={list.setSelectedKeys} items={list.items} width="250px"> {item => <Item>{item.name}</Item>} </ListView> <ActionBar selectedItemCount={list.selectedKeys === 'all' ? list.items.length : list.selectedKeys.size} onAction={action('onAction')} onClearSelection={() => list.setSelectedKeys(new Set([]))} {...props}> <Item key="edit"> <Edit /> <Text>Edit</Text> </Item> <Item key="copy"> <Copy /> <Text>Copy</Text> </Item> <Item key="delete"> <Delete /> <Text>Delete</Text> </Item> </ActionBar> </ActionBarContainer> ); }
the_stack
'use strict' // **Github:** https://github.com/fidm/quic // // **License:** MIT import { inspect } from 'util' import { randomBytes } from 'crypto' import { AddressInfo } from 'dgram' import { QuicError } from './error' import { kVal } from './symbol' import { Visitor, BufferVisitor, readUnsafeUInt, writeUnsafeUInt } from './common' const QUIC_VERSIONS = ['Q039'] export enum SessionType { SERVER = 0, CLIENT = 1, } export enum FamilyType { IPv4 = 'IPv4', IPv6 = 'IPv6', } /** * Returns supported version. */ export function getVersion (): string { return QUIC_VERSIONS[0] } /** * Returns supported versions array. */ export function getVersions (): string[] { return QUIC_VERSIONS.slice() } /** * Chooses the best version in the overlap of ours and theirs. */ export function chooseVersion (theirs: string[]): string { for (const v of theirs) { if (isSupportedVersion(v)) { return v } } return '' } /** * Returns true if the server supports this version. */ export function isSupportedVersion (version: string): boolean { return QUIC_VERSIONS.includes(version) } /** Protocol representing a base protocol. */ export abstract class Protocol { static fromBuffer (_bufv: BufferVisitor, _len?: number): Protocol { throw new Error(`class method "fromBuffer" is not implemented`) } protected readonly [kVal]: any constructor (val: any) { this[kVal] = val } abstract equals (other: Protocol): boolean abstract byteLen (arg?: any): number abstract writeTo (bufv: BufferVisitor, arg?: any): BufferVisitor abstract valueOf (): any abstract toString (): string [inspect.custom] (_depth: any, _options: any): string { return `<${this.constructor.name} ${this.toString()}>` } } const ConnectionIDReg = /^[0-9a-f]{16}$/ /** ConnectionID representing a connectionID. */ export class ConnectionID extends Protocol { static fromBuffer (bufv: BufferVisitor): ConnectionID { bufv.walk(8) if (bufv.isOutside()) { throw new QuicError('QUIC_INTERNAL_ERROR') } return new ConnectionID(bufv.buf.toString('hex', bufv.start, bufv.end)) } static random (): ConnectionID { return new ConnectionID(randomBytes(8).toString('hex')) } constructor (id: string) { if (!ConnectionIDReg.test(id)) { throw new Error('invalid Connection ID') } super(id) } /** * @return {string} - 16 length hex string */ valueOf (): string { return this[kVal] } equals (other: ConnectionID): boolean { return (other instanceof ConnectionID) && this.valueOf() === other.valueOf() } byteLen (): number { return 8 } writeTo (bufv: BufferVisitor): BufferVisitor { bufv.walk(8) bufv.buf.write(this[kVal], bufv.start, 8, 'hex') return bufv } toString (): string { return this[kVal] } } /** PacketNumber representing a packetNumber. */ export class PacketNumber extends Protocol { // The lower 8, 16, 32, or 48 bits of the packet number, based on which // FLAG_?BYTE_SEQUENCE_NUMBER flag is set in the public flags. // Each Regular Packet (as opposed to the Special public reset and version // negotiation packets) is assigned a packet number by the sender. // The first packet sent by an endpoint shall have a packet number of 1, and // each subsequent packet shall have a packet number one larger than that of the previous packet. static flagToByteLen (flagBits: number): number { if ((flagBits & 0b11) !== flagBits) { throw new Error('invalid flagBits') } return flagBits > 0 ? (flagBits * 2) : 1 } static fromBuffer (bufv: BufferVisitor, len: number): PacketNumber { bufv.walk(len) if (bufv.isOutside()) { throw new QuicError('QUIC_INTERNAL_ERROR') } return new PacketNumber(bufv.buf.readUIntBE(bufv.start, len)) } constructor (val: number) { if (!Number.isInteger(val) || val < 1 || val > 0xffffffffffff) { throw new Error(`invalid PacketNumber val ${val}`) } super(val) } valueOf (): number { return this[kVal] } nextNumber (): PacketNumber { return new PacketNumber(this[kVal] + 1) } prevNumber (): PacketNumber { return new PacketNumber(this[kVal] - 1) } isLimitReached (): boolean { // If a QUIC endpoint transmits a packet with a packet number of (2^64-1), // that packet must include a CONNECTION_CLOSE frame with an error code of QUIC_SEQUENCE_NUMBER_LIMIT_REACHED, // and the endpoint must not transmit any additional packets. return this[kVal] >= 0xffffffffffff // but here 2^48 } delta (other: PacketNumber): number { return Math.abs(this.valueOf() - other.valueOf()) } closestTo (a: PacketNumber, b: PacketNumber): PacketNumber { return this.delta(a) < this.delta(b) ? a : b } flagBits (): number { const byteLen = this.byteLen() if (byteLen === 1) { return 0 } return byteLen / 2 } equals (other: PacketNumber): boolean { return (other instanceof PacketNumber) && this.valueOf() === other.valueOf() } byteLen (isFull: boolean = false): number { if (!isFull) { const value = this[kVal] if (value <= 0xff) { return 1 } else if (value <= 0xffff) { return 2 } else if (value <= 0xffffffff) { return 4 } } return 6 } writeTo (bufv: BufferVisitor, isFull: boolean = false): BufferVisitor { const len = isFull ? 6 : this.byteLen() bufv.walk(len) bufv.buf.writeUIntBE(this[kVal], bufv.start, len) return bufv } toString (): string { return String(this[kVal]) } } /** StreamID representing a streamID. */ export class StreamID extends Protocol { // the Stream-ID must be even if the server initiates the stream, and odd if the client initiates the stream. // 0 is not a valid Stream-ID. Stream 1 is reserved for the crypto handshake, // which should be the first client-initiated stream. /** * 2 bits -> 8/8, 16/8, 24/8, 32/8 */ static flagToByteLen (flagBits: number): number { if ((flagBits & 0b11) !== flagBits) { throw new Error('invalid flagBits') } return flagBits + 1 } static fromBuffer (bufv: BufferVisitor, len: number): StreamID { bufv.walk(len) if (bufv.isOutside()) { throw new QuicError('QUIC_INVALID_STREAM_DATA') } return new StreamID(bufv.buf.readUIntBE(bufv.start, len)) } constructor (id: number) { // StreamID(0) is used by WINDOW_UPDATE if (!Number.isInteger(id) || id < 0 || id > 0xffffffff) { throw new Error(`invalid Stream ID ${id}`) } super(id) } valueOf (): number { return this[kVal] } flagBits (): number { return this.byteLen() - 1 } nextID (): StreamID { const value = this[kVal] + 2 return new StreamID(value <= 0xffffffff ? value : (value - 0xffffffff)) } prevID (): StreamID { return new StreamID(this[kVal] - 2) } equals (other: StreamID): boolean { return (other instanceof StreamID) && this.valueOf() === other.valueOf() } byteLen (isFull: boolean = false): number { if (!isFull) { const value = this[kVal] if (value <= 0xff) { return 1 } else if (value <= 0xffff) { return 2 } else if (value <= 0xffffff) { return 3 } } return 4 } writeTo (bufv: BufferVisitor, isFull: boolean = false): BufferVisitor { const len = isFull ? 4 : this.byteLen() bufv.walk(len) bufv.buf.writeUIntBE(this[kVal], bufv.start, len) return bufv } toString (): string { return String(this[kVal]) } } /** Offset representing a data offset. */ export class Offset extends Protocol { /** * 3 bits -> 0, 16/8, 24/8, 32/8, 40/8, 48/8, 56/8, 64/8 */ static flagToByteLen (flagBits: number): number { if ((flagBits & 0b111) !== flagBits) { throw new Error('invalid flagBits') } return flagBits > 0 ? (flagBits + 1) : 0 } static fromBuffer (bufv: BufferVisitor, len: number): Offset { bufv.walk(len) if (bufv.isOutside()) { throw new QuicError('QUIC_INTERNAL_ERROR') } return new Offset(readUnsafeUInt(bufv.buf, bufv.start, len)) } constructor (offset: number) { if (!Number.isSafeInteger(offset) || offset < 0) { throw new Error(`invalid Offset ${offset}`) } super(offset) } valueOf (): number { return this[kVal] } equals (other: Offset): boolean { return this.valueOf() === other.valueOf() } gt (other: Offset): boolean { return this.valueOf() > other.valueOf() } byteLen (isFull: boolean = false): number { if (!isFull) { const value = this[kVal] if (value === 0) { return 0 } else if (value <= 0xffff) { return 2 } else if (value <= 0xffffff) { return 3 } else if (value <= 0xffffffff) { return 4 } else if (value <= 0xffffffffff) { return 5 } else if (value <= 0xffffffffffff) { return 6 } return 7 // value should small than 0xffffffffffffff } return 8 } /** * 0, 16/8, 24/8, 32/8, 40/8, 48/8, 56/8, 64/8 -> 3 bits */ flagBits (): number { const byteLen = this.byteLen() if (byteLen === 0) { return 0 } return byteLen > 1 ? (byteLen - 1) : 1 } writeTo (bufv: BufferVisitor, isFull: boolean = false): BufferVisitor { const len = isFull ? 8 : this.byteLen() bufv.walk(len) if (bufv.isOutside()) { throw new QuicError('QUIC_INTERNAL_ERROR') } writeUnsafeUInt(bufv.buf, this[kVal], bufv.start, len) return bufv } toString (): string { return String(this[kVal]) } } /** SocketAddress representing a socket address. */ export class SocketAddress extends Protocol { static fromBuffer (bufv: BufferVisitor): SocketAddress { const obj: AddressInfo = { address: '', family: FamilyType.IPv4, port: 0, } bufv.walk(2) if (bufv.isOutside()) { throw new QuicError('QUIC_INTERNAL_ERROR') } const family = bufv.buf.readUInt16BE(bufv.start) if (family === 0x02) { obj.family = FamilyType.IPv4 bufv.walk(4) if (bufv.isOutside()) { throw new QuicError('QUIC_INTERNAL_ERROR') } obj.address = [ bufv.buf.readUInt8(bufv.start), bufv.buf.readUInt8(bufv.start + 1), bufv.buf.readUInt8(bufv.start + 2), bufv.buf.readUInt8(bufv.start + 3), ].join('.') bufv.walk(2) if (bufv.isOutside()) { throw new QuicError('QUIC_INTERNAL_ERROR') } obj.port = bufv.buf.readUInt16BE(bufv.start) } else if (family === 0x0a) { obj.family = FamilyType.IPv6 bufv.walk(16) if (bufv.isOutside()) { throw new QuicError('QUIC_INTERNAL_ERROR') } obj.address = [ bufv.buf.readUInt16BE(bufv.start).toString(16), bufv.buf.readUInt16BE(bufv.start + 2).toString(16), bufv.buf.readUInt16BE(bufv.start + 4).toString(16), bufv.buf.readUInt16BE(bufv.start + 6).toString(16), bufv.buf.readUInt16BE(bufv.start + 8).toString(16), bufv.buf.readUInt16BE(bufv.start + 10).toString(16), bufv.buf.readUInt16BE(bufv.start + 12).toString(16), bufv.buf.readUInt16BE(bufv.start + 14).toString(16), ].join(':') bufv.walk(2) if (bufv.isOutside()) { throw new QuicError('QUIC_INTERNAL_ERROR') } obj.port = bufv.buf.readUInt16BE(bufv.start) } else { throw new Error('invalid SocketAddress buffer') } return new SocketAddress(obj) } port: number address: string family: FamilyType constructor (obj: AddressInfo) { if (!isAddress(obj)) { throw new Error(`invalid Socket Address ${JSON.stringify(obj)}`) } let address = obj.address if (address.includes('::')) { const unfold = '0:' if (address.startsWith('::')) { address = '0' + address } else if (address.endsWith('::')) { address += '0' } const _address = address.split(':') _address[_address.indexOf('')] = unfold.repeat(9 - _address.length).slice(0, -1) address = _address.join(':') } super(address) this.port = obj.port this.family = obj.family as FamilyType this.address = address } valueOf () { return { address: this.address, family: this.family as string, port: this.port, } } equals (other: SocketAddress): boolean { if (!(other instanceof SocketAddress)) { return false } return this.family === other.family && this.port === other.port && this.address === other.address } byteLen (): number { return this.family === FamilyType.IPv4 ? 8 : 20 } writeTo (bufv: BufferVisitor): BufferVisitor { const address = this.address if (this.family === FamilyType.IPv4) { bufv.walk(2) bufv.buf.writeUInt16BE(0x02, bufv.start) for (const val of address.split('.')) { bufv.walk(1) bufv.buf.writeUInt8(parseInt(val, 10), bufv.start) } bufv.walk(2) bufv.buf.writeUInt16BE(this.port, bufv.start) } else { bufv.walk(2) bufv.buf.writeUInt16BE(0x0a, bufv.start) for (const val of address.split(':')) { bufv.walk(2) bufv.buf.writeUInt16BE(parseInt(val, 16), bufv.start) } bufv.walk(2) bufv.buf.writeUInt16BE(this.port, bufv.start) } return bufv } toString (): string { return JSON.stringify(this.valueOf()) } } /** QuicTags representing a QUIC tag. */ export class QuicTags extends Protocol { static fromBuffer (bufv: BufferVisitor): QuicTags { bufv.walk(4) const tagName = bufv.buf.readUInt32BE(bufv.start) const quicTag = new QuicTags(tagName) bufv.walk(4) if (bufv.isOutside()) { throw new QuicError('QUIC_INTERNAL_ERROR') } let count = bufv.buf.readInt16LE(bufv.start) const baseOffset = bufv.end + 8 * count const v2 = new Visitor(baseOffset) while (count-- > 0) { bufv.walk(4) if (bufv.isOutside()) { throw new QuicError('QUIC_INTERNAL_ERROR') } const key = bufv.buf.readInt32BE(bufv.start) bufv.walk(4) v2.walk(0) if (bufv.isOutside()) { throw new QuicError('QUIC_INTERNAL_ERROR') } v2.end = baseOffset + bufv.buf.readInt32LE(bufv.start) if (bufv.length < v2.end) { throw new QuicError('QUIC_INTERNAL_ERROR') } const val = bufv.buf.slice(v2.start, v2.end) quicTag.set(key, val) } bufv.reset(v2.end, v2.end) return quicTag } name: Tag tags: Map<Tag, Buffer> constructor (name: Tag) { super(name) this.name = name this.tags = new Map() } valueOf () { const tags: any = {} for (const [key, value] of this.tags) { tags[Tag[key]] = value } return { name: Tag[this.name], tags, } } get size (): number { return this.tags.size } [Symbol.iterator] () { return this.tags[Symbol.iterator]() } set (key: Tag, val: Buffer): void { this.tags.set(key, val) } get (key: Tag): Buffer | undefined { return this.tags.get(key) } has (key: Tag): boolean { return this.tags.has(key) } equals (other: QuicTags): boolean { if (!(other instanceof QuicTags)) { return false } if (this.name !== other.name || this.tags.size !== other.tags.size) { return false } for (const key of this.tags.keys()) { const a = this.tags.get(key) const b = other.tags.get(key) if (a == null || b == null || !a.equals(b)) { return false } } return true } byteLen (): number { let byteLen = 8 for (const buf of this.tags.values()) { byteLen += 8 + buf.length } return byteLen } writeTo (bufv: BufferVisitor): BufferVisitor { bufv.walk(4) bufv.buf.writeUInt32BE(this.name, bufv.start) bufv.walk(4) const size = this.tags.size bufv.buf.writeUInt16LE(size, bufv.start) bufv.buf.writeUInt16LE(0, bufv.start + 2) let baseOffset = 0 const v = new Visitor(bufv.end + 8 * size) const keys = Array.from(this.tags.keys()) keys.sort((a, b) => a - b) for (const key of keys) { const val = this.tags.get(key) if (val == null) { throw new QuicError('QUIC_INTERNAL_ERROR') } bufv.walk(4) bufv.buf.writeUInt32BE(key, bufv.start) bufv.walk(4) baseOffset += val.length bufv.buf.writeUInt32LE(baseOffset, bufv.start) v.walk(val.length) val.copy(bufv.buf, v.start, 0, val.length) } bufv.reset(v.end, v.end) return bufv } toString (): string { return JSON.stringify(this.valueOf()) } } export enum Tag { CHLO = toTag('C', 'H', 'L', 'O'), // Client hello SHLO = toTag('S', 'H', 'L', 'O'), // Server hello SCFG = toTag('S', 'C', 'F', 'G'), // Server config REJ = toTag('R', 'E', 'J', '\u{0}'), // Reject SREJ = toTag('S', 'R', 'E', 'J'), // Stateless reject CETV = toTag('C', 'E', 'T', 'V'), // Client encrypted tag-value pairs PRST = toTag('P', 'R', 'S', 'T'), // Public reset SCUP = toTag('S', 'C', 'U', 'P'), // Server config update ALPN = toTag('A', 'L', 'P', 'N'), // Application-layer protocol // Key exchange methods P256 = toTag('P', '2', '5', '6'), // ECDH, Curve P-256 C255 = toTag('C', '2', '5', '5'), // ECDH, Curve25519 // AEAD algorithms AESG = toTag('A', 'E', 'S', 'G'), // AES128 + GCM-12 CC20 = toTag('C', 'C', '2', '0'), // ChaCha20 + Poly1305 RFC7539 // Socket receive buffer SRBF = toTag('S', 'R', 'B', 'F'), // Socket receive buffer // Congestion control feedback types QBIC = toTag('Q', 'B', 'I', 'C'), // TCP cubic // Connection options (COPT) values AFCW = toTag('A', 'F', 'C', 'W'), // Auto-tune flow control receive windows. IFW5 = toTag('I', 'F', 'W', '5'), // Set initial size of stream flow control receive window to 32KB. (2^5 KB). IFW6 = toTag('I', 'F', 'W', '6'), // Set initial size of stream flow control receive window to 64KB. (2^6 KB). IFW7 = toTag('I', 'F', 'W', '7'), // Set initial size of stream flow control receive window to 128KB. (2^7 KB). IFW8 = toTag('I', 'F', 'W', '8'), // Set initial size of stream flow control receive window to 256KB. (2^8 KB). IFW9 = toTag('I', 'F', 'W', '9'), // Set initial size of stream flow control receive window to 512KB. (2^9 KB). IFWA = toTag('I', 'F', 'W', 'a'), // Set initial size of stream flow control receive window to 1MB. (2^0xa KB). TBBR = toTag('T', 'B', 'B', 'R'), // Reduced Buffer Bloat TCP '1RTT' = toTag('1', 'R', 'T', 'T'), // STARTUP in BBR for 1 RTT '2RTT' = toTag('2', 'R', 'T', 'T'), // STARTUP in BBR for 2 RTTs LRTT = toTag('L', 'R', 'T', 'T'), // Exit STARTUP in BBR on loss BBRR = toTag('B', 'B', 'R', 'R'), // Rate-based recovery in BBR BBR1 = toTag('B', 'B', 'R', '1'), // Ack aggregatation v1 BBR2 = toTag('B', 'B', 'R', '2'), // Ack aggregatation v2 RENO = toTag('R', 'E', 'N', 'O'), // Reno Congestion Control TPCC = toTag('P', 'C', 'C', '\u{0}'), // Performance-Oriented Congestion Control BYTE = toTag('B', 'Y', 'T', 'E'), // TCP cubic or reno in bytes IW03 = toTag('I', 'W', '0', '3'), // Force ICWND to 3 IW10 = toTag('I', 'W', '1', '0'), // Force ICWND to 10 IW20 = toTag('I', 'W', '2', '0'), // Force ICWND to 20 IW50 = toTag('I', 'W', '5', '0'), // Force ICWND to 50 '1CON' = toTag('1', 'C', 'O', 'N'), // Emulate a single connection NTLP = toTag('N', 'T', 'L', 'P'), // No tail loss probe NCON = toTag('N', 'C', 'O', 'N'), // N Connection Congestion Ctrl NRTO = toTag('N', 'R', 'T', 'O'), // CWND reduction on loss UNDO = toTag('U', 'N', 'D', 'O'), // Undo any pending retransmits if they're likely spurious. TIME = toTag('T', 'I', 'M', 'E'), // Time based loss detection ATIM = toTag('A', 'T', 'I', 'M'), // Adaptive time loss detection MIN1 = toTag('M', 'I', 'N', '1'), // Min CWND of 1 packet MIN4 = toTag('M', 'I', 'N', '4'), // Min CWND of 4 packets, with a min rate of 1 BDP. TLPR = toTag('T', 'L', 'P', 'R'), // Tail loss probe delay of 0.5RTT. ACKD = toTag('A', 'C', 'K', 'D'), // Ack decimation style acking. AKD2 = toTag('A', 'K', 'D', '2'), // Ack decimation tolerating out of order packets. AKD3 = toTag('A', 'K', 'D', '3'), // Ack decimation style acking with 1/8 RTT acks. AKD4 = toTag('A', 'K', 'D', '4'), // Ack decimation with 1/8 RTT tolerating out of order. AKDU = toTag('A', 'K', 'D', 'U'), // Unlimited number of packets receieved before acking SSLR = toTag('S', 'S', 'L', 'R'), // Slow Start Large Reduction. NPRR = toTag('N', 'P', 'R', 'R'), // Pace at unity instead of PRR '5RTO' = toTag('5', 'R', 'T', 'O'), // Close connection on 5 RTOs '3RTO' = toTag('3', 'R', 'T', 'O'), // Close connection on 3 RTOs CTIM = toTag('C', 'T', 'I', 'M'), // Client timestamp in seconds since UNIX epoch. DHDT = toTag('D', 'H', 'D', 'T'), // Disable HPACK dynamic table. CONH = toTag('C', 'O', 'N', 'H'), // Conservative Handshake Retransmissions. LFAK = toTag('L', 'F', 'A', 'K'), // Don't invoke FACK on the first ack. // TODO(fayang): Remove this connection option in QUIC_VERSION_37, in which // MAX_HEADER_LIST_SIZE settings frame should be supported. SMHL = toTag('S', 'M', 'H', 'L'), // Support MAX_HEADER_LIST_SIZE settings frame. CCVX = toTag('C', 'C', 'V', 'X'), // Fix Cubic convex bug. CBQT = toTag('C', 'B', 'Q', 'T'), // Fix CubicBytes quantization. BLMX = toTag('B', 'L', 'M', 'X'), // Fix Cubic BetaLastMax bug. CPAU = toTag('C', 'P', 'A', 'U'), // Allow Cubic per-ack-updates. NSTP = toTag('N', 'S', 'T', 'P'), // No stop waiting frames. // Optional support of truncated Connection IDs. If sent by a peer, the value // is the minimum number of bytes allowed for the connection ID sent to the // peer. TCID = toTag('T', 'C', 'I', 'D'), // Connection ID truncation. // Multipath option. MPTH = toTag('M', 'P', 'T', 'H'), // Enable multipath. NCMR = toTag('N', 'C', 'M', 'R'), // Do not attempt connection migration. // Enable bandwidth resumption experiment. BWRE = toTag('B', 'W', 'R', 'E'), // Bandwidth resumption. BWMX = toTag('B', 'W', 'M', 'X'), // Max bandwidth resumption. BWRS = toTag('B', 'W', 'R', 'S'), // Server bandwidth resumption. BWS2 = toTag('B', 'W', 'S', '2'), // Server bw resumption v2. // Enable path MTU discovery experiment. MTUH = toTag('M', 'T', 'U', 'H'), // High-target MTU discovery. MTUL = toTag('M', 'T', 'U', 'L'), // Low-target MTU discovery. // Tags for async signing experiments ASYN = toTag('A', 'S', 'Y', 'N'), // Perform asynchronous signing SYNC = toTag('S', 'Y', 'N', 'C'), // Perform synchronous signing FHL2 = toTag('F', 'H', 'L', '2'), // Force head of line blocking. // Proof types (i.e. certificate types) // NOTE: although it would be silly to do so, specifying both kX509 and kX59R // is allowed and is equivalent to specifying only kX509. X509 = toTag('X', '5', '0', '9'), // X.509 certificate, all key types X59R = toTag('X', '5', '9', 'R'), // X.509 certificate, RSA keys only CHID = toTag('C', 'H', 'I', 'D'), // Channel ID. // Client hello tags VER = toTag('V', 'E', 'R', '\u{0}'), // Version NONC = toTag('N', 'O', 'N', 'C'), // The client's nonce NONP = toTag('N', 'O', 'N', 'P'), // The client's proof nonce KEXS = toTag('K', 'E', 'X', 'S'), // Key exchange methods AEAD = toTag('A', 'E', 'A', 'D'), // Authenticated encryption algorithms COPT = toTag('C', 'O', 'P', 'T'), // Connection options CLOP = toTag('C', 'L', 'O', 'P'), // Client connection options ICSL = toTag('I', 'C', 'S', 'L'), // Idle network timeout SCLS = toTag('S', 'C', 'L', 'S'), // Silently close on timeout MSPC = toTag('M', 'S', 'P', 'C'), // Max streams per connection. MIDS = toTag('M', 'I', 'D', 'S'), // Max incoming dynamic streams IRTT = toTag('I', 'R', 'T', 'T'), // Estimated initial RTT in us. SWND = toTag('S', 'W', 'N', 'D'), // Server's Initial congestion window. SNI = toTag('S', 'N', 'I', '\u{0}'), // Server name indication PUBS = toTag('P', 'U', 'B', 'S'), // Public key values SCID = toTag('S', 'C', 'I', 'D'), // Server config id ORBT = toTag('O', 'B', 'I', 'T'), // Server orbit. PDMD = toTag('P', 'D', 'M', 'D'), // Proof demand. PROF = toTag('P', 'R', 'O', 'F'), // Proof (signature). CCS = toTag('C', 'C', 'S', '\u{0}'), // Common certificate set CCRT = toTag('C', 'C', 'R', 'T'), // Cached certificate EXPY = toTag('E', 'X', 'P', 'Y'), // Expiry STTL = toTag('S', 'T', 'T', 'L'), // Server Config TTL SFCW = toTag('S', 'F', 'C', 'W'), // Initial stream flow control receive window. CFCW = toTag('C', 'F', 'C', 'W'), // Initial session/connection flow control receive window. UAID = toTag('U', 'A', 'I', 'D'), // Client's User Agent ID. XLCT = toTag('X', 'L', 'C', 'T'), // Expected leaf certificate. TBKP = toTag('T', 'B', 'K', 'P'), // Token Binding key params. // Token Binding tags TB10 = toTag('T', 'B', '1', '0'), // TB draft 10 with P256. // Rejection tags RREJ = toTag('R', 'R', 'E', 'J'), // Reasons for server sending // Stateless Reject tags RCID = toTag('R', 'C', 'I', 'D'), // Server-designated connection ID // Server hello tags CADR = toTag('C', 'A', 'D', 'R'), // Client IP address and port ASAD = toTag('A', 'S', 'A', 'D'), // Alternate Server IP address and port. // CETV tags CIDK = toTag('C', 'I', 'D', 'K'), // ChannelID key CIDS = toTag('C', 'I', 'D', 'S'), // ChannelID signature // Public reset tags RNON = toTag('R', 'N', 'O', 'N'), // Public reset nonce proof RSEQ = toTag('R', 'S', 'E', 'Q'), // Rejected packet number // Universal tags PAD = toTag('P', 'A', 'D', '\u{0}'), // Padding // Server push tags SPSH = toTag('S', 'P', 'S', 'H'), // Support server push. // clang-format on // These tags have a special form so that they appear either at the beginning // or the end of a handshake message. Since handshake messages are sorted by // tag value, the tags with 0 at the end will sort first and those with 255 at // the end will sort last. // // The certificate chain should have a tag that will cause it to be sorted at // the end of any handshake messages because it's likely to be large and the // client might be able to get everything that it needs from the small values at // the beginning. // // Likewise tags with random values should be towards the beginning of the // message because the server mightn't hold state for a rejected client hello // and therefore the client may have issues reassembling the rejection message // in the event that it sent two client hellos. SNO = toTag('S', 'N', 'O', '\u{0}'), // The server's nonce STK = toTag('S', 'T', 'K', '\u{0}'), // Source-address token CRT = toTag('C', 'R', 'T', '\u{ff}'), // Certificate chain CSCT = toTag('C', 'S', 'C', 'T'), // Signed cert timestamp (RFC6962) of leaf cert. } function toTag (a: string, b: string, c: string, d: string): number { return a.charCodeAt(0) * (0xffffff + 1) + b.charCodeAt(0) * (0xffff + 1) + c.charCodeAt(0) * (0xff + 1) + d.charCodeAt(0) } function isAddress (address: AddressInfo): boolean { return address != null && address.port >= 0 && Number.isInteger(address.port) && typeof address.address === 'string' && (address.family === FamilyType.IPv4 || address.family === FamilyType.IPv6) }
the_stack
import { ArgumentNode, DocumentNode, execute, FieldNode, FragmentDefinitionNode, getNamedType, GraphQLError, GraphQLField, GraphQLInputObjectType, GraphQLInputType, GraphQLList, GraphQLNamedType, GraphQLNonNull, GraphQLOutputType, GraphQLScalarType, GraphQLSchema, OperationDefinitionNode, ResponsePath, SelectionSetNode, VariableDefinitionNode } from 'graphql'; import { getNonNullType, walkFields } from '../../graphql/schema-utils'; import { LinkConfig } from '../../extended-schema/extended-schema'; import { arrayToObject, intersect, modifyPropertyAtPath, throwError } from '../../utils/utils'; import { getFieldAsQueryParts, SlimGraphQLResolveInfo } from '../../graphql/field-as-query'; import { addFieldSelectionSafely, addVariableDefinitionSafely, createFieldNode, createNestedArgumentWithVariableNode, createSelectionChain } from '../../graphql/language-utils'; import { isArray } from 'util'; import { assertSuccessfulResult } from '../../graphql/execution-result'; import { FieldErrorValue, moveErrorsToData } from '../../graphql/errors-in-result'; import { prefixGraphQLErrorPath } from './error-paths'; import { WeavingError, WeavingErrorConsumer } from '../../config/errors'; export const FILTER_ARG = 'filter'; export const ORDER_BY_ARG = 'orderBy'; export const FIRST_ARG = 'first'; export const SKIP_ARG = 'skip'; export function parseLinkTargetPath(path: string, schema: GraphQLSchema): { field: GraphQLField<any, any>, fieldPath: string[] } | undefined { const fieldPath = path.split('.'); const queryType = schema.getQueryType(); if (!queryType) { return undefined; } const field = walkFields(queryType, fieldPath); if (!field) { return undefined; } return {field, fieldPath}; } async function basicResolve(params: { targetFieldPath: ReadonlyArray<string>, payloadSelectionSet: SelectionSetNode, args?: ArgumentNode[], variableDefinitions: VariableDefinitionNode[], variableValues: { [name: string]: any }, fragments: ReadonlyArray<FragmentDefinitionNode>, context: any, schema: GraphQLSchema, path: ResponsePath, operationName?: string }): Promise<any> { const {payloadSelectionSet, variableValues, variableDefinitions, context, schema, targetFieldPath, args, fragments} = params; // wrap selection in field node chain on target, and add the argument with the key field const outerFieldNames = [...targetFieldPath]; const innerFieldName = outerFieldNames.pop()!; // this removes the last element of outerFields in-place const innerFieldNode: FieldNode = { ...createFieldNode(innerFieldName), selectionSet: payloadSelectionSet, arguments: args }; const innerSelectionSet: SelectionSetNode = { kind: 'SelectionSet', selections: [innerFieldNode] }; const selectionSet = createSelectionChain(outerFieldNames, innerSelectionSet); // create document const operation: OperationDefinitionNode = { kind: 'OperationDefinition', operation: 'query', name: params.operationName ? { kind: 'Name', value: params.operationName } : undefined, variableDefinitions, selectionSet }; const document: DocumentNode = { kind: 'Document', definitions: [ operation, ...fragments ] }; // execute // note: don't need to run query pipeline on this document because it will be passed to the unlinked schema // which will in turn peform their query pipeline (starting from the next module onwards) on the query in the // proxy resolver. Query pipeline modules before this module have already been exectued on the whole query // (because the linked fields obviously have not been truncated there) // TODO invesitage nested links, might be necessary to execute this particiular query pipeline module const result = await execute(schema, document, {} /* root */, context, variableValues); const resultData = assertSuccessfulResult(moveErrorsToData(result, e => prefixGraphQLErrorPath(e, params.path, targetFieldPath.length))); // unwrap return targetFieldPath.reduce((data, fieldName) => { if (!(fieldName in data)) { throw new Error(`Property "${fieldName}" missing in result of "${targetFieldPath.join('.')}"`); } const result = data![fieldName]; if (result instanceof FieldErrorValue) { const err = result.getError(); const message = `Field "${targetFieldPath.join('.')}" reported error: ${err.message}`; if (err instanceof GraphQLError) { // see if we got some useful location information to keep // but don't do this if we don't have location info, because graphql 0.13 won't add the location info of the path if it's a GraphQLError const hasLocationInfo = (err.positions && err.positions.length) || (err.nodes && err.nodes.some(node => !!node.loc)); if (hasLocationInfo) { throw new GraphQLError(message, err.nodes, err.source, err.positions, err.path, err); } } throw new Error(message); } return result; }, resultData); } /** * Fetches a list of objects by their keys * * @param params.keys an array of key values * @param params.info the resolve info that specifies the structure of the query * @return an array of objects, with 1:1 mapping to the keys */ export async function fetchLinkedObjects(params: { keys: any[], keyType: GraphQLScalarType, linkConfig: LinkConfig, unlinkedSchema: GraphQLSchema, context: any, info: SlimGraphQLResolveInfo }): Promise<any[]> { const {unlinkedSchema, keys, keyType, linkConfig, info, context} = params; const {fieldPath: targetFieldPath} = parseLinkTargetPath(linkConfig.field, unlinkedSchema) || throwError(`Link target field as ${linkConfig.field} which does not exist in the schema`); /** * Fetches one object, or a list of objects in batch mode, according to the query underlying the resolveInfo * @param key the key * @param resolveInfo the resolveInfo from the request * @param context graphql execution context * @returns {Promise<void>} */ async function fetchSingular(key: any) { const {fragments, ...originalParts} = getFieldAsQueryParts(info); // add variable const varType = getNonNullType(keyType); const varNameBase = linkConfig.argument.split('.').pop()!; const {variableDefinitions, name: varName} = addVariableDefinitionSafely(originalParts.variableDefinitions, varNameBase, varType); const variableValues = { ...originalParts.variableValues, [varName]: key }; return await basicResolve({ targetFieldPath, schema: unlinkedSchema, context, variableDefinitions, variableValues, fragments, args: [ createNestedArgumentWithVariableNode(linkConfig.argument, varName) ], payloadSelectionSet: originalParts.selectionSet, path: info.path, operationName: info.operation.name ? info.operation.name.value : undefined }); } /** * Fetches one object, or a list of objects in batch mode, according to the query underlying the resolveInfo * @param keyOrKeys either a single key of a list of keys, depending on link.batchMode * @param resolveInfo the resolveInfo from the request * @param context graphql execution context * @returns {Promise<void>} */ async function fetchBatchOneToOne(keys: any) { const {fragments, ...originalParts} = getFieldAsQueryParts(info); // add variable const varType = new GraphQLNonNull(new GraphQLList(getNonNullType(keyType))); const varNameBase = linkConfig.argument.split('.').pop()!; const {variableDefinitions, name: varName} = addVariableDefinitionSafely(originalParts.variableDefinitions, varNameBase, varType); const variableValues = { ...originalParts.variableValues, [varName]: keys }; return basicResolve({ targetFieldPath, schema: unlinkedSchema, context, variableDefinitions, variableValues, fragments, args: [ createNestedArgumentWithVariableNode(linkConfig.argument, varName) ], payloadSelectionSet: originalParts.selectionSet, path: info.path, operationName: info.operation.name ? info.operation.name.value : undefined }); } /** * Fetches one object, or a list of objects in batch mode, according to the query underlying the resolveInfo * @param keyOrKeys either a single key of a list of keys, depending on link.batchMode * @param resolveInfo the resolveInfo from the request * @param context graphql execution context * @returns {Promise<void>} */ async function fetchBatchWithKeyField(keyOrKeys: any) { const {fragments, ...originalParts} = getFieldAsQueryParts(info); // add variable const varType = new GraphQLNonNull(new GraphQLList(getNonNullType(keyType))); const varNameBase = linkConfig.argument.split('.').pop()!; const {variableDefinitions, name: varName} = addVariableDefinitionSafely(originalParts.variableDefinitions, varNameBase, varType); const variableValues = { ...originalParts.variableValues, [varName]: keyOrKeys }; // add keyField const {alias: keyFieldAlias, selectionSet: payloadSelectionSet} = addFieldSelectionSafely(originalParts.selectionSet, linkConfig.keyField!, arrayToObject(fragments, f => f.name.value)); const data = await basicResolve({ targetFieldPath, schema: unlinkedSchema, context, variableDefinitions, variableValues, fragments, args: [ createNestedArgumentWithVariableNode(linkConfig.argument, varName) ], payloadSelectionSet, path: info.path, operationName: info.operation.name ? info.operation.name.value : undefined }); checkObjectsAndKeysForErrorValues(data, keyFieldAlias, linkConfig.keyField!); // unordered case: endpoints does not preserve order, so we need to remap based on a key field // first, create a lookup table from id to item if (!isArray(data)) { throw new Error(`Result of ${targetFieldPath.join('.')} expected to be an array because batchMode is true`); } const map = new Map((<any[]>data).map(item => <[any, any]>[item[keyFieldAlias], item])); // Then, use the lookup table to efficiently order the result return (keyOrKeys as any[]).map(key => map.get(key)); } if (!linkConfig.batchMode) { return keys.map(key => fetchSingular(key)); } if (linkConfig.keyField) { return fetchBatchWithKeyField(keys); } return fetchBatchOneToOne(keys); } export async function fetchJoinedObjects(params: { keys: any[], additionalFilter: any, orderBy?: string, first?: number, skip?: number, filterType: GraphQLInputType, keyType: GraphQLScalarType, linkConfig: LinkConfig, unlinkedSchema: GraphQLSchema, context: any, info: SlimGraphQLResolveInfo }): Promise<{ orderedObjects: {[key:string]:any}[], objectsByID: Map<string, {[key:string]:any}>, keyFieldAlias: string }> { const {unlinkedSchema, additionalFilter, orderBy, filterType, linkConfig, info, context, keys} = params; const {fragments, ...originalParts} = getFieldAsQueryParts(info); const {fieldPath: targetFieldPath} = parseLinkTargetPath(linkConfig.field, unlinkedSchema) || throwError(() => new WeavingError(`Target field ${JSON.stringify(linkConfig.field)} does not exist`)); const [filterArgumentName, ...keyFieldPath] = linkConfig.argument.split('.'); if (!keyFieldPath) { throw new WeavingError(`argument ${JSON.stringify(linkConfig.argument)} on link field needs to be a path of the form argumentName.fieldPath, where fieldPath is dot-separated.`); } const filterValue = modifyPropertyAtPath(additionalFilter, existingKeys => existingKeys ? intersect(existingKeys, keys) : keys, keyFieldPath); // add variable const varNameBase = info.fieldNodes[0].name.value + 'Filter'; const {variableDefinitions, name: varName} = addVariableDefinitionSafely(originalParts.variableDefinitions, varNameBase, filterType); const variableValues = { ...originalParts.variableValues, [varName]: filterValue }; // add keyField const {alias: keyFieldAlias, selectionSet: payloadSelectionSet} = addFieldSelectionSafely(originalParts.selectionSet, linkConfig.keyField!, arrayToObject(fragments, f => f.name.value)); const filterArgument: ArgumentNode = { kind: 'Argument', name: { kind: 'Name', value: filterArgumentName }, value: { kind: 'Variable', name: { kind: 'Name', value: varName } } }; let args = [filterArgument]; if (orderBy) { const orderByArg: ArgumentNode = { kind: 'Argument', name: { kind: 'Name', value: ORDER_BY_ARG }, value: { kind: 'EnumValue', value: orderBy } }; args = [...args, orderByArg]; } if (params.first != undefined) { const firstArg: ArgumentNode = { kind: 'Argument', name: { kind: 'Name', value: FIRST_ARG }, value: { kind: 'IntValue', value: params.first + "" } }; args = [...args, firstArg]; } if (params.skip) { const skipArg: ArgumentNode = { kind: 'Argument', name: { kind: 'Name', value: SKIP_ARG }, value: { kind: 'IntValue', value: params.skip + "" } }; args = [...args, skipArg]; } const data = await basicResolve({ targetFieldPath, schema: unlinkedSchema, context, variableDefinitions, variableValues, fragments, args, payloadSelectionSet, path: info.path, operationName: info.operation.name ? info.operation.name.value : undefined }); if (!isArray(data)) { throw new Error(`Result of ${targetFieldPath.join('.')} expected to be an array because batchMode is true`); } checkObjectsAndKeysForErrorValues(data, keyFieldAlias, linkConfig.keyField!); const objectsByID = new Map((<any[]>data).map(item => <[any, any]>[item[keyFieldAlias], item])); return { orderedObjects: data, objectsByID, keyFieldAlias }; } export function getLinkArgumentType(linkConfig: LinkConfig, targetField: GraphQLField<any, any>): GraphQLInputType { const [filterArgumentName, ...keyFieldPath] = linkConfig.argument.split('.'); const arg = targetField.args.filter(arg => arg.name == filterArgumentName)[0]; if (!arg) { throw new WeavingError(`Argument ${JSON.stringify(filterArgumentName)} does not exist on target field ${JSON.stringify(linkConfig.field)}`); } const type = arg.type; return keyFieldPath.reduce((type, fieldName) => { if (!(type instanceof GraphQLInputObjectType) || !(fieldName in type.getFields())) { throw new Error(`Argument path ${JSON.stringify(linkConfig.argument)} cannot be resolved: ${type} does not have a field ${JSON.stringify(fieldName)}`); } return type.getFields()[fieldName].type }, type); } export function getKeyType(config: { linkConfig: LinkConfig, linkFieldType: GraphQLOutputType, linkFieldName: string, parentObjectType: GraphQLNamedType, targetField: GraphQLField<any, any>, reportError: WeavingErrorConsumer}) { const linkKeyType = getNamedType(config.linkFieldType); const argumentType = getNamedType(getLinkArgumentType(config.linkConfig, config.targetField)); if (!(linkKeyType instanceof GraphQLScalarType)) { throw new WeavingError(`Type of @link field must be scalar type or list/non-null type of scalar type, but is ${config.linkFieldType}`); } if (!(argumentType instanceof GraphQLScalarType)) { throw new WeavingError(`Type of argument field ${JSON.stringify(config.linkConfig.argument)} must be scalar type or list/non-null-type of a scalar type, but is ${argumentType}`); } // comparing the names here. Can't use reference equality on the types because mapped and unmapped types are confused here. // We don't rename scalars in this module, so this is fine if (argumentType.name != linkKeyType.name) { config.reportError(new WeavingError(`Link field ${JSON.stringify(config.linkFieldName)} is of type ${linkKeyType}, but argument ${JSON.stringify(config.linkConfig.argument)} on target field ${JSON.stringify(config.linkConfig.field)} has type ${argumentType}`)); } // Even if the types do not match, we can still continue and just pass the link value as argument. For ID/String/Int mismatches, this should not be a problem. // However, we need to use the argument type as variable name, so this will be returned return argumentType; } function checkObjectsAndKeysForErrorValues(objects: any, keyFieldAlias: string, keyFieldName: string) { // Don't try to access the key field on this error object - just throw it if (objects instanceof FieldErrorValue) { throw objects.getError(); } const erroredKeys: FieldErrorValue[] = objects .map((item: any) => item[keyFieldAlias]) .filter((keyValue: any) => keyValue instanceof FieldErrorValue); if (erroredKeys.length) { throw new Error(`Errors retrieving key field ${JSON.stringify(keyFieldName)}:\n\n${erroredKeys.map(error => error.getError().message).join('\n\n')}`); } }
the_stack
import * as dagre from 'dagre'; import ErrorIcon from '@material-ui/icons/Error'; import PendingIcon from '@material-ui/icons/Schedule'; import RunningIcon from '../icons/statusRunning'; import SkippedIcon from '@material-ui/icons/SkipNext'; import SuccessIcon from '@material-ui/icons/CheckCircle'; import CachedIcon from '@material-ui/icons/Cached'; import TerminatedIcon from '../icons/statusTerminated'; import Tooltip from '@material-ui/core/Tooltip'; import UnknownIcon from '@material-ui/icons/Help'; import { color } from '../Css'; export function statusToBgColor(status?: NodePhase, nodeMessage?: string): string { status = checkIfTerminated(status, nodeMessage); switch (status) { case NodePhase.ERROR: // fall through case NodePhase.FAILED: return statusBgColors.error; case NodePhase.PENDING: return statusBgColors.notStarted; case NodePhase.TERMINATING: // fall through case NodePhase.RUNNING: return statusBgColors.running; case NodePhase.SUCCEEDED: return statusBgColors.succeeded; case NodePhase.CACHED: return statusBgColors.cached; case NodePhase.SKIPPED: // fall through case NodePhase.TERMINATED: return statusBgColors.terminatedOrSkipped; case NodePhase.UNKNOWN: // fall through default: console.log("Status to background color: status not recognized") return statusBgColors.notStarted; } } export function formatDateString(date: Date | string | undefined): string { if (typeof date === 'string') { return new Date(date).toLocaleString(); } else { return date ? date.toLocaleString() : '-'; } } export function checkIfTerminated(status?: NodePhase, nodeMessage?: string): NodePhase | undefined { // Argo considers terminated runs as having "Failed", so we have to examine the failure message to // determine why the run failed. if (status === NodePhase.FAILED && nodeMessage === 'terminated') { status = NodePhase.TERMINATED; } return status; } export function statusToIcon( status?: NodePhase, startDate?: Date | string, endDate?: Date | string, nodeMessage?: string, ): JSX.Element { status = checkIfTerminated(status, nodeMessage); // tslint:disable-next-line:variable-name let IconComponent: any = UnknownIcon; let iconColor = color.inactive; let title = 'Unknown status'; switch (status) { case NodePhase.ERROR: IconComponent = ErrorIcon; iconColor = color.errorText; title = 'Error while running this resource'; break; case NodePhase.FAILED: IconComponent = ErrorIcon; iconColor = color.errorText; title = 'Resource failed to execute'; break; case NodePhase.PENDING: IconComponent = PendingIcon; iconColor = color.weak; title = 'Pending execution'; break; case NodePhase.RUNNING: IconComponent = RunningIcon; iconColor = color.blue; title = 'Running'; break; case NodePhase.TERMINATING: IconComponent = RunningIcon; iconColor = color.blue; title = 'Run is terminating'; break; case NodePhase.SKIPPED: IconComponent = SkippedIcon; title = 'Execution has been skipped for this resource'; break; case NodePhase.SUCCEEDED: IconComponent = SuccessIcon; iconColor = color.success; title = 'Executed successfully'; break; case NodePhase.COMPLETED: IconComponent = SuccessIcon; iconColor = color.success; title = 'Executed successfully'; break; case NodePhase.CACHED: // This is not argo native, only applies to node. IconComponent = CachedIcon; iconColor = color.success; title = 'Execution was skipped and outputs were taken from cache'; break; case NodePhase.TERMINATED: IconComponent = TerminatedIcon; iconColor = color.terminated; title = 'Run was manually terminated'; break; case NodePhase.PIPELINERUNTIMEOUT: IconComponent = ErrorIcon; iconColor = color.errorText; title = 'Pipeline run timeout'; break; case NodePhase.COULDNTGETCONDITION: IconComponent = ErrorIcon; iconColor = color.errorText; title = 'Could not retrieve the condition'; break; case NodePhase.CONDITIONCHECKFAILED: IconComponent = SkippedIcon; title = 'Execution has been skipped due to a Condition check failure'; break; case NodePhase.PIPELINERUNCANCELLED: IconComponent = TerminatedIcon; iconColor = color.terminated; title = 'PipelineRun cancelled'; break; case NodePhase.PIPELINERUNCOULDNTCANCEL: IconComponent = TerminatedIcon; iconColor = color.terminated; title = 'PipelineRun could not cancel'; break; case NodePhase.TASKRUNCANCELLED: IconComponent = TerminatedIcon; iconColor = color.terminated; title = 'TaskRun cancelled'; break; case NodePhase.TASKRUNCOULDNTCANCEL: IconComponent = TerminatedIcon; iconColor = color.terminated; title = 'TaskRun could not cancel'; break; case NodePhase.UNKNOWN: break; default: console.log("Status to icon: status not recognized") } return ( <Tooltip title={ <div> <div>{title}</div> {/* These dates may actually be strings, not a Dates due to a bug in swagger's handling of dates */} {startDate && <div>Start: {formatDateString(startDate)}</div>} {endDate && <div>End: {formatDateString(endDate)}</div>} </div> } > <span style={{ height: 18 }}> <IconComponent style={{ color: iconColor, height: 18, width: 18 }} /> </span> </Tooltip> ); } export const Constants = { NODE_HEIGHT: 64, NODE_WIDTH: 172, }; export interface KeyValue<T> extends Array<any> { 0?: string; 1?: T; } export const statusBgColors = { error: '#fce8e6', notStarted: '#f7f7f7', running: '#e8f0fe', succeeded: '#e6f4ea', cached: '#e6f4ea', terminatedOrSkipped: '#f1f3f4', warning: '#fef7f0', }; export enum NodePhase { ERROR = 'Error', FAILED = 'Failed', PENDING = 'Pending', RUNNING = 'Running', SKIPPED = 'Skipped', SUCCEEDED = 'Succeeded', COMPLETED = 'Completed', CACHED = 'Cached', TERMINATING = 'Terminating', PIPELINERUNTIMEOUT = 'PipelineRunTimeout', COULDNTGETCONDITION = 'CouldntGetCondition', CONDITIONCHECKFAILED = 'ConditionCheckFailed', PIPELINERUNCANCELLED = 'PipelineRunCancelled', PIPELINERUNCOULDNTCANCEL = 'PipelineRunCouldntCancel', TASKRUNCANCELLED = 'TaskRunCancelled', TASKRUNCOULDNTCANCEL = 'TaskRunCouldntCancel', TERMINATED = 'Terminated', UNKNOWN = 'Unknown', } export function statusToPhase(nodeStatus: string | undefined): NodePhase { if (!nodeStatus) return 'Unknown' as NodePhase; else if (nodeStatus === 'Completed') return 'Succeeded' as NodePhase; else if (nodeStatus === 'ConditionCheckFailed') return 'Skipped' as NodePhase; else if (nodeStatus === 'CouldntGetCondition') return 'Error' as NodePhase; else if ( nodeStatus === 'PipelineRunCancelled' || nodeStatus === 'PipelineRunCouldntCancel' || nodeStatus === 'TaskRunCancelled' || nodeStatus === 'TaskRunCouldntCancel' ) return 'Terminated' as NodePhase; return nodeStatus as NodePhase; } export enum StorageService { GCS = 'gcs', HTTP = 'http', HTTPS = 'https', MINIO = 'minio', S3 = 's3', } export interface StoragePath { source: StorageService; bucket: string; key: string; } export default class WorkflowParser { public static createRuntimeGraph(workflow: any): dagre.graphlib.Graph { const graph = new dagre.graphlib.Graph(); graph.setGraph({}); graph.setDefaultEdgeLabel(() => ({})); // If a run exists but has no status is available yet return an empty graph if ( workflow && workflow.status && (Object.keys(workflow.status).length === 0 || !workflow.status.taskRuns) ) return graph; const tasks = (workflow['spec']['pipelineSpec']['tasks'] || []).concat( workflow['spec']['pipelineSpec']['finally'] || [], ); const status = workflow['status']['taskRuns']; const pipelineParams = workflow['spec']['params']; const exitHandlers = (workflow['spec']['pipelineSpec']['finally'] || []).map((element: any) => { return element['name']; }) || []; // Create a map from task name to status for every status received const statusMap = new Map<string, any>(); for (const taskRunId of Object.getOwnPropertyNames(status)) { status[taskRunId]['taskRunId'] = taskRunId; if (status[taskRunId]['status']) statusMap.set(status[taskRunId]['pipelineTaskName'], status[taskRunId]); } for (const task of tasks) { // If the task has a status then add it and its edges to the graph if (statusMap.get(task['name'])) { const conditions = task['conditions'] || []; const taskId = statusMap.get(task['name']) && statusMap.get(task['name'])!['status']['podName'] !== '' ? statusMap.get(task['name'])!['status']['podName'] : task['name']; const edges = this.checkParams(statusMap, pipelineParams, task, ''); // Add all of this Task's conditional dependencies as Task dependencies for (const condition of conditions) edges.push(...this.checkParams(statusMap, pipelineParams, condition, taskId)); if (task['runAfter']) { task['runAfter'].forEach((parentTask: any) => { if ( statusMap.get(parentTask) && statusMap.get(parentTask)!['status']['conditions'][0]['type'] === 'Succeeded' ) { const parentId = statusMap.get(parentTask)!['status']['podName']; edges.push({ parent: parentId, child: taskId }); } }); } for (const edge of edges || []) graph.setEdge(edge['parent'], edge['child']); const status = this.getStatus(statusMap.get(task['name'])); const phase = statusToPhase(status); const statusColoring = exitHandlers.includes(task['name']) ? '#fef7f0' : statusToBgColor(phase, ''); // Add a node for the Task graph.setNode(taskId, { height: Constants.NODE_HEIGHT, icon: statusToIcon(status), label: task['name'], statusColoring: statusColoring, width: Constants.NODE_WIDTH, }); } } return graph; } private static checkParams( statusMap: Map<string, any>, pipelineParams: any, component: any, ownerTask: string, ): { parent: string; child: string }[] { const edges: { parent: string; child: string }[] = []; const componentId = ownerTask !== '' ? component['conditionRef'] : statusMap.get(component['name']) && statusMap.get(component['name'])!['status']['podName'] !== '' ? statusMap.get(component['name'])!['status']['podName'] : component['name']; // Adds dependencies from task params for (const param of component['params'] || []) { let paramValue = param['value'] || ''; // If the parameters are passed from the pipeline parameters then grab the value from the pipeline parameters if ( param['value'].substring(0, 9) === '$(params.' && param['value'].substring(param['value'].length - 1) === ')' ) { const paramName = param['value'].substring(9, param['value'].length - 1); for (const pipelineParam of pipelineParams) if (pipelineParam['name'] === paramName) paramValue = pipelineParam['value']; } // If the parameters are passed from the parent task's results and the task is completed then grab the resulting values else if ( param['value'].substring(0, 2) === '$(' && param['value'].substring(param['value'].length - 1) === ')' ) { const paramSplit = param['value'].split('.'); const parentTask = paramSplit[1]; const paramName = paramSplit[paramSplit.length - 1].substring( 0, paramSplit[paramSplit.length - 1].length - 1, ); if ( statusMap.get(parentTask) && statusMap.get(parentTask)!['status']['conditions'][0]['type'] === 'Succeeded' ) { const parentId = statusMap.get(parentTask)!['status']['podName']; edges.push({ parent: parentId, child: ownerTask === '' ? componentId : ownerTask }); // Add the taskResults value to the params value in status for (const result of statusMap.get(parentTask)!['status']['taskResults'] || []) { if (result['name'] === paramName) paramValue = result['value']; } } } // Find the output that matches this input and pull the value if ( statusMap.get(component['name']) && statusMap.get(component['name'])['status']['taskSpec'] ) { for (const statusParam of statusMap.get(component['name'])!['status']['taskSpec']['params']) if (statusParam['name'] === param['name']) statusParam['value'] = paramValue; } } return edges; } public static getStatus(execStatus: any): NodePhase { return execStatus!.status.conditions[0].reason; } }
the_stack
import { ParseTreeVisitor } from "antlr4ts/tree/ParseTreeVisitor"; import { StylesheetContext } from "./LessParser"; import { StatementContext } from "./LessParser"; import { MediaContext } from "./LessParser"; import { MediaQueryListContext } from "./LessParser"; import { MediaQueryContext } from "./LessParser"; import { MediaTypeContext } from "./LessParser"; import { MediaExpressionContext } from "./LessParser"; import { MediaFeatureContext } from "./LessParser"; import { VariableNameContext } from "./LessParser"; import { CommandStatementContext } from "./LessParser"; import { MathCharacterContext } from "./LessParser"; import { MathStatementContext } from "./LessParser"; import { ExpressionContext } from "./LessParser"; import { FuncContext } from "./LessParser"; import { ConditionsContext } from "./LessParser"; import { ConditionContext } from "./LessParser"; import { ConditionStatementContext } from "./LessParser"; import { VariableDeclarationContext } from "./LessParser"; import { ImportDeclarationContext } from "./LessParser"; import { ImportOptionContext } from "./LessParser"; import { ReferenceUrlContext } from "./LessParser"; import { MediaTypesContext } from "./LessParser"; import { RulesetContext } from "./LessParser"; import { BlockContext } from "./LessParser"; import { BlockItemContext } from "./LessParser"; import { MixinDefinitionContext } from "./LessParser"; import { MixinGuardContext } from "./LessParser"; import { MixinDefinitionParamContext } from "./LessParser"; import { MixinReferenceContext } from "./LessParser"; import { SelectorsContext } from "./LessParser"; import { SelectorContext } from "./LessParser"; import { AttribContext } from "./LessParser"; import { NegationContext } from "./LessParser"; import { PseudoContext } from "./LessParser"; import { ElementContext } from "./LessParser"; import { SelectorPrefixContext } from "./LessParser"; import { AttribRelateContext } from "./LessParser"; import { IdentifierContext } from "./LessParser"; import { IdentifierPartContext } from "./LessParser"; import { IdentifierVariableNameContext } from "./LessParser"; import { PropertyContext } from "./LessParser"; import { ValuesContext } from "./LessParser"; import { UrlContext } from "./LessParser"; import { MeasurementContext } from "./LessParser"; /** * This interface defines a complete generic visitor for a parse tree produced * by `LessParser`. * * @param <Result> The return type of the visit operation. Use `void` for * operations with no return type. */ export interface LessParserVisitor<Result> extends ParseTreeVisitor<Result> { /** * Visit a parse tree produced by `LessParser.stylesheet`. * @param ctx the parse tree * @return the visitor result */ visitStylesheet?: (ctx: StylesheetContext) => Result; /** * Visit a parse tree produced by `LessParser.statement`. * @param ctx the parse tree * @return the visitor result */ visitStatement?: (ctx: StatementContext) => Result; /** * Visit a parse tree produced by `LessParser.media`. * @param ctx the parse tree * @return the visitor result */ visitMedia?: (ctx: MediaContext) => Result; /** * Visit a parse tree produced by `LessParser.mediaQueryList`. * @param ctx the parse tree * @return the visitor result */ visitMediaQueryList?: (ctx: MediaQueryListContext) => Result; /** * Visit a parse tree produced by `LessParser.mediaQuery`. * @param ctx the parse tree * @return the visitor result */ visitMediaQuery?: (ctx: MediaQueryContext) => Result; /** * Visit a parse tree produced by `LessParser.mediaType`. * @param ctx the parse tree * @return the visitor result */ visitMediaType?: (ctx: MediaTypeContext) => Result; /** * Visit a parse tree produced by `LessParser.mediaExpression`. * @param ctx the parse tree * @return the visitor result */ visitMediaExpression?: (ctx: MediaExpressionContext) => Result; /** * Visit a parse tree produced by `LessParser.mediaFeature`. * @param ctx the parse tree * @return the visitor result */ visitMediaFeature?: (ctx: MediaFeatureContext) => Result; /** * Visit a parse tree produced by `LessParser.variableName`. * @param ctx the parse tree * @return the visitor result */ visitVariableName?: (ctx: VariableNameContext) => Result; /** * Visit a parse tree produced by `LessParser.commandStatement`. * @param ctx the parse tree * @return the visitor result */ visitCommandStatement?: (ctx: CommandStatementContext) => Result; /** * Visit a parse tree produced by `LessParser.mathCharacter`. * @param ctx the parse tree * @return the visitor result */ visitMathCharacter?: (ctx: MathCharacterContext) => Result; /** * Visit a parse tree produced by `LessParser.mathStatement`. * @param ctx the parse tree * @return the visitor result */ visitMathStatement?: (ctx: MathStatementContext) => Result; /** * Visit a parse tree produced by `LessParser.expression`. * @param ctx the parse tree * @return the visitor result */ visitExpression?: (ctx: ExpressionContext) => Result; /** * Visit a parse tree produced by `LessParser.func`. * @param ctx the parse tree * @return the visitor result */ visitFunc?: (ctx: FuncContext) => Result; /** * Visit a parse tree produced by `LessParser.conditions`. * @param ctx the parse tree * @return the visitor result */ visitConditions?: (ctx: ConditionsContext) => Result; /** * Visit a parse tree produced by `LessParser.condition`. * @param ctx the parse tree * @return the visitor result */ visitCondition?: (ctx: ConditionContext) => Result; /** * Visit a parse tree produced by `LessParser.conditionStatement`. * @param ctx the parse tree * @return the visitor result */ visitConditionStatement?: (ctx: ConditionStatementContext) => Result; /** * Visit a parse tree produced by `LessParser.variableDeclaration`. * @param ctx the parse tree * @return the visitor result */ visitVariableDeclaration?: (ctx: VariableDeclarationContext) => Result; /** * Visit a parse tree produced by `LessParser.importDeclaration`. * @param ctx the parse tree * @return the visitor result */ visitImportDeclaration?: (ctx: ImportDeclarationContext) => Result; /** * Visit a parse tree produced by `LessParser.importOption`. * @param ctx the parse tree * @return the visitor result */ visitImportOption?: (ctx: ImportOptionContext) => Result; /** * Visit a parse tree produced by `LessParser.referenceUrl`. * @param ctx the parse tree * @return the visitor result */ visitReferenceUrl?: (ctx: ReferenceUrlContext) => Result; /** * Visit a parse tree produced by `LessParser.mediaTypes`. * @param ctx the parse tree * @return the visitor result */ visitMediaTypes?: (ctx: MediaTypesContext) => Result; /** * Visit a parse tree produced by `LessParser.ruleset`. * @param ctx the parse tree * @return the visitor result */ visitRuleset?: (ctx: RulesetContext) => Result; /** * Visit a parse tree produced by `LessParser.block`. * @param ctx the parse tree * @return the visitor result */ visitBlock?: (ctx: BlockContext) => Result; /** * Visit a parse tree produced by `LessParser.blockItem`. * @param ctx the parse tree * @return the visitor result */ visitBlockItem?: (ctx: BlockItemContext) => Result; /** * Visit a parse tree produced by `LessParser.mixinDefinition`. * @param ctx the parse tree * @return the visitor result */ visitMixinDefinition?: (ctx: MixinDefinitionContext) => Result; /** * Visit a parse tree produced by `LessParser.mixinGuard`. * @param ctx the parse tree * @return the visitor result */ visitMixinGuard?: (ctx: MixinGuardContext) => Result; /** * Visit a parse tree produced by `LessParser.mixinDefinitionParam`. * @param ctx the parse tree * @return the visitor result */ visitMixinDefinitionParam?: (ctx: MixinDefinitionParamContext) => Result; /** * Visit a parse tree produced by `LessParser.mixinReference`. * @param ctx the parse tree * @return the visitor result */ visitMixinReference?: (ctx: MixinReferenceContext) => Result; /** * Visit a parse tree produced by `LessParser.selectors`. * @param ctx the parse tree * @return the visitor result */ visitSelectors?: (ctx: SelectorsContext) => Result; /** * Visit a parse tree produced by `LessParser.selector`. * @param ctx the parse tree * @return the visitor result */ visitSelector?: (ctx: SelectorContext) => Result; /** * Visit a parse tree produced by `LessParser.attrib`. * @param ctx the parse tree * @return the visitor result */ visitAttrib?: (ctx: AttribContext) => Result; /** * Visit a parse tree produced by `LessParser.negation`. * @param ctx the parse tree * @return the visitor result */ visitNegation?: (ctx: NegationContext) => Result; /** * Visit a parse tree produced by `LessParser.pseudo`. * @param ctx the parse tree * @return the visitor result */ visitPseudo?: (ctx: PseudoContext) => Result; /** * Visit a parse tree produced by `LessParser.element`. * @param ctx the parse tree * @return the visitor result */ visitElement?: (ctx: ElementContext) => Result; /** * Visit a parse tree produced by `LessParser.selectorPrefix`. * @param ctx the parse tree * @return the visitor result */ visitSelectorPrefix?: (ctx: SelectorPrefixContext) => Result; /** * Visit a parse tree produced by `LessParser.attribRelate`. * @param ctx the parse tree * @return the visitor result */ visitAttribRelate?: (ctx: AttribRelateContext) => Result; /** * Visit a parse tree produced by `LessParser.identifier`. * @param ctx the parse tree * @return the visitor result */ visitIdentifier?: (ctx: IdentifierContext) => Result; /** * Visit a parse tree produced by `LessParser.identifierPart`. * @param ctx the parse tree * @return the visitor result */ visitIdentifierPart?: (ctx: IdentifierPartContext) => Result; /** * Visit a parse tree produced by `LessParser.identifierVariableName`. * @param ctx the parse tree * @return the visitor result */ visitIdentifierVariableName?: (ctx: IdentifierVariableNameContext) => Result; /** * Visit a parse tree produced by `LessParser.property`. * @param ctx the parse tree * @return the visitor result */ visitProperty?: (ctx: PropertyContext) => Result; /** * Visit a parse tree produced by `LessParser.values`. * @param ctx the parse tree * @return the visitor result */ visitValues?: (ctx: ValuesContext) => Result; /** * Visit a parse tree produced by `LessParser.url`. * @param ctx the parse tree * @return the visitor result */ visitUrl?: (ctx: UrlContext) => Result; /** * Visit a parse tree produced by `LessParser.measurement`. * @param ctx the parse tree * @return the visitor result */ visitMeasurement?: (ctx: MeasurementContext) => Result; }
the_stack
import { Component, OnInit, ViewChild, OnDestroy, NgZone, TemplateRef } from "@angular/core"; import { PanelScopeEnchantmentService } from "./panel-scope-enchantment.service"; import { ScopeEnchantmentModel, AuxliLineModel, CornerPinModel, PanelScopeTextEditorModel, OuterSphereHasAuxlModel, } from "./model"; import { DraggablePort } from "@ng-public/directive/draggable/draggable.interface"; import { Subscription, BehaviorSubject, fromEvent } from "rxjs"; import { PanelExtendService } from "../panel-extend.service"; import { debounceTime, map, distinctUntilChanged } from "rxjs/operators"; import { ILocation } from "../model"; import { NzContextMenuService, NzDropdownMenuComponent } from "ng-zorro-antd"; import { PanelScopeTextEditorComponent } from "./panel-scope-text-editor/panel-scope-text-editor.component"; import { cloneDeep } from "lodash"; import { DraggableTensileCursorService } from "./draggable-tensile-cursor.service"; import { ClipPathResizeMaskService } from "./clip-path-resize-mask.service"; import { PanelScaleplateService } from "../panel-scaleplate/panel-scaleplate.service"; import { PanelExtendQuickShortcutsService } from "../panel-extend-quick-shortcuts.service"; import { PanelAssistArborService } from "../panel-assist-arbor/panel-assist-arbor.service"; import { PanelWidgetModel } from "../panel-widget/model"; @Component({ selector: "app-panel-scope-enchantment", templateUrl: "./panel-scope-enchantment.component.html", styleUrls: ["./panel-scope-enchantment.component.scss", "./panel-scope-corner-pin.scss"], }) export class PanelScopeEnchantmentComponent implements OnInit, OnDestroy { @ViewChild("widgetContextMenuEl", { static: true }) public widgetContextMenuEl: NzDropdownMenuComponent; @ViewChild("panelScopeTextEditorComponentEl", { static: false }) public panelScopeTextEditorComponentEl: PanelScopeTextEditorComponent; private mouseIntcrementRX$: Subscription; private mouseContextMenu$: Subscription; private profileOuterSphereRX$: Subscription; private profileOuterSphereRotateRX$: Subscription; private rectRX$: Subscription; public get scopeEnchantment(): ScopeEnchantmentModel { return this.panelScopeEnchantmentService.scopeEnchantmentModel; } // 文本编辑器模式 public get panelScopeTextEditor$(): BehaviorSubject<PanelScopeTextEditorModel> { return this.panelScopeEnchantmentService.panelScopeTextEditorModel$; } // 是否允许设置组合,需要选中多个组件才能创建组合 public get isCombination(): boolean { return this.panelAssistArborService.isCombination; } // 是否允许设置打散,需要备选组件当中有组合元素组件 public get isDisperse(): boolean { return this.panelAssistArborService.isDisperse; } // 当前选中的唯一一个widget组件 public get onlyOneWidgetInfo(): PanelWidgetModel { const s = this.scopeEnchantment.outerSphereInsetWidgetList$.value; return Array.isArray(s) && s.length == 1 ? s[0] : null; } public get clipPathService(): ClipPathResizeMaskService { return this.clipPathResizeMaskService } constructor( private readonly clipPathResizeMaskService: ClipPathResizeMaskService, private readonly panelScopeEnchantmentService: PanelScopeEnchantmentService, private readonly panelExtendService: PanelExtendService, private readonly draggableTensileCursorService: DraggableTensileCursorService, private readonly panelExtendQuickShortcutsService: PanelExtendQuickShortcutsService, private readonly panelAssistArborService: PanelAssistArborService, private readonly panelScaleplateService: PanelScaleplateService, private readonly zone: NgZone, private readonly nzContextMenuService: NzContextMenuService ) { // 右键 this.mouseContextMenu$ = this.panelScopeEnchantmentService.launchContextmenu$.subscribe(event => { // 生成右键菜单 if (event) { this.nzContextMenuService.create(event, this.widgetContextMenuEl); } }); this.mouseIntcrementRX$ = this.panelScopeEnchantmentService.launchMouseIncrement$ .pipe() .subscribe((drag: DraggablePort) => { if (drag) { this.handleProfileOuterSphereLocation(drag); } }); this.rectRX$ = this.panelExtendService.selectionRectModel.launchRectData.subscribe(port => { this.handleRectInsetWidget(port); }); // 生成完主轮廓之后计算其余组件的横线和竖线情况并保存起来 // 同时取消文本编辑器模式 this.profileOuterSphereRX$ = this.scopeEnchantment.profileOuterSphere$.pipe().subscribe(value => { const insetW = this.panelScopeEnchantmentService.scopeEnchantmentModel.outerSphereInsetWidgetList$.value; if (value) { this.createAllLineSave(); // 主轮廓创建完成就开启角度值监听 this.openRotateSubject(value); // 根据角度计算主轮廓的offset坐标增量 const cValue = cloneDeep(value); const offsetCoord = this.panelScopeEnchantmentService.handleOuterSphereRotateOffsetCoord(cValue); value.setOffsetAmount(offsetCoord); // 开始记录所有被选组件的位置比例 insetW.forEach(w => { w.profileModel.recordInsetProOuterSphereFourProportion(value); }); } this.panelScopeEnchantmentService.panelScopeTextEditorModel$.next(null); this.clipPathService.emptyClipPath(); }); } ngOnInit() {} ngOnDestroy() { if (this.mouseIntcrementRX$) this.mouseIntcrementRX$.unsubscribe(); if (this.mouseContextMenu$) this.mouseContextMenu$.unsubscribe(); if (this.rectRX$) this.rectRX$.unsubscribe(); if (this.profileOuterSphereRX$) this.profileOuterSphereRX$.unsubscribe(); if (this.profileOuterSphereRotateRX$) this.profileOuterSphereRotateRX$.unsubscribe(); } /** * 开启旋转角订阅 */ public openRotateSubject(proOuter: OuterSphereHasAuxlModel): void { setTimeout(() => { this.scopeEnchantment.handleCursorPinStyle( this.panelScopeEnchantmentService.conversionRotateOneCircle(proOuter.rotate) ); }); if (this.profileOuterSphereRotateRX$) this.profileOuterSphereRotateRX$.unsubscribe(); this.profileOuterSphereRotateRX$ = proOuter.valueChange$ .pipe( map(v => v.rotate), debounceTime(1), distinctUntilChanged() ) .subscribe(value => { this.scopeEnchantment.handleCursorPinStyle( this.panelScopeEnchantmentService.conversionRotateOneCircle(value) ); }); } /** * 根据鼠标偏移的增量来处理计算主轮廓的位置 */ public handleProfileOuterSphereLocation(drag: DraggablePort): void { // 计算主轮廓的位置 this.scopeEnchantment.handleProfileOuterSphereLocationInsetWidget(drag); // 判断是否开启辅助线计算 if (this.panelScopeEnchantmentService.isOpenAltCalc$.value) { // 同时把标尺已绘制的辅助线条并入到auxliLineModel里面!!!! const hLine = this.panelScaleplateService.canvasScaleplateModel.hLineList$.value; const vLine = this.panelScaleplateService.canvasScaleplateModel.vLineList$.value; const auxli = this.panelScopeEnchantmentService.auxliLineModel$.value; if (Array.isArray(hLine) && hLine.length > 0) { auxli.vLineList = auxli.vLineList.concat(hLine.map(v => v.inCanvasNum)); } if (Array.isArray(vLine) && vLine.length > 0) { auxli.hLineList = auxli.hLineList.concat(vLine.map(v => v.inCanvasNum)); } auxli.handleSetData(); this.panelScopeEnchantmentService.auxliLineModel$.next(auxli); this.panelScopeEnchantmentService.handleAuxlineCalculate(); } else { this.scopeEnchantment.valueProfileOuterSphere.resetAuxl(); } // 计算主轮廓内所有被选组件的位置 this.scopeEnchantment.handleLocationInsetWidget(drag); } /** * 根据rect矩形判断是否有组件在这个范围内,是的话则选中 * 实现多选效果 * 判断依据是大于左下角,小于右上角 */ public handleRectInsetWidget(port: ILocation): void { const allWidget = this.panelExtendService.valueWidgetList(); const panelInfo = this.panelExtendService.panelInfoModel; let resutArr = []; if (port.width != 0 && port.height != 0) { allWidget.forEach(w => { let offsetCoord = { left: 0, top: 0 }; if (w.profileModel.rotate != 0) { offsetCoord = this.panelScopeEnchantmentService.handleOuterSphereRotateOffsetCoord(w.profileModel); } let tLeft = panelInfo.left + w.profileModel.left + offsetCoord.left; let tBottom = panelInfo.top + w.profileModel.height + w.profileModel.top + offsetCoord.top * -1; let tRight = tLeft + w.profileModel.width + offsetCoord.left * -2; let tTop = tBottom - w.profileModel.height + offsetCoord.top * 2; if ( tLeft > port.left && tBottom < port.top + port.height && tRight < port.left + port.width && tTop > port.top ) { resutArr.push(w); } }); this.panelScopeEnchantmentService.pushOuterSphereInsetWidget(resutArr); } } /** * 生成完主轮廓之后遍历其他不在主轮廓内的组件的横线和竖线 * 计算并保存起来 */ public createAllLineSave(): void { const otherWidgetList = this.panelExtendService.valueWidgetList(); const auxli = new AuxliLineModel(); const panelInfo = this.panelExtendService.panelInfoModel; const fnOffset = this.panelScopeEnchantmentService.handleOuterSphereRotateOffsetCoord.bind( this.panelScopeEnchantmentService ); if (Array.isArray(otherWidgetList)) { auxli.vLineList.push(0, panelInfo.width); auxli.hLineList.push(0, panelInfo.height); auxli.vcLineList.push(panelInfo.width / 2); auxli.hcLineList.push(panelInfo.height / 2); for (let i: number = 0, l = otherWidgetList.length; i < l; i++) { const pro = otherWidgetList[i].profileModel; const offsetCoor = fnOffset(otherWidgetList[i].profileModel); if (pro.isCheck == false) { const lLeft = pro.left + offsetCoor.left; const lRight = pro.left + pro.width + offsetCoor.left * -1; const lTop = pro.top + offsetCoor.top; const lBottom = pro.top + pro.height + offsetCoor.top * -1; auxli.vLineList.push(lLeft, lRight); auxli.hLineList.push(lTop, lBottom); auxli.vcLineList.push(lLeft + pro.width / 2); auxli.hcLineList.push(lTop + pro.height / 2); } } auxli.handleSetData(); this.panelScopeEnchantmentService.auxliLineModel$.next(auxli); } } /** * 八个拖拽点按下的时候记录组件的固定值 * 以及被选组件的固定值 */ public acceptDraggableMouseDown(): void { const pro = this.panelScopeEnchantmentService.scopeEnchantmentModel.valueProfileOuterSphere; const insetWidget = this.scopeEnchantment.outerSphereInsetWidgetList$.value; pro.recordImmobilizationData(); pro.setMouseCoord([pro.left, pro.top]); if (Array.isArray(insetWidget)) { insetWidget.forEach(e => { e.profileModel.recordImmobilizationData(); e.profileModel.setMouseCoord([e.profileModel.left, e.profileModel.top]); }); } } /** * 接收旋转角度的按下事件 */ public acceptRotateIco(mouse: MouseEvent): void { // 转弧度为度数的公式为 Math.atan( x )*180/Math.PI mouse.stopPropagation(); let mouseMove$: Subscription; let mouseUp$: Subscription; const pro = this.scopeEnchantment.valueProfileOuterSphere; const panelInfo = this.panelExtendService.panelInfoModel; let rotate: number = null; mouseMove$ = fromEvent(document, "mousemove").subscribe((move: MouseEvent) => { this.zone.run(() => { // 记录轮廓中心坐标点 const proCenterCoor = [ pro.left + pro.width / 2 + panelInfo.left, pro.top + pro.height / 2 + panelInfo.top, ]; const calcX = move.pageX - proCenterCoor[0]; const calcY = proCenterCoor[1] - move.pageY; rotate = this.panelScopeEnchantmentService.conversionTwoCoordToRotate([calcX, calcY]); this.scopeEnchantment.valueProfileOuterSphere.setData({ rotate: rotate }); this.scopeEnchantment.outerSphereInsetWidgetList$.value.forEach(e => { e.profileModel.setData({ rotate: rotate }); }); }); }); mouseUp$ = fromEvent(document, "mouseup").subscribe(() => { this.zone.run(() => { if (mouseMove$) mouseMove$.unsubscribe(); if (mouseUp$) mouseUp$.unsubscribe(); }); }); } /** * 接受八个拖拽点移动的回调 * 同时重新记录被选组件在主轮廓里的位置比例 */ public acceptDraggableCursor(drag: DraggablePort, corner: CornerPinModel): void { const insetWidget = this.scopeEnchantment.outerSphereInsetWidgetList$.value; const pro = this.scopeEnchantment.valueProfileOuterSphere; if (pro && Array.isArray(insetWidget)) { insetWidget.forEach(w => { w.profileModel.recordInsetProOuterSphereFourProportion(this.scopeEnchantment.valueProfileOuterSphere); }); } this.draggableTensileCursorService.acceptDraggableCursor(drag, corner); } public handleZIndexTopOrBottom(type: "top" | "bottom"): void { this.panelExtendService.handleZIndexTopOrBottom(this.scopeEnchantment.outerSphereInsetWidgetList$.value, type); } public copyWidgetInsetPaste(): void { this.panelExtendQuickShortcutsService.performCopy(); } public cutWidgetInsetPaste(): void { this.panelExtendQuickShortcutsService.performCutWidget(); } public delWidget(): void { this.panelExtendQuickShortcutsService.performDelWidget(); } public createCombination(): void { this.panelAssistArborService.launchCreateCombination$.next(); } public disperseCombination(): void { this.panelAssistArborService.launchDisperseCombination$.next(); } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_expense_Information { interface Tabs { } interface Body { /** Enter the total amount for expense. */ msdyn_Amount: DevKit.Controls.Money; /** Enter the expense category. */ msdyn_ExpenseCategory: DevKit.Controls.Lookup; /** Shows the status of the expense entry. */ msdyn_ExpenseStatus: DevKit.Controls.OptionSet; /** The external comments of the expense entry. */ msdyn_externaldescription: DevKit.Controls.String; /** Enter the expense's purpose. */ msdyn_name: DevKit.Controls.String; /** Enter the Unit Price */ msdyn_Price: DevKit.Controls.Money; /** Enter the project. */ msdyn_Project: DevKit.Controls.Lookup; /** Enter the Quantity */ msdyn_Quantity: DevKit.Controls.Decimal; /** Enter the sales tax amount. */ msdyn_Salestaxamount: DevKit.Controls.Money; /** Shows the total amount of the expense entry. */ msdyn_totalamount: DevKit.Controls.Money; /** Enter the date of the expense transaction. */ msdyn_TransactionDate: DevKit.Controls.Date; /** Enter the Unit */ msdyn_Unit: DevKit.Controls.Lookup; /** Enter the Unit Group */ msdyn_UnitGroup: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Shows the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_msdyn_expense_msdyn_expensereceipt_ExpenseId: DevKit.Controls.NavigationItem } } class Formmsdyn_expense_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_expense_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_expense_Information */ Body: DevKit.Formmsdyn_expense_Information.Body; /** The Navigation of form msdyn_expense_Information */ Navigation: DevKit.Formmsdyn_expense_Information.Navigation; } namespace FormCreate_Expense { interface tab_tab_1_Sections { tab_1_column_1_section_1: DevKit.Controls.Section; } interface tab_tab_1 extends DevKit.Controls.ITab { Section: tab_tab_1_Sections; } interface Tabs { tab_1: tab_tab_1; } interface Body { Tab: Tabs; /** Enter the total amount for expense. */ msdyn_Amount: DevKit.Controls.Money; /** Enter the expense category. */ msdyn_ExpenseCategory: DevKit.Controls.Lookup; /** The external comments of the expense entry. */ msdyn_externaldescription: DevKit.Controls.String; /** Enter the expense's purpose. */ msdyn_name: DevKit.Controls.String; /** Enter the Unit Price */ msdyn_Price: DevKit.Controls.Money; /** Enter the project. */ msdyn_Project: DevKit.Controls.Lookup; /** Enter the Quantity */ msdyn_Quantity: DevKit.Controls.Decimal; /** Enter the sales tax amount. */ msdyn_Salestaxamount: DevKit.Controls.Money; /** Enter the date of the expense transaction. */ msdyn_TransactionDate: DevKit.Controls.Date; /** Enter the Unit */ msdyn_Unit: DevKit.Controls.Lookup; /** Enter the Unit Group */ msdyn_UnitGroup: DevKit.Controls.Lookup; /** Shows the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } } class FormCreate_Expense extends DevKit.IForm { /** * DynamicsCrm.DevKit form Create_Expense * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Create_Expense */ Body: DevKit.FormCreate_Expense.Body; } class msdyn_expenseApi { /** * DynamicsCrm.DevKit msdyn_expenseApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Enter the total amount for expense. */ msdyn_Amount: DevKit.WebApi.MoneyValue; /** Value of the Amount in base currency. */ msdyn_amount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the bookable resource.. */ msdyn_bookableresource: DevKit.WebApi.LookupValue; /** Enter the expense category. */ msdyn_ExpenseCategory: DevKit.WebApi.LookupValue; /** Shows the entity instances. */ msdyn_expenseId: DevKit.WebApi.GuidValue; /** Shows the status of the expense entry. */ msdyn_ExpenseStatus: DevKit.WebApi.OptionSetValue; /** The external comments of the expense entry. */ msdyn_externaldescription: DevKit.WebApi.StringValue; /** Select the manager of the expense user. This field is used for approval. */ msdyn_manager: DevKit.WebApi.LookupValue; /** Enter the expense's purpose. */ msdyn_name: DevKit.WebApi.StringValue; /** Enter the Unit Price */ msdyn_Price: DevKit.WebApi.MoneyValue; /** Value of the Price in base currency. */ msdyn_price_Base: DevKit.WebApi.MoneyValueReadonly; /** Enter the project. */ msdyn_Project: DevKit.WebApi.LookupValue; /** Enter the Quantity */ msdyn_Quantity: DevKit.WebApi.DecimalValue; /** Select the organizational unit at the time the entry was registered of the resource who had the expense. */ msdyn_ResourceOrganizationalUnitId: DevKit.WebApi.LookupValue; /** Enter the sales tax amount. */ msdyn_Salestaxamount: DevKit.WebApi.MoneyValue; /** Value of the Sales tax amount in base currency. */ msdyn_salestaxamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the status that the record will be transitioned to asynchronously. Currently, this is only implemented from submission to approved. */ msdyn_targetExpenseStatus: DevKit.WebApi.OptionSetValue; /** Shows the total amount of the expense entry. */ msdyn_totalamount: DevKit.WebApi.MoneyValueReadonly; /** Enter the value of the total amount in the base currency. */ msdyn_totalamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Enter the date of the expense transaction. */ msdyn_TransactionDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the Unit */ msdyn_Unit: DevKit.WebApi.LookupValue; /** Enter the Unit Group */ msdyn_UnitGroup: DevKit.WebApi.LookupValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Contains the id of the process associated with the entity. */ processid: DevKit.WebApi.GuidValue; /** Contains the id of the stage where the entity is located. */ stageid: DevKit.WebApi.GuidValue; /** Status of the Expense */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Expense */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Shows the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */ traversedpath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_expense { enum msdyn_ExpenseStatus { /** 192350002 */ Approved, /** 192350000 */ Draft, /** 192350005 */ Paid, /** 192350004 */ Posted, /** 192350006 */ Recall_Requested, /** 192350003 */ Rejected, /** 192350001 */ Submitted } enum msdyn_targetExpenseStatus { /** 192350002 */ Approved, /** 192350000 */ Draft, /** 192350005 */ Paid, /** 192350004 */ Posted, /** 192350006 */ Recall_Requested, /** 192350003 */ Rejected, /** 192350001 */ Submitted } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 867380003 */ Approved, /** 867380000 */ Draft, /** 867380005 */ Paid, /** 867380004 */ Posted, /** 867380001 */ Rejected, /** 867380002 */ Submitted } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Create Expense','Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { Component, Input, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { BehaviorSubject, Observable, of as observableOf, Subscription } from 'rxjs'; import { map, mergeMap, switchMap, take } from 'rxjs/operators'; import { PaginatedList } from '../../../../core/data/paginated-list.model'; import { RemoteData } from '../../../../core/data/remote-data'; import { GroupDataService } from '../../../../core/eperson/group-data.service'; import { Group } from '../../../../core/eperson/models/group.model'; import { getFirstCompletedRemoteData, getFirstSucceededRemoteData, getRemoteDataPayload } from '../../../../core/shared/operators'; import { NotificationsService } from '../../../../shared/notifications/notifications.service'; import { PaginationComponentOptions } from '../../../../shared/pagination/pagination-component-options.model'; import { NoContent } from '../../../../core/shared/NoContent.model'; import { PaginationService } from '../../../../core/pagination/pagination.service'; import { followLink } from '../../../../shared/utils/follow-link-config.model'; /** * Keys to keep track of specific subscriptions */ enum SubKey { Members, ActiveGroup, SearchResults, } @Component({ selector: 'ds-subgroups-list', templateUrl: './subgroups-list.component.html' }) /** * The list of subgroups in the edit group page */ export class SubgroupsListComponent implements OnInit, OnDestroy { @Input() messagePrefix: string; /** * Result of search groups, initially all groups */ searchResults$: BehaviorSubject<RemoteData<PaginatedList<Group>>> = new BehaviorSubject(undefined); /** * List of all subgroups of group being edited */ subGroups$: BehaviorSubject<RemoteData<PaginatedList<Group>>> = new BehaviorSubject(undefined); /** * Map of active subscriptions */ subs: Map<SubKey, Subscription> = new Map(); /** * Pagination config used to display the list of groups that are result of groups search */ configSearch: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), { id: 'ssgl', pageSize: 5, currentPage: 1 }); /** * Pagination config used to display the list of subgroups of currently active group being edited */ config: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), { id: 'sgl', pageSize: 5, currentPage: 1 }); // The search form searchForm; // Current search in edit group - groups search form currentSearchQuery: string; // Whether or not user has done a Groups search yet searchDone: boolean; // current active group being edited groupBeingEdited: Group; constructor(public groupDataService: GroupDataService, private translateService: TranslateService, private notificationsService: NotificationsService, private formBuilder: FormBuilder, private paginationService: PaginationService, private router: Router) { this.currentSearchQuery = ''; } ngOnInit() { this.searchForm = this.formBuilder.group(({ query: '', })); this.subs.set(SubKey.ActiveGroup, this.groupDataService.getActiveGroup().subscribe((activeGroup: Group) => { if (activeGroup != null) { this.groupBeingEdited = activeGroup; this.retrieveSubGroups(); } })); } /** * Retrieve the Subgroups that are members of the group * * @param page the number of the page to retrieve * @private */ private retrieveSubGroups() { this.unsubFrom(SubKey.Members); this.subs.set( SubKey.Members, this.paginationService.getCurrentPagination(this.config.id, this.config).pipe( switchMap((config) => this.groupDataService.findAllByHref(this.groupBeingEdited._links.subgroups.href, { currentPage: config.currentPage, elementsPerPage: config.pageSize }, true, true, followLink('object') )) ).subscribe((rd: RemoteData<PaginatedList<Group>>) => { this.subGroups$.next(rd); })); } /** * Whether or not the given group is a subgroup of the group currently being edited * @param possibleSubgroup Group that is a possible subgroup (being tested) of the group currently being edited */ isSubgroupOfGroup(possibleSubgroup: Group): Observable<boolean> { return this.groupDataService.getActiveGroup().pipe(take(1), mergeMap((activeGroup: Group) => { if (activeGroup != null) { if (activeGroup.uuid === possibleSubgroup.uuid) { return observableOf(false); } else { return this.groupDataService.findAllByHref(activeGroup._links.subgroups.href, { currentPage: 1, elementsPerPage: 9999 }) .pipe( getFirstSucceededRemoteData(), getRemoteDataPayload(), map((listTotalGroups: PaginatedList<Group>) => listTotalGroups.page.filter((groupInList: Group) => groupInList.id === possibleSubgroup.id)), map((groups: Group[]) => groups.length > 0)); } } else { return observableOf(false); } })); } /** * Whether or not the given group is the current group being edited * @param group Group that is possibly the current group being edited */ isActiveGroup(group: Group): Observable<boolean> { return this.groupDataService.getActiveGroup().pipe(take(1), mergeMap((activeGroup: Group) => { if (activeGroup != null && activeGroup.uuid === group.uuid) { return observableOf(true); } return observableOf(false); })); } /** * Deletes given subgroup from the group currently being edited * @param subgroup Group we want to delete from the subgroups of the group currently being edited */ deleteSubgroupFromGroup(subgroup: Group) { this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((activeGroup: Group) => { if (activeGroup != null) { const response = this.groupDataService.deleteSubGroupFromGroup(activeGroup, subgroup); this.showNotifications('deleteSubgroup', response, subgroup.name, activeGroup); } else { this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.noActiveGroup')); } }); } /** * Adds given subgroup to the group currently being edited * @param subgroup Subgroup to add to group currently being edited */ addSubgroupToGroup(subgroup: Group) { this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((activeGroup: Group) => { if (activeGroup != null) { if (activeGroup.uuid !== subgroup.uuid) { const response = this.groupDataService.addSubGroupToGroup(activeGroup, subgroup); this.showNotifications('addSubgroup', response, subgroup.name, activeGroup); } else { this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.subgroupToAddIsActiveGroup')); } } else { this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.noActiveGroup')); } }); } /** * Search in the groups (searches by group name and by uuid exact match) * @param data Contains query param */ search(data: any) { const query: string = data.query; if (query != null && this.currentSearchQuery !== query) { this.router.navigateByUrl(this.groupDataService.getGroupEditPageRouterLink(this.groupBeingEdited)); this.currentSearchQuery = query; this.configSearch.currentPage = 1; } this.searchDone = true; this.unsubFrom(SubKey.SearchResults); this.subs.set(SubKey.SearchResults, this.paginationService.getCurrentPagination(this.configSearch.id, this.configSearch).pipe( switchMap((config) => this.groupDataService.searchGroups(this.currentSearchQuery, { currentPage: config.currentPage, elementsPerPage: config.pageSize }, true, true, followLink('object') )) ).subscribe((rd: RemoteData<PaginatedList<Group>>) => { this.searchResults$.next(rd); })); } /** * Unsubscribe from a subscription if it's still subscribed, and remove it from the map of * active subscriptions * * @param key The key of the subscription to unsubscribe from * @private */ private unsubFrom(key: SubKey) { if (this.subs.has(key)) { this.subs.get(key).unsubscribe(); this.subs.delete(key); } } /** * unsub all subscriptions */ ngOnDestroy(): void { for (const key of this.subs.keys()) { this.unsubFrom(key); } this.paginationService.clearPagination(this.config.id); this.paginationService.clearPagination(this.configSearch.id); } /** * Shows a notification based on the success/failure of the request * @param messageSuffix Suffix for message * @param response RestResponse observable containing success/failure request * @param nameObject Object request was about * @param activeGroup Group currently being edited */ showNotifications(messageSuffix: string, response: Observable<RemoteData<Group|NoContent>>, nameObject: string, activeGroup: Group) { response.pipe(getFirstCompletedRemoteData()).subscribe((rd: RemoteData<Group>) => { if (rd.hasSucceeded) { this.notificationsService.success(this.translateService.get(this.messagePrefix + '.notification.success.' + messageSuffix, { name: nameObject })); this.groupDataService.clearGroupLinkRequests(activeGroup._links.subgroups.href); } else { this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.' + messageSuffix, { name: nameObject })); } }); } /** * Reset all input-fields to be empty and search all search */ clearFormAndResetResult() { this.searchForm.patchValue({ query: '', }); this.search({ query: '' }); } }
the_stack
import fs from "fs"; import { strict as assert } from "assert"; import { ZonedDateTime, ZoneOffset } from "@js-joda/core"; import got, { Response as GotResponse } from "got"; import { Semaphore } from "await-semaphore"; import Denque from "denque"; import { LogSeries, LogSeriesFragmentPushRequest, LogSeriesFragment, LogSeriesFetchAndValidateOpts, LokiQueryResult } from "./logs"; import { MetricSeries, MetricSeriesFragment, MetricSeriesFragmentPushMessage, MetricSeriesFetchAndValidateOpts } from "./metrics"; import { LabelSet, WalltimeCouplingOptions } from "./series"; import { sleep, mtimeDiffSeconds, mtimeDeadlineInSeconds, mtime } from "./mtime"; import { log } from "./log"; import * as util from "./util"; export const START_TIME_JODA = ZonedDateTime.now(ZoneOffset.UTC); // const START_TIME_EPOCH = START_TIME_JODA.toEpochSecond(); const START_TIME_MONOTONIC = mtime(); import { parseCmdlineArgs, CFG, BEARER_TOKEN } from "./args"; import * as pm from "./prommetrics"; interface WriteStats { nEntriesSent: number; nPayloadBytesSent: number; entriesSentPerSec: number; megaPayloadBytesSentPerSec: number; durationSeconds: number; } interface ReadStats { nEntriesRead: number; nPayloadBytesRead: number; entriesReadPerSec: number; megaPayloadBytesReadPerSec: number; durationSeconds: number; } export const DEFAULT_LOG_LEVEL_STDERR = "info"; // only expose via CLI args if a good use case arises. export let WALLTIME_COUPLING_PARAMS: WalltimeCouplingOptions; let tooFastMsgLoggedLastTime = BigInt(0); // let STATS_WRITE: WriteStats; // let STATS_READ: ReadStats; // these are set dynamically per-cycle. let CYCLE_START_TIME_MONOTONIC: bigint; let CYCLE_STOP_WRITE_AFTER_SECONDS: number; // I didn't find a sane way to get the current value of a prometheus counter // so this duplicates this as a global for internal things. Does not wrap, // of course. let COUNTER_STREAM_FRAGMENTS_PUSHED = BigInt(0); let COUNTER_PUSHREQUEST_STATS_LOG_THROTTLE = 0; // Prepare a mapping between series unique name and a count let PER_STREAM_FRAGMENTS_CONSUMED_IN_CURRENT_CYCLE: Record<string, number> = {}; function setUptimeGauge() { // Set this in various places of the program visted regularly. const uptimeSeconds = mtimeDiffSeconds(START_TIME_MONOTONIC); pm.gauge_uptime.set(Math.round(uptimeSeconds)); } async function main() { parseCmdlineArgs(); const httpServerTerminator = pm.setupPromExporter(); WALLTIME_COUPLING_PARAMS = calcWalltimeCouplingOptions(); log.info("cycle 1: create a fresh set of time series"); let series: Array<LogSeries | MetricSeries> = await createNewSeries( cycleId(1) ); let cyclenum = 0; while (true) { cyclenum++; // create a bit of visual separation between per-cycle log blobs. // `process.stderr.write()` might interleave unpredictably with rest of log // output. // log.info("cyclenum: %s", cyclenum); if (cyclenum > 1) { // log.info("\n\n\n"); process.stderr.write("\n\n"); } log.info("enter write/read cycle %s", cyclenum); setUptimeGauge(); const cycleid = cycleId(cyclenum); if (cyclenum > 1) { if ( CFG.change_series_every_n_cycles > 0 && (cyclenum - 1) % CFG.change_series_every_n_cycles === 0 ) { log.info( `cycle ${cyclenum}: fresh time series object(s) as ` + "of CFG.change_series_every_n_cycles" ); series = await createNewSeries(cycleid); } else { log.info( "cycle %s: continue to use time series of previous cycle", cyclenum ); } } pm.counter_rw_cycles.inc(); try { await performWriteReadCycle(cyclenum, series, cycleid); } catch (err) { log.crit("err during write/read cycle: %s", err); process.exit(1); } if (CFG.n_cycles !== 0) { if (cyclenum === CFG.n_cycles) { log.info(`cycles completed: ${CFG.n_cycles}, terminate`); } break; } } log.debug("shutting down http server"); httpServerTerminator.terminate(); } /** * Generate Cycle ID from cycle number `n`. `n` is 1, 2, 3, ... * * Return value is constant for constant `n`. * * The Cycle ID contains the invocation ID which contains quite a bit of * randomness. * @param n: the cycle number, an integer >= 1 */ function cycleId(n: number) { // The idea is that `CFG.invocation_id` is unique among those looker // instances that interact with the same data ingest system. return `${CFG.invocation_id}-${n}`; } function calcFragmentTimeLeapSeconds(): number { let sample_time_increment_ns: number; if (CFG.metrics_mode) { sample_time_increment_ns = CFG.metrics_time_increment_ms * 1000; } else { sample_time_increment_ns = CFG.log_time_increment_ns; } // Fragment time leap, defined as the time difference between the last sample // of a fragment and the last sample of the previous fragment, equal to // (n_samples_per_series_fragment) * delta_t. const fragmentTimeLeapSeconds = CFG.n_samples_per_series_fragment * (sample_time_increment_ns / 10 ** 6); return fragmentTimeLeapSeconds; } function calcWalltimeCouplingOptions(): WalltimeCouplingOptions { const fragmentTimeLeapSeconds = calcFragmentTimeLeapSeconds(); log.info( "walltime coupling: fragmentTimeLeapSeconds: " + `${fragmentTimeLeapSeconds.toFixed(2)} s` ); // Why must maxLagSeconds depend on fragmentTimeLeapSconds? See // `TimeseriesBase.validateWtOpts()`. const minimalMaxLagSeconds = 2 * 60; const dynamicMaxLagSeconds = Math.ceil(fragmentTimeLeapSeconds * 5); let actualMaxLagSeconds; if (dynamicMaxLagSeconds < minimalMaxLagSeconds) { log.info( `walltime coupling: use minimal maxLagSeconds: ${minimalMaxLagSeconds}` ); actualMaxLagSeconds = minimalMaxLagSeconds; } else { log.info( `walltime coupling: use dynamic maxLagSeconds: ${dynamicMaxLagSeconds} ` + `(based on fragmentTimeLeapSeconds: ${fragmentTimeLeapSeconds.toFixed( 2 )} s)` ); actualMaxLagSeconds = dynamicMaxLagSeconds; } return { maxLagSeconds: actualMaxLagSeconds, minLagSeconds: 0.5 * 60 }; } async function createNewSeries( invocationCycleId: string ): Promise<Array<LogSeries | MetricSeries>> { const series = []; log.info(`create ${CFG.n_series} time series objects`); if (CFG.additional_labels !== undefined) { log.info( "adding additional labels: %s", JSON.stringify(CFG.additional_labels) ); } const now = ZonedDateTime.now(); for (let i = 1; i < CFG.n_series + 1; i++) { const seriesname = `${invocationCycleId}-${i.toString()}`; const labelset: LabelSet = {}; // add more labels (key/value pairs) as given by command line // without further validation if (CFG.additional_labels !== undefined) { // log.info( // "adding additional labels: %s", // JSON.stringify(CFG.additional_labels) // ); for (const kvpair of CFG.additional_labels) { labelset[kvpair[0]] = kvpair[1]; } } let s: MetricSeries | LogSeries; // Smear out the synthetic start time across individual time series, within // the 'green interval' [now-wcp.maxLagSeconds, now-wcp.minLagSeconds), // which is the interval of allowed timestamp values. At the boundaries of // that interval the walltime coupling correction mechanism hits in. As we // don't want these mechanisms to hit in right away, add a bit of leeway to // the left and right -- make the interval a little more narrow but cutting // a slice whose thickness depends on the time width of the series // fragments. Rely on the fact that the 'green interval' is at least 5 // times as wide as a single time series fragment (in time). If the total // buffer is 3 times that then the regime to pick values from is as wide as // 2 ... const startTimeOffsetIntoPast = util.rndFloatFromInterval( WALLTIME_COUPLING_PARAMS.minLagSeconds + 1.5 * calcFragmentTimeLeapSeconds(), WALLTIME_COUPLING_PARAMS.maxLagSeconds - 1.5 * calcFragmentTimeLeapSeconds() ); // const startTimeOffsetIntoPast = util.rndFloatFromInterval( // WALLTIME_COUPLING_PARAMS.minLagSeconds + 5, // WALLTIME_COUPLING_PARAMS.maxLagSeconds - 5 // ); const starttime = now.minusSeconds(startTimeOffsetIntoPast).withNano(0); if (CFG.metrics_mode) { // TODO some sort of adjustable cardinality here, where the number of // distinct label permutations across a series is configurable? (e.g. 10k // distinct labels across a series) s = new MetricSeries({ // kept distinct across concurrent streams, see above TODO about sharing metric names // ensure any dashes in metric name are switched to underscores: required by prometheus // see also: https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels metricName: seriesname.replace(/-/g, "_"), // must not collide among concurrent streams uniqueName: seriesname, n_samples_per_series_fragment: CFG.n_samples_per_series_fragment, starttime: starttime, // any check needed before doing this multiplication? would love to // have guarantee that the result is the sane integer that it needs // to be for the expected regime that users choose // `CFG.metrics_time_increment_ms` from. sample_time_increment_ns: CFG.metrics_time_increment_ms * 1000, labelset: labelset, wtopts: WALLTIME_COUPLING_PARAMS, counterForwardLeap: pm.counter_forward_leap }); } else { // disable wall time coupling when --log-start-time has been set. let wtopts: WalltimeCouplingOptions | undefined = WALLTIME_COUPLING_PARAMS; let logstarttime: ZonedDateTime | undefined = starttime; if (CFG.log_start_time !== "") { log.info("wall time coupling disabled as of --log-start-time"); wtopts = undefined; logstarttime = ZonedDateTime.parse(CFG.log_start_time); } s = new LogSeries({ n_samples_per_series_fragment: CFG.n_samples_per_series_fragment, n_chars_per_msg: CFG.n_chars_per_msg, starttime: logstarttime, uniqueName: seriesname, sample_time_increment_ns: CFG.log_time_increment_ns, includeTimeInMsg: true, labelset: labelset, compressability: CFG.compressability, wtopts: wtopts }); } const msg = `Initialized series: ${s}. Time of first sample: ${s.currentTimeRFC3339Nano()}`; const logEveryN = util.logEveryNcalc(CFG.n_series); if (i % logEveryN == 0) { log.info(msg + ` (${logEveryN - 1} msgs like this are/will be hidden)`); // Allow for more or less snappy SIGINTing this initialization step. await sleep(0.0001); } else { log.debug(msg); } series.push(s); } log.info("time series initialization finished"); return series; } async function performWriteReadCycle( cyclenum: number, series: Array<LogSeries | MetricSeries>, invocationCycleId: string ) { CYCLE_START_TIME_MONOTONIC = mtime(); CYCLE_STOP_WRITE_AFTER_SECONDS = CFG.cycle_stop_write_after_n_seconds; if (CFG.cycle_stop_write_after_n_seconds_jitter !== 0) { const jitter = util.rndFloatFromInterval( -CFG.cycle_stop_write_after_n_seconds_jitter, CFG.cycle_stop_write_after_n_seconds_jitter ); CYCLE_STOP_WRITE_AFTER_SECONDS += jitter; log.info( "CYCLE_STOP_WRITE_AFTER_SECONDS: (%s + %s) s", CFG.cycle_stop_write_after_n_seconds, jitter.toFixed(2) ); } const arrayLengthBeforeWrite = series.length; log.info("cycle %s: entering write phase", cyclenum); const writestats = await writePhase(series); // This is to protect against bugs in `writePhase()` where the `series` // array becomes accidentally mutated (had this before: series got // depopulated, read validation was happy in no time: 0 streams to validate) assert(arrayLengthBeforeWrite === series.length); log.info("cycle %s: entering read phase", cyclenum); await sleep(1); const readstats = await readPhase(series); const report = { argv: process.argv, renderedConfig: CFG, invocationTime: util.timestampToRFC3339Nano(START_TIME_JODA), cycleStats: { cycleNum: cyclenum, invocationCycleId: invocationCycleId, write: writestats, read: readstats } }; log.debug("Report:\n%s", JSON.stringify(report, null, 2)); const reportFilePath = `${invocationCycleId}.report.json`; fs.writeFileSync(reportFilePath, JSON.stringify(report, null, 2)); log.info("wrote report to %s", reportFilePath); } async function writePhase(streams: Array<LogSeries | MetricSeries>) { const fragmentsPushedBefore = COUNTER_STREAM_FRAGMENTS_PUSHED; log.debug("reset per-series fragment push counter"); PER_STREAM_FRAGMENTS_CONSUMED_IN_CURRENT_CYCLE = {}; for (const s of streams) { PER_STREAM_FRAGMENTS_CONSUMED_IN_CURRENT_CYCLE[s.uniqueName] = 0; } const lt0 = mtime(); // First, mark all streams so that (no) validation info is collected (to // override state from previous cycle, if the stream objects were carried // over from the previous cycle). Special case for --skip-read. if (CFG.skip_read) { log.info( "mark all streams to not keep track of validation info: --skip-read" ); for (const s of streams) { s.disableValidation(); } } else if (CFG.read_n_series_only === 0) { log.info( "mark all streams to keep track of validation info: no --skip-read, and no --read-n-streams-only" ); for (const s of streams) { s.enableValidation(); } } // Optimize for the case where there are many streams of which a small // fraction is supposed to be read-validated after the write phase. Only keep // record of the data that was written for that little fraction. I.eq., mark // most streams with a validation-info-not-needed flag, which reduces the // memory usage during the write phase. if (CFG.read_n_series_only !== 0) { // this implies that --skip-read is _not_ set. log.info( "mark all streams to not keep track of validation info: --read-n-streams-only is set" ); for (const s of streams) { s.disableValidation(); } log.info( "randomly marking %s/%s streams for validation", CFG.read_n_series_only, CFG.n_series ); const streamsToValidate: Array<LogSeries | MetricSeries> = util.randomSampleFromArray(streams, CFG.read_n_series_only); // For a small selection, show the names of the streams, for debuggability if (CFG.read_n_series_only < 20) { const names = streamsToValidate.map(s => s.uniqueName).join(", "); log.info("selected: %s", names); } for (const s of streamsToValidate) { s.enableValidation(); } } const labelForValidationDurationSeconds = mtimeDiffSeconds(lt0); // It's interesting to see how long these iterations took for millions of // streams. log.debug( "re-labeling series for validation info collection took %s s", labelForValidationDurationSeconds.toFixed(2) ); // Now enter the actual write phase. const wt0 = mtime(); await generateAndPostFragments(streams); const writeDurationSeconds = mtimeDiffSeconds(wt0); const nStreamFragmentsSent = Number( COUNTER_STREAM_FRAGMENTS_PUSHED - fragmentsPushedBefore ); // This loop might be too heavy for millions of time series // for (const stream of streams) { // log.debug( // "stream %s: wrote %s fragment(s)", // stream.uniqueName, // stream.nFragmentsSuccessfullySentSinceLastValidate // ); // } log.info( `fragments POSTed in write phase: ${nStreamFragmentsSent}, across ` + `${streams.length} series` ); const nEntriesSent = nStreamFragmentsSent * CFG.n_samples_per_series_fragment; let nPayloadBytesSent = nEntriesSent * CFG.n_chars_per_msg; if (CFG.metrics_mode) { // Think: payload bytes sent, i.e. sample bytes excluding timestamp. In // Prometheus, a sample value is a double precision floating point number, // i.e. set this to the number of samples sent times 8 Bytes. nPayloadBytesSent = nEntriesSent * 8; } const megaPayloadBytesSent = nPayloadBytesSent / 10 ** 6; // int division ok? const megaPayloadBytesSentPerSec = megaPayloadBytesSent / writeDurationSeconds; const stats: WriteStats = { nEntriesSent: nEntriesSent, nPayloadBytesSent: nPayloadBytesSent, entriesSentPerSec: nEntriesSent / writeDurationSeconds, megaPayloadBytesSentPerSec: megaPayloadBytesSentPerSec, durationSeconds: writeDurationSeconds }; log.info( "End of write phase. Log entries / metric samples sent: %s, Payload bytes sent: %s million", nEntriesSent, megaPayloadBytesSent.toFixed(2) ); log.info( "Payload write net throughput (mean): " + megaPayloadBytesSentPerSec.toFixed(5) + " million bytes per second (assumes utf8 for logs and 12+8 " + "bytes per sample for metrics)" ); // `FATAL ERROR: Reached heap limit Allocation failed` happens somewhere // after the write phase. Trying to find out where/why. await sleep(1); // for (const stream of streams) { // log.debug( // "Stats of last-consumed fragment of stream %s: %s", // stream.uniqueName, // stream.lastFragmentConsumed?.stats //currentTimeRFC3339Nano() // ); // } return stats; } async function throttledFetchAndValidate( semaphore: Semaphore, stream: LogSeries | MetricSeries ) { let fetchresult; const st0 = mtime(); const release = await semaphore.acquire(); log.debug( "fetchAndValidate held back by semaphore for %s s", mtimeDiffSeconds(st0).toFixed(2) ); try { fetchresult = await unthrottledFetchAndValidate(stream); } catch (err: any) { log.info("err in sem-protected, release, re-throw"); release(); throw err; } release(); return fetchresult; } async function unthrottledFetchAndValidate(stream: LogSeries | MetricSeries) { if (CFG.metrics_mode) { const opts: MetricSeriesFetchAndValidateOpts = { querierBaseUrl: CFG.apibaseurl, customHTTPGetFunc: httpGETRetryUntil200OrError }; return await stream.fetchAndValidate(opts); } const opts: LogSeriesFetchAndValidateOpts = { querierBaseUrl: CFG.apibaseurl, additionalHeaders: {}, // inspectEveryNthEntry: inspectEveryNthEntry, customLokiQueryFunc: queryLokiWithRetryOrError // only used by LogSeries.fetchAndValidate: has custom header injection }; return await stream.fetchAndValidate(opts); } async function readPhase(streams: Array<LogSeries | MetricSeries>) { log.debug("entering read / validation phase"); const validators = []; const vt0 = mtime(); if (CFG.skip_read) { log.info("skipping readout as of --skip-read"); } else { // Note that the 'sparse readout' where --skip-read is not set but // --read-n-streams-only is set is implemented per series object: the // validation method is effectively a noop for streams that were set to not // collect validation info. However, do not call functions where not // needed, that's why there is the `s.shouldBeValidated()`-based condition // Also, calling millions of noop functions does not work: // `RangeError: Too many elements passed to Promise.all` if (CFG.max_concurrent_reads === 0) { for (const s of streams) { if (s.shouldBeValidated()) { validators.push(unthrottledFetchAndValidate(s)); } } } else { const semaphore = new Semaphore(CFG.max_concurrent_reads); for (const s of streams) { if (s.shouldBeValidated()) { validators.push(throttledFetchAndValidate(semaphore, s)); } } } } log.info(`created ${validators.length} actor(s) for validation/readout`); await sleep(1); // This code section must still be reached when using --skip-read, to // generate a 'correct' report, indicating that nothing was read. let nSamplesReadArr; try { // each validator returns the number of entries read (and validated) // TODO: a little it of progress report here would be nice. nSamplesReadArr = await Promise.all(validators); } catch (err: any) { log.crit("error during validation: %s", err); process.exit(1); } if (CFG.read_n_series_only !== 0) { log.debug("drop 'validation info' for all streams"); for (const s of streams) { // Say there are 10^6 streams and we just read/validated a tiny fraction // of them, then there's a lot of data in memory (that would be needed to // to do read validation for all the other streams, which we know we // would not do). Assume that this is idempotent and fast. It is // important to do this _after_ `await Promise.all(validators)` above, so // that we do not pull validation info underneath validator methods that // need them. // TODO: might not be needed if in the beginning of the cycle things // are properly set up s.dropValidationInfo(); } } const nSamplesRead = nSamplesReadArr.reduce((a, b) => a + b, 0); //log.info("nSamplesReadArr sum: %s", nSamplesRead); const readDurationSeconds = mtimeDiffSeconds(vt0); log.info( `validation (read) took ${readDurationSeconds.toFixed(1)} s overall. ` + `${nSamplesRead} samples read across ${validators.length} series (` + `${nSamplesRead / validators.length} per series).` ); // assume that exact payload was read as previously sent for now // TODO: build these stats on the fly during readout and expect numbers // to match write? //const nSamplesRead = STATS_WRITE.nEntriesSent; let nPayloadBytesRead = nSamplesRead * CFG.n_chars_per_msg; if (CFG.metrics_mode) { // 64 bit floating point, i.e. 8 bytes per sample nPayloadBytesRead = nSamplesRead * 8; } const megaPayloadBytesRead = nPayloadBytesRead / 10 ** 6; const stats: ReadStats = { nEntriesRead: nSamplesRead, nPayloadBytesRead: nPayloadBytesRead, entriesReadPerSec: nSamplesRead / readDurationSeconds, megaPayloadBytesReadPerSec: megaPayloadBytesRead / readDurationSeconds, durationSeconds: readDurationSeconds }; return stats; } /* This function is the core of the write phase within a cycle. For each series, send all fragments (until intra-cycle stop criterion is hit). A "push request" or "push message" is a Prometheus term for a (snappy-compressed) protobuf message carrying log/metric payload data. If `CFG.n_fragments_per_push_message` is larger than 1 then this means that each push message is supposed to contain data from that many time series. */ export async function generateAndPostFragments( series: Array<LogSeries | MetricSeries> ): Promise<void> { const actors = []; // `CFG.max_concurrent_writes` is at most `N_concurrent_streams`. // N_concurrent_streams may be up to O(10**6). // // The main activity within an // actor is to do this in a loop: // // - generate one or more time series fragments // - serialize this/these fragment(s) into a binary push messages // - send that message out via an HTTP POST request // We do not want to mutate the original `series` Array -- which of the // following two techniques fulfills that? Both? //const seriespool = new Denque([...series]); const seriespool = new Denque(series); const actorCount = CFG.max_concurrent_writes; for (let i = 1; i <= actorCount; i++) { actors.push( produceAndPOSTpushrequestsUntilCycleStopCriterion( seriespool, CFG.n_fragments_per_push_message, actorCount, i ) ); } await Promise.all(actors); log.info("all write actors terminated"); // Somewhere around here is where FATAL ERROR: Reached heap limit Allocation // failed - JavaScript heap out of memory happens, if it happens. I doubt // this function has anything to do with it, and to confirm that I'd like to // see the log statement above -- and to really give that time to end up // being visible on the transport (stderr / file), sleep for a moment. await sleep(1); } /** * Get at most N fragments from series pool. * * Invariant: get at most one fragment per series. * * If the series pool doesn't have N fragments ready to be consumed then the * returned number may be 0 or any number less than N. * * This only returns less than N for boundary effects, towards 'end of work'. * * As of the way the concurrent actors operate on `seriespool` this might * return a set of fragments with varying 'generation' across fragments, i.e. * one fragment is the Mth one from a time series, and another fragment is the * Pth one from another time series with M != P. * * (before this, looker once had a concurrency architecture that ensured that * _all_ first-generation fragments get pushed before moving on to generating * second-generation fragments, and so on.) * * The sorting order of time series objects on the series pool may vary and get * more and more random over time when there is a lot of work to do, as of the * unpredictable timing of HTTP requests -- that is why certain time series * objects may after all be processed faster than others. Over time, this may * create an interesting distribution of 'progress' for each time series. * * @param seriespool * @param nf: desired number of fragments * @param actorCount * @param actorIndex * @returns */ async function tryToGetNFragmentsFromSeriesPool( seriespool: Denque<LogSeries | MetricSeries>, nf: number, actorCount: number, // total number of actors actorIndex: number // representing the actor as part of which this func runs ): Promise<Array<LogSeriesFragment | MetricSeriesFragment>> { const fragments: Array<LogSeriesFragment | MetricSeriesFragment> = []; // candidate-popping loop: try to acquire at most `nf` fragments (all from // different series) from the pool (not every candidate might have one // ready!) let candidatesPoppedSinceLastFragmentGenerated = 0; while (true) { // Look at a candidate: pop off item from the end of the queue. const s = seriespool.pop(); candidatesPoppedSinceLastFragmentGenerated += 1; if (s === undefined) { log.info( `write actor ${actorIndex}: series pool is empty. ` + `generated ${fragments.length} fragments (desired: ${nf})` ); // Break from the loop. At this point, the `fragments` array may // be of length between 0 or nf-1. return fragments; } let fragment: MetricSeriesFragment | LogSeriesFragment | undefined = undefined; // This while loop is effectively implementing the throttling mechanism // when synthetic time moves too fast. let histobserved = false; // lazy-throttling loop: once the pool is small, keep an eye on the // individual candidate, periodically, via this loop. When there's still // work on the pool never spend more than one iteration in here. while (true) { const [shiftIntoPastSeconds, f] = s.generateNextFragmentOrSkip(); // If `f` was freshly generated (no throttling) then rely on // `shiftIntoPastSeconds` to represent the last sample of that fresh // fragment. If `f` is `undefined` then rely on this value to represent // the last sample of the last generated fragment. Only observe this once // in this current loop here to not skew the histogram. (maybe it's // better to decouple that and do this elsewhere). if (!histobserved) { pm.hist_lag_compared_to_wall_time.observe(shiftIntoPastSeconds); histobserved = true; } if (f !== undefined) { // A fragment was generated from `s`. Leave this lazy-throttling loop. fragment = f; candidatesPoppedSinceLastFragmentGenerated = 0; break; } // `s` was not ready. Info-log this fact, but only once per N seconds (to // keep some progress report here; this might take many minutes w/o // generating log output otherwise). if (mtimeDiffSeconds(tooFastMsgLoggedLastTime) > 10) { const shiftIntoPastMinutes = shiftIntoPastSeconds / 60; log.info( `write actor ${actorIndex}: ${s}: current lag compared to wall time is ${shiftIntoPastMinutes.toFixed( 1 )} minutes. Sample generation is too fast. Delay generating ` + "and pushing the next fragment. This may take up to " + `${(s.fragmentTimeLeapSeconds / 60.0).toFixed(1)} minutes, ` + "the time width of a series fragment. " + "(not logged for every case)" ); tooFastMsgLoggedLastTime = mtime(); } pm.counter_fragment_generation_delayed.inc(1); if (candidatesPoppedSinceLastFragmentGenerated >= CFG.n_series) { // We looked at at least as many time series as there are and none of // them had a fragment ready. Example: just one actor and two series, // and none of these two series will have a fragment ready within the // next five minutes of wall time. Then do not busy-spin in this loop // (the candidate-popping loop) by constantly popping one of those // series off the work pool and immediately putting it back, // immediately proceeding with the next. Add a tiny sleep in this case // per candidate-popping loop iteration. This allows for CTRL+C ing // quickly in this scenario and changes the average CPU utilization // from ~100 % to ~0 %. await sleep(0.5); } // If there's still a bunch of other candidates in the pool then put the // current candidate back and pick another one. Else, start polling loop // and watch the current candidate. const ql = seriespool.length; if (ql <= actorCount - 1) { // There is as much work left in the pool as other actors are there // or less work than that. Don't put the current candidate back into // the pool. Observe it. log.debug( `write actor ${actorIndex}: actors are running out of work ` + `(queue length: ${ql}): idle-watch candidate` ); await sleep(5); continue; } // There's still work in the pool (candidates to look at before other // actors will). Put this candidate back onto the queue (left-hand side) // and leave this lazy-throttling loop with a `break`. Since this is a // double-ended queue implementation this operation is of constant time // complexity (O(1)). seriespool.unshift(s); break; } if (fragment === undefined) { // That means that the current candidate `s` did not have a fragment // ready and that it has been put back into the pool. Get a new candidate // from the pool. continue; } fragments.push(fragment); s.lastFragmentConsumed = fragment; // Book-keeping for stop-criterion PER_STREAM_FRAGMENTS_CONSUMED_IN_CURRENT_CYCLE[s.uniqueName] += 1; if (fragments.length === nf) { log.debug(`seriespool.length: ${seriespool.length}`); log.debug(`write actor ${actorIndex}: collected ${nf} fragments`); return fragments; } } } async function produceAndPOSTpushrequestsUntilCycleStopCriterion( seriespool: Denque<LogSeries | MetricSeries>, nfppm: number, actorCount: number, actorIndex: number ) { // Repetitively call into tryToGetNFragmentsFromSeriesPool() precisely until // no fragments are returned anymore. while (true) { const fragments = await tryToGetNFragmentsFromSeriesPool( seriespool, nfppm, actorCount, actorIndex ); if (fragments.length === 0) { log.info( `write actor ${actorIndex}: tryToGetNFragmentsFromSeriesPool() ` + "return 0 fragments: work done, exit actor" ); return; } await _postFragments(fragments, actorIndex); // implement intra-cycle stop criteria if (CYCLE_STOP_WRITE_AFTER_SECONDS !== 0) { const secondsSinceCycleStart = mtimeDiffSeconds( CYCLE_START_TIME_MONOTONIC ); if (secondsSinceCycleStart > CYCLE_STOP_WRITE_AFTER_SECONDS) { log.info( `write actor ${actorIndex}: ${secondsSinceCycleStart.toFixed( 2 )} seconds passed: stop` ); return; } } // For each of the fragments pushed there is a corresponding series object // that maybe needs to be put back onto the work pool (it's important to // only do that now after the push message has been sent out) for (const f of fragments) { const s = f.parent!; if (CFG.cycle_stop_write_after_n_fragments !== 0) { if ( PER_STREAM_FRAGMENTS_CONSUMED_IN_CURRENT_CYCLE[s.uniqueName] === CFG.cycle_stop_write_after_n_fragments ) { log.debug( `write actor ${actorIndex}: CFG.cycle_stop_write_after_n_fragments ` + `(${CFG.cycle_stop_write_after_n_fragments}) ` + `pushed for ${s.uniqueName}, do not put back into work queue` ); continue; } } // Put back into work pool (left-hand side). All other actors might // have terminated by now because maybe temporarily the pool size // appeared as 0 (and in fact, was). Now that _this actor here_ is // adding back items onto the pool, we also have to make sure that this // actor here performs one more outer loop interation. seriespool.unshift(s); log.debug(`put ${s.uniqueName} back into work queue`); } } } async function _postFragments( fragments: Array<LogSeriesFragment | MetricSeriesFragment>, actorIndex: number ) { const t0 = mtime(); let pr: LogSeriesFragmentPushRequest | MetricSeriesFragmentPushMessage; if (CFG.metrics_mode) { pr = new MetricSeriesFragmentPushMessage( fragments as MetricSeriesFragment[] ); } else { pr = new LogSeriesFragmentPushRequest(fragments as LogSeriesFragment[]); } const genduration = mtimeDiffSeconds(t0); // the compiler thinks that this can be `undefined` as of the [0] -- but // it's confirmed (above) that this array is not empty. const firstseries = fragments[0].parent as LogSeries | MetricSeries; const fcount = fragments.length; const name = `write actor ${actorIndex}: _postFragments((nstreams=${fcount}, ` + `first=${firstseries.promQueryString()})`; if ( COUNTER_PUSHREQUEST_STATS_LOG_THROTTLE < 1 || COUNTER_PUSHREQUEST_STATS_LOG_THROTTLE % 200 == 0 ) { const firstFragment = pr.fragments[0]; const lastFragment = pr.fragments.slice(-1)[0]; log.info( `${name}: generated pushrequest msg in ${genduration.toFixed( 2 )} s with ` + `${fcount} series ` + `(first: ${ firstFragment.parent?.uniqueName }, index ${firstFragment.indexString(3)} -- ` + `last: ${ lastFragment.parent?.uniqueName }, index ${lastFragment.indexString(3)}), ` + `size: ${pr.dataLengthMiB.toFixed(4)} MiB). ` + "POST it (not logged for every case)." ); } COUNTER_PUSHREQUEST_STATS_LOG_THROTTLE++; const postT0 = mtime(); try { // Do not use pr.postWithRetryOrError() which is super simple, // but use a custom function with CLI arg-controlled retrying // parameters etc. await customPostWithRetryOrError(pr, CFG.apibaseurl); } catch (err: any) { log.crit("consider critical: %s", err); process.exit(1); } const postDurationSeconds = mtimeDiffSeconds(postT0); pm.hist_duration_post_with_retry_seconds.observe(postDurationSeconds); COUNTER_STREAM_FRAGMENTS_PUSHED = COUNTER_STREAM_FRAGMENTS_PUSHED + BigInt(fcount); pm.counter_fragments_pushed.inc(fcount); pm.counter_log_entries_pushed.inc(CFG.n_samples_per_series_fragment * fcount); // NOTE: payloadByteCount() includes timestamps. For logs, the timestamp // payload data (12 bytes per entry) might be small compared to the log // entry data. For metrics, the timestamp data is _larger than_ the // numerical sample data (8 bytes per sample). // Convert BigInt to Number and assume that the numbers are small enough pm.counter_payload_bytes_pushed.inc(Number(pr.payloadByteCount)); pm.counter_serialized_fragments_bytes_pushed.inc(pr.dataLengthBytes); pm.gauge_last_http_request_body_size_bytes.set(pr.dataLengthBytes); } /* Calculate delay in seconds _before_ performing the attempt `attempt`. Definition: attempt 1 is the first attempt, i.e. not a retry. */ function calcDelayBetweenPostRetries(attempt: number): number { if (attempt === 1) { return 0; } // Choose base delay using an exponential backoff technique. The base 1.6 is // chosen based on taste, by looking at the series: // // >>> [f'{b:.2f}' for b in ((1.6 ** a)/2.56 for a in range(2,10))] // ['1.00', '1.60', '2.56', '4.10', '6.55', '10.49', '16.78', '26.84'] // // The first value is for a = 2. That is, attempt 2 (which is the _first_ // retry!) is performed with a base delay of 1 second. const expBackoff = 1.6 ** attempt / 2.56; // Scale this (linearly) with the minimal desired delay time, so that between // the first two attempts the (unjittered) delay is precisely that time. const unjitteredDelay = expBackoff * CFG.retry_post_min_delay_seconds; // Add jitter: +/- 50 % (by default, with `CFG.retry_post_jitter` being set // to 0.5) of the so far chosen backoff value. const jitter = util.rndFloatFromInterval( -CFG.retry_post_jitter * unjitteredDelay, CFG.retry_post_jitter * unjitteredDelay ); const backoffPlusJitter = unjitteredDelay + jitter; log.debug( `calcDelayBetweenPostRetries: expBackoff: ${expBackoff.toFixed(2)}, ` + `unjitteredDelay: ${unjitteredDelay.toFixed(2)}, jitter: ${jitter.toFixed( 2 )} ` + `-> ${backoffPlusJitter.toFixed(2)}` ); if (backoffPlusJitter > CFG.retry_post_max_delay_seconds) { // Rely on the idea that the individual retrying process has been random // enough (accumulated enough jitter) so far, simply return this cap. log.debug( "calcDelayBetweenPostRetries: return cap: %s", CFG.retry_post_max_delay_seconds ); return CFG.retry_post_max_delay_seconds; } return backoffPlusJitter; } async function customPostWithRetryOrError( pr: LogSeriesFragmentPushRequest | MetricSeriesFragmentPushMessage, baseUrl: string ) { const deadline = mtimeDeadlineInSeconds(CFG.retry_post_deadline_seconds); let attempt = 0; // There are HTTP responses that indicate a problem in the receiving end, but // the insert of the data may nevertheless have succeeded. Typical // distributed systems problem. Keep note of that, so that a subsequent push // retry which fails with '400 out of order' is _not_ fatal. let previousPushSuccessAmbiguous = false; while (true) { attempt++; const delay = calcDelayBetweenPostRetries(attempt); if (attempt > 1) { log.info( "POST %s: schedule to perform attempt %s in %s s", pr, attempt, delay.toFixed(2) ); await sleep(delay); } const overDeadline = mtimeDiffSeconds(deadline); if (overDeadline > 0) { throw new Error( `Failed to POST ${pr}: attempt ${attempt} would trigger ` + `${overDeadline.toFixed(2)} s over the deadline (${ CFG.retry_post_deadline_seconds } s).` ); } setUptimeGauge(); let pushpath = "/loki/api/v1/push"; if (CFG.metrics_mode) { pushpath = "/api/v1/push"; } let response; try { response = await httpPostProtobuf( `${baseUrl}${pushpath}`, pr.data, pr.postHeaders ); } catch (e: any) { if (e instanceof got.RequestError) { // Note(JP): this code block is meant to handle only transient errors // (TCP conn errors/ timeout errors). I do hope that `e instanceof // got.RequestError` is not too specific, we will see. // Reflect this transient error in Prom counter. We could add a stream // name label here so that this error is associated with a specific // dummystream. pm.counter_post_non_http_errors.inc(); // Example log message: `POST // PushRequest(md5=434f0758a5df51275ba0f188ab9b07a2): attempt 1 failed // with: socket hang up` log.warning( `POST ${pr}: attempt ${attempt}: transient problem: ${e.message}` ); // Note that the request might have been written successfully and maybe // we're missing a success response because of an unfortunate TCP // connection breakdown. In this case, the write was successful but we // didn't receive the confirmation. We would land in here AFAIU, in the // `RequestError` handler and _could_ set // `previousPushSuccessAmbiguous` so that a subsequent 'out of order' // error wouldn't be fatal. But this should be done so that it's clear // that the request was actually written. Should be detectable, can // look into that later. // Note: doing this now, because seen the need in the wild: // https://github.com/opstrace/opstrace/issues/1328 // but this should be more precise, ideally. if ( e.message.includes("Timeout awaiting 'request'") || e.message.includes("Timeout awaiting 'response'") ) { previousPushSuccessAmbiguous = true; log.warning( `POST ${pr}: previousPushSuccessAmbiguous: set as of a ` + "got http client timeout for the 'request' or 'response' " + "phase -> next 'out or order' error not fatal" ); } // Move on to next attempt. continue; } else { // Assume that this is a programming error, let program crash. throw e; } } // Rely on that when we're here that we actually got an HTTP response, i.e. // a status code is known. pm.counter_post_responses.inc({ statuscode: response.statusCode }); if ([200, 204].includes(response.statusCode)) { util.logHTTPResponseLight(response, `${pr}`); markPushMessageAsSuccessfullySent(pr); return; } if (response.statusCode === 429) { log.info( `POST ${pr}: 429 resp, sleep 2, body[:200]: ${response.body.slice( 0, 200 )}` ); // Move on to next attempt. continue; } // We got an HTTP response that reveals a request error or a transient // problem. We want to learn as much as we can about both: log HTTP // response in more detail. util.logHTTPResponse(response, `${pr}`); // Handle 4xx responses (most likely permanent errors with the request) if (response.statusCode.toString().startsWith("4")) { // Special-case treatment of out-of-order err after ambiguous previous push if (response.statusCode === 400) { if (response.body.includes("out of order sample")) { if (previousPushSuccessAmbiguous) { log.warning( "POST %s: saw 'out of order' error but do not treat fatal as of previous ambiguous push result", pr ); // Treat this push message as successfully inserted. markPushMessageAsSuccessfullySent(pr); return; } } } throw new Error(`POST ${pr}: Bad HTTP request (see log above)`); } if (response.statusCode === 500) { // Note(JP): this is a real-world example I have seen where the receiving // system internally generated a 'DeadlineExceeded' error and wrapped it // into a 500 response -- the next push retry then failed with a 400 out // of order error. const needles = [ "DeadlineExceeded", "code = Unavailable desc = transport is closing" ]; for (const n in needles) { if (response.body.includes(n)) { previousPushSuccessAmbiguous = true; log.warning( `POST ${pr}: previousPushSuccessAmbiguous: set as of a` + `500(${n}) response, next 'out or order' error not fatal` ); } } } // All other HTTP responses: treat as transient problems log.info("POST %s: Treat as transient problem, retry after sleep", pr); } } // should this be a method on pushmessage class? function markPushMessageAsSuccessfullySent( pr: LogSeriesFragmentPushRequest | MetricSeriesFragmentPushMessage ) { // Keep track of the fact that this was successfully pushed out, // important for e.g. read-based validation after write. // A push message can contain more than one time series fragment. for (const f of pr.fragments) { if (f.parent!.shouldBeValidated()) { // Drop actual samples (otherwise mem usage could grow quite fast). f.buildStatisticsAndDropData(); f.parent!.rememberFragmentForValidation(f); } } } // The Loki query system may get overwhelmed easily (emitting 500s and 502s). // for now all we need is a functioning readout, even if it's slow-ish. // therefore, retry a couple of times (no backoff for simplicity for now). this // retry loop is intended for transient TCP errors and transient HTTP errors // (5xx, also 429) async function httpGETRetryUntil200OrError( url: string, gotRequestOptions: any ): Promise<GotResponse<string>> { const maxRetries = 10; for (let attempt = 1; attempt <= maxRetries; attempt++) { setUptimeGauge(); let response; // If desired, decorate HTTP request with authentication token. if (BEARER_TOKEN) { if (gotRequestOptions.headers === undefined) { gotRequestOptions.headers = {}; } gotRequestOptions.headers["Authorization"] = `Bearer ${BEARER_TOKEN}`; } try { response = await got(url, gotRequestOptions); } catch (e: any) { if (e instanceof got.RequestError) { // Note(JP): this code block is meant to handle only transient errors // (TCP conn errors/ timeout errors). I do hope that `e instanceof // got.RequestError` is not too specific, we will see. // Reflect this transient error in Prom counter. We could add a stream // name label here so that this error is associated with a specific // dummystream. pm.counter_get_non_http_errors.inc(); log.warning( `Query: attempt ${attempt}/${maxRetries} failed with ${e.message}` ); // Note(JP): pragmatic time constant for now await sleep(3.0); // Move on to next attempt. continue; } else { // Assume that this is a programming error, let program crash. throw e; } } // Rely on that when we're here that we actually got an HTTP response, // i.e. a status code is known. pm.counter_get_responses.inc({ statuscode: response.statusCode }); if (response.statusCode === 200) { util.logHTTPResponseLight(response); // In the corresponding LogSeries object keep track of the fact that // this was successfully pushed out, important for e.g. read-based // validation after write. return response; } if (response.statusCode === 429) { log.info(`429 resp, sleep 2, body[:200]: ${response.body.slice(0, 200)}`); await sleep(3.0); // Move on to next attempt. continue; } // We got an HTTP response that reveals a request error or a transient // problem. We want to learn as much as we can about both: log HTTP // response in more detail. util.logHTTPResponse(response); // Handle what's most likely permanent errors with the request if (response.statusCode.toString().startsWith("4")) { throw new Error("Bad HTTP request (see log above)"); } // All other HTTP responses: treat as transient problems log.info("Treat as transient problem, retry"); } throw new Error( `Failed to GET after ${maxRetries} attempts. Request options: ${JSON.stringify( gotRequestOptions, null, 2 )}` ); } async function queryLokiWithRetryOrError( lokiQuerierBaseUrl: string, additionalHeaders: Record<string, string>, queryParams: Record<string, string>, expectedEntryCount: number, chunkIndex: number, stream: LogSeries ): Promise<LokiQueryResult> { log.debug("looker-specific query func"); // wrap httpGETRetryUntil200OrError() and inspect entry count. async function _queryAndCountEntries( lokiQuerierBaseUrl: string, queryParams: Record<string, string> ) { // httpGETRetryUntil200OrError() retries internally upon transient // problems. If no error this thrown then `response` represents a 200 HTTP // response. const url = `${CFG.apibaseurl}/loki/api/v1/query_range`; const gotRequestOptions = { retry: 0, throwHttpErrors: false, searchParams: new URLSearchParams(queryParams), timeout: util.httpTimeoutSettings, https: { rejectUnauthorized: false } // disable TLS server cert verification for now }; const response = await httpGETRetryUntil200OrError(url, gotRequestOptions); const data = JSON.parse(response.body); if (data.data === undefined || data.data.result === undefined) { throw new Error( `unexpected JSON doc: ${JSON.stringify(data, null, 2).slice(0, 400)}}` ); } if (data.data.result.length !== 1) { throw new Error( `data.data.result.length: expected 1, but got ${data.data.result.length}}` ); } // expect 1 stream with non-zero entries, maybe assert on that here. const entrycount = data.data.result[0].values.length; // log.info( // "expected nbr of query results: %s, got %s", // expectedEntryCount, // entrycount // ); // Expect N log entries in the stream. if (entrycount === expectedEntryCount) { const labels = data.data.result[0].stream; //logqlKvPairTextToObj(data["streams"][0]["labels"]); const result: LokiQueryResult = { entries: data.data.result[0].values, labels: labels, textmd5: "disabled" }; return result; } throw new Error( `unexpected entry count returned in query result: ${entrycount} ` + `(expected: ${expectedEntryCount}). stream: ${stream.uniqueName} chunkIndex: ${chunkIndex}` ); } // Retry `_queryAndCountEntries` N times. It has an inner retry loop for // transient errors. This outer retry loop retries upon errors like // unexpected count of log entries in query result (which might be a // permanent error condition or actually be resolved with a retry, need to // know). const maxRetries = 3; for (let attempt = 1; attempt <= maxRetries; attempt++) { try { return await _queryAndCountEntries(lokiQuerierBaseUrl, queryParams); } catch (err: any) { pm.counter_unexpected_query_results.inc(); log.warning( `_queryAndCountEntries() failed with \`${err.message}\`, retry soon` ); await sleep(5.0); } } throw new Error( `_queryAndCountEntries() failed ${maxRetries} times. ` + `stream: ${stream.uniqueName} chunkIndex: ${chunkIndex}` ); } async function httpPostProtobuf( url: string, data: Buffer, headers: Record<string, string> ) { // log.info("httpPostProtobuf data: %s", data); if (BEARER_TOKEN) { headers = { ...headers, Authorization: `Bearer ${BEARER_TOKEN}` }; } const response = await got.post(url, { body: data, throwHttpErrors: false, headers: headers, https: { rejectUnauthorized: false }, // disable TLS server cert verification for now timeout: { // If a TCP connect() takes longer then ~5 seconds then most certainly there // is a backpressure or networking issue, fail fast in that case. connect: 12000, // After TCP-connect, this controls the time it takes for the TLS handshake secureConnect: 5000, // after (secure)connect, require request to be written to connection within // ~20 seconds. send: 20000, // After having written the request, expect response _headers_ to arrive // within that time (not the complete response). response: 60000, // global timeout, supposedly until final response byte arrived. request: 80000 } }); return response; } // https://stackoverflow.com/a/6090287/145400 if (require.main === module) { process.on("SIGINT", function () { log.info("Received SIGINT, exiting"); process.exit(1); }); // NodeJS 12 does not crash by default upon unhandled promise rejections. // Make it crash. process.on("unhandledRejection", err => { throw err; }); main(); }
the_stack
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import JqxButton from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxbuttons'; import JqxScheduler, { ISchedulerProps, jqx } from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxscheduler'; class App extends React.PureComponent<{}, ISchedulerProps> { private myScheduler = React.createRef<JqxScheduler>(); private printButton = React.createRef<JqxButton>(); constructor(props: {}) { super(props); const appointments = new Array(); const appointment1 = { calendar: "East Coast Events", description: "George brings projector for presentations.", end: new Date(2017, 10, 18, 16, 0, 0), id: "id1", location: "", start: new Date(2017, 10, 15, 9, 0, 0), subject: "Fashion Expo" }; const appointment2 = { calendar: "Middle West Events", description: "", end: new Date(2017, 10, 22, 15, 0, 0), id: "id2", location: "", start: new Date(2017, 10, 20, 10, 0, 0), subject: "Cloud Data Expo" }; const appointment3 = { calendar: "West Coast Events", description: "", end: new Date(2017, 10, 28, 13, 0, 0), id: "id3", location: "", start: new Date(2017, 10, 23, 11, 0, 0), subject: "Digital Media Conference" }; const appointment4 = { calendar: "West Coast Events", description: "", end: new Date(2017, 10, 12, 18, 0, 0), id: "id4", location: "", start: new Date(2017, 10, 10, 16, 0, 0), subject: "Modern Software Development Conference" }; const appointment5 = { calendar: "Middle West Events", description: "", end: new Date(2017, 10, 6, 17, 0, 0), id: "id5", location: "", start: new Date(2017, 10, 5, 15, 0, 0), subject: "Marketing Future Expo" }; const appointment6 = { calendar: "East Coast Events", description: "", end: new Date(2017, 10, 20, 16, 0, 0), id: "id6", location: "", start: new Date(2017, 10, 13, 14, 0, 0), subject: "Future Computing" }; appointments.push(appointment1); appointments.push(appointment2); appointments.push(appointment3); appointments.push(appointment4); appointments.push(appointment5); appointments.push(appointment6); const source: any = { dataFields: [ { name: 'id', type: 'string' }, { name: 'description', type: 'string' }, { name: 'location', type: 'string' }, { name: 'subject', type: 'string' }, { name: 'calendar', type: 'string' }, { name: 'start', type: 'date' }, { name: 'end', type: 'date' } ], dataType: "array", id: 'id', localData: appointments }; const dataAdapter: any = new jqx.dataAdapter(source); this.state = { appointmentDataFields: { description: "description", from: "start", id: "id", location: "location", resourceId: "calendar", subject: "subject", to: "end" }, date: new jqx.date(2017, 11, 23), /** * called when the dialog is closed. * @param {Object} dialog - jqxWindow's jQuery object. * @param {Object} fields - Object with all widgets inside the dialog. * @param {Object} the selected appointment instance or NULL when the dialog is opened from cells selection. */ editDialogClose: (dialog: any, fields: any, editAppointment: any) => { // editDialogClose callback }, // called when the dialog is craeted. editDialogCreate: (dialog: any, fields: any, editAppointment: any) => { // hide repeat option fields.repeatContainer.hide(); // hide status option fields.statusContainer.hide(); // hide timeZone option fields.timeZoneContainer.hide(); // hide color option fields.colorContainer.hide(); fields.subjectLabel.html("Title"); fields.locationLabel.html("Where"); fields.fromLabel.html("Start"); fields.toLabel.html("End"); fields.resourceLabel.html("Calendar"); const buttonContainer = document.createElement("div"); buttonContainer.style.cssFloat = 'right'; buttonContainer.style.marginLeft = '5px'; fields.buttons[0].appendChild(buttonContainer); const printingFunction = (event: any) => { const appointmentContent = "<table class='printTable'>" + "<tr>" + "<td class='label'>Title</td>" + "<td>" + fields.subject.val() + "</td>" + "</tr>" + "<tr>" + "<td class='label'>Start</td>" + "<td>" + fields.from.val() + "</td>" + "</tr>" + "<tr>" + "<td class='label'>End</td>" + "<td>" + fields.to.val() + "</td>" + "</tr>" + "<tr>" + "<td class='label'>Where</td>" + "<td>" + fields.location.val() + "</td>" + "</tr>" + "<tr>" + "<td class='label'>Calendar</td>" + "<td>" + fields.resource.val() + "</td>" + "</tr>" + "</table>"; const newWindow = window.open("", "", "width=800, height=500"); const document = newWindow!.document.open(); const pageContent = '<!DOCTYPE html>\n' + '<html>\n' + '<head>\n' + '<meta charset="utf-8" />\n' + '<title>jQWidgets Scheduler</title>\n' + '<style>\n' + '.printTable {\n' + 'border-color: #aaa;\n' + '}\n' + '.printTable .label {\n' + 'font-weight: bold;\n' + '}\n' + '.printTable td{\n' + 'padding: 4px 3px;\n' + 'border: 1px solid #DDD;\n' + 'vertical-align: top;\n' + '}\n' + '</style>' + '</head>\n' + '<body>\n' + appointmentContent + '\n</body>\n</html>'; try { document.write(pageContent); document.close(); } catch (error) { // error handler } newWindow!.print(); } const printButton = <JqxButton theme={'material-purple'} ref={this.printButton} onClick={printingFunction} width={40} height={16} > Print </JqxButton>; ReactDOM.render( printButton, buttonContainer ); }, /** * called when a key is pressed while the dialog is on focus. Returning true or false as a result disables the built-in keyDown handler. * @param {Object} dialog - jqxWindow's jQuery object. * @param {Object} fields - Object with all widgets inside the dialog. * @param {Object} editAppointment the selected appointment instance or NULL when the dialog is opened from cells selection. * @param {jQuery.Event Object} the keyDown event. */ editDialogKeyDown: (dialog: any, fields: any, editAppointment: any, event: any) => { // editDialogKeyDown callback return false; }, /** * called when the dialog is opened. Returning true as a result disables the built-in handler. * @param {Object} dialog - jqxWindow's jQuery object. * @param {Object} fields - Object with all widgets inside the dialog. * @param {Object} the selected appointment instance or NULL when the dialog is opened from cells selection. */ editDialogOpen: (dialog: any, fields: any, editAppointment: any) => { if (!editAppointment && this.printButton.current!) { this.printButton.current!.setOptions({ disabled: true }); } else if (editAppointment && this.printButton) { this.printButton.current!.setOptions({ disabled: false }); } }, height: 600, resources: { colorScheme: "scheme01", dataField: "calendar", source: new jqx.dataAdapter(source) }, source: dataAdapter, views: [ 'dayView', 'weekView', 'monthView' ] }; } public render() { return ( <JqxScheduler theme={'material-purple'} ref={this.myScheduler} // @ts-ignore width={'100%'} height={this.state.height} date={this.state.date} source={this.state.source} showLegend={true} editDialogCreate={this.state.editDialogCreate} editDialogOpen={this.state.editDialogOpen} editDialogClose={this.state.editDialogClose} editDialogKeyDown={this.state.editDialogKeyDown} resources={this.state.resources} view={'monthView'} views={this.state.views} appointmentDataFields={this.state.appointmentDataFields} /> ); } } export default App;
the_stack
interface CommonClipOptions { /** * By default, we try to break only at word boundaries. Set to true if this is undesired. */ breakWords?: boolean; /** * Set to `true` if the string is HTML-encoded. If so, this method will take extra care to make * sure the HTML-encoding is correctly maintained. */ html?: boolean; /** * The string to insert to indicate clipping. Default: "…". */ indicator?: string; /** * Maximum amount of lines allowed. If given, the string will be clipped either at the moment * the maximum amount of characters is exceeded or the moment maxLines newlines are discovered, * whichever comes first. */ maxLines?: number; } interface ClipPlainTextOptions extends CommonClipOptions { html?: false; } interface ClipHtmlOptions extends CommonClipOptions { html: true; /** * The amount of characters to assume for images. This is used whenever an image is encountered, * but also for SVG and MathML content. Default: `2`. */ imageWeight?: number; } type ClipOptions = ClipPlainTextOptions | ClipHtmlOptions; // Void elements are elements without inner content, // which close themselves regardless of trailing slash. // E.g. both <br> and <br /> are self-closing. const VOID_ELEMENTS = [ "area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr", ]; // Block elements trigger newlines where they're inserted, // and are always safe places for truncation. const BLOCK_ELEMENTS = [ "address", "article", "aside", "blockquote", "canvas", "dd", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "li", "main", "nav", "noscript", "ol", "output", "p", "pre", "section", "table", "tbody", "tfoot", "thead", "tr", "ul", "video", ]; const NEWLINE_CHAR_CODE = 10; // '\n' const EXCLAMATION_CHAR_CODE = 33; // '!' const DOUBLE_QUOTE_CHAR_CODE = 34; // '"' const AMPERSAND_CHAR_CODE = 38; // '&' const SINGLE_QUOTE_CHAR_CODE = 39; // '\'' const FORWARD_SLASH_CHAR_CODE = 47; // '/' const SEMICOLON_CHAR_CODE = 59; // ';' const TAG_OPEN_CHAR_CODE = 60; // '<' const EQUAL_SIGN_CHAR_CODE = 61; // '=' const TAG_CLOSE_CHAR_CODE = 62; // '>' const CHAR_OF_INTEREST_REGEX = /[<&\n\ud800-\udbff]/; const SIMPLIFY_WHITESPACE_REGEX = /\s{2,}/g; /** * Clips a string to a maximum length. If the string exceeds the length, it is truncated and an * indicator (an ellipsis, by default) is appended. * * In detail, the clipping rules are as follows: * - The resulting clipped string may never contain more than maxLength characters. Examples: * - clip("foo", 3) => "foo" * - clip("foo", 2) => "f…" * - The indicator is inserted if and only if the string is clipped at any place other than a * newline. Examples: * - clip("foo bar", 5) => "foo …" * - clip("foo\nbar", 5) => "foo" * - If the html option is true and valid HTML is inserted, the clipped output *must* also be valid * HTML. If the input is not valid HTML, the result is undefined (not to be confused with JS' * "undefined" type; some errors might be detected and result in an exception, but this is not * guaranteed). * * @param string The string to clip. * @param maxLength The maximum length of the clipped string in number of characters. * @param options Optional options object. * * @return The clipped string. */ export default function clip(string: string, maxLength: number, options: ClipOptions = {}): string { if (!string) { return ""; } string = string.toString(); return options.html ? clipHtml(string, maxLength, options) : clipPlainText(string, maxLength, options); } function clipHtml(string: string, maxLength: number, options: ClipHtmlOptions): string { const { imageWeight = 2, indicator = "\u2026", maxLines = Infinity } = options; let numChars = indicator.length; let numLines = 1; let i = 0; let isUnbreakableContent = false; const tagStack: Array<string> = []; // Stack of currently open HTML tags. const { length } = string; for (; i < length; i++) { const rest = i ? string.slice(i) : string; const nextIndex = rest.search(CHAR_OF_INTEREST_REGEX); const nextBlockSize = nextIndex > -1 ? nextIndex : rest.length; i += nextBlockSize; if (!isUnbreakableContent) { if (shouldSimplifyWhiteSpace(tagStack)) { numChars += simplifyWhiteSpace( nextBlockSize === rest.length ? rest : rest.slice(0, nextIndex), ).length; if (numChars > maxLength) { i -= nextBlockSize; // We just cut off the entire incorrectly placed text... break; } } else { numChars += nextBlockSize; if (numChars > maxLength) { i = Math.max(i - numChars + maxLength, 0); break; } } } if (nextIndex === -1) { break; } const charCode = string.charCodeAt(i); if (charCode === TAG_OPEN_CHAR_CODE) { const nextCharCode = string.charCodeAt(i + 1); const isSpecialTag = nextCharCode === EXCLAMATION_CHAR_CODE; if (isSpecialTag && string.substr(i + 2, 2) === "--") { const commentEndIndex = string.indexOf("-->", i + 4) + 3; i = commentEndIndex - 1; // - 1 because the outer for loop will increment it } else if (isSpecialTag && string.substr(i + 2, 7) === "[CDATA[") { const cdataEndIndex = string.indexOf("]]>", i + 9) + 3; i = cdataEndIndex - 1; // - 1 because the outer for loop will increment it // note we don't count CDATA text for our character limit because it is only // allowed within SVG and MathML content, both of which we don't clip } else { // don't open new tags if we are currently at the limit if ( numChars === maxLength && string.charCodeAt(i + 1) !== FORWARD_SLASH_CHAR_CODE ) { numChars++; break; } let attributeQuoteCharCode = 0; let endIndex = i; let isAttributeValue = false; while (true /* eslint-disable-line */) { endIndex++; if (endIndex >= length) { throw new Error(`Invalid HTML: ${string}`); } const charCode = string.charCodeAt(endIndex); if (isAttributeValue) { if (attributeQuoteCharCode) { if (charCode === attributeQuoteCharCode) { isAttributeValue = false; } } else { if (isWhiteSpace(charCode)) { isAttributeValue = false; } else if (charCode === TAG_CLOSE_CHAR_CODE) { isAttributeValue = false; endIndex--; // re-evaluate this character } } } else if (charCode === EQUAL_SIGN_CHAR_CODE) { while (isWhiteSpace(string.charCodeAt(endIndex + 1))) { endIndex++; // skip whitespace } isAttributeValue = true; const firstAttributeCharCode = string.charCodeAt(endIndex + 1); if ( firstAttributeCharCode === DOUBLE_QUOTE_CHAR_CODE || firstAttributeCharCode === SINGLE_QUOTE_CHAR_CODE ) { attributeQuoteCharCode = firstAttributeCharCode; endIndex++; } else { attributeQuoteCharCode = 0; } } else if (charCode === TAG_CLOSE_CHAR_CODE) { const isEndTag = string.charCodeAt(i + 1) === FORWARD_SLASH_CHAR_CODE; const tagNameStartIndex = i + (isEndTag ? 2 : 1); const tagNameEndIndex = Math.min( indexOfWhiteSpace(string, tagNameStartIndex), endIndex, ); let tagName = string .slice(tagNameStartIndex, tagNameEndIndex) .toLowerCase(); if (tagName.charCodeAt(tagName.length - 1) === FORWARD_SLASH_CHAR_CODE) { // Remove trailing slash for self-closing tag names like <br/> tagName = tagName.slice(0, tagName.length - 1); } if (isEndTag) { const currentTagName = tagStack.pop(); if (currentTagName !== tagName) { throw new Error(`Invalid HTML: ${string}`); } if (tagName === "math" || tagName === "svg") { isUnbreakableContent = tagStack.includes("math") || tagStack.includes("svg"); if (!isUnbreakableContent) { numChars += imageWeight; if (numChars > maxLength) { break; } } } if (BLOCK_ELEMENTS.includes(tagName)) { // All block level elements should trigger a new line // when truncating if (!isUnbreakableContent) { numLines++; if (numLines > maxLines) { // If we exceed the max lines, push the tag back onto the // stack so that it will be added back correctly after // truncation tagStack.push(tagName); break; } } } } else if ( VOID_ELEMENTS.includes(tagName) || string.charCodeAt(endIndex - 1) === FORWARD_SLASH_CHAR_CODE ) { if (tagName === "br") { numLines++; if (numLines > maxLines) { break; } } else if (tagName === "img") { numChars += imageWeight; if (numChars > maxLength) { break; } } } else { tagStack.push(tagName); if (tagName === "math" || tagName === "svg") { isUnbreakableContent = true; } } i = endIndex; break; } } if (numChars > maxLength || numLines > maxLines) { break; } } } else if (charCode === AMPERSAND_CHAR_CODE) { let endIndex = i + 1; let isCharacterReference = true; while (true /* eslint-disable-line */) { const charCode = string.charCodeAt(endIndex); if (isCharacterReferenceCharacter(charCode)) { endIndex++; } else if (charCode === SEMICOLON_CHAR_CODE) { break; } else { isCharacterReference = false; break; } } if (!isUnbreakableContent) { numChars++; if (numChars > maxLength) { break; } } if (isCharacterReference) { i = endIndex; } } else if (charCode === NEWLINE_CHAR_CODE) { if (!isUnbreakableContent && !shouldSimplifyWhiteSpace(tagStack)) { numChars++; if (numChars > maxLength) { break; } numLines++; if (numLines > maxLines) { break; } } } else { if (!isUnbreakableContent) { numChars++; if (numChars > maxLength) { break; } } // high Unicode surrogate should never be separated from its matching low surrogate const nextCharCode = string.charCodeAt(i + 1); if ((nextCharCode & 0xfc00) === 0xdc00) { i++; } } } if (numChars > maxLength) { let nextChar = takeHtmlCharAt(string, i); if (indicator) { let peekIndex = i + nextChar.length; while ( string.charCodeAt(peekIndex) === TAG_OPEN_CHAR_CODE && string.charCodeAt(peekIndex + 1) === FORWARD_SLASH_CHAR_CODE ) { const nextPeekIndex = string.indexOf(">", peekIndex + 2) + 1; if (nextPeekIndex) { peekIndex = nextPeekIndex; } else { break; } } if (peekIndex && (peekIndex === string.length || isLineBreak(string, peekIndex))) { // if there's only a single character remaining in the input string, or the next // character is followed by a line-break, we can include it instead of the clipping // indicator (provided it's not a special HTML character) i += nextChar.length; nextChar = string.charAt(i); } } // include closing tags before adding the clipping indicator if that's where they // are in the input string while (nextChar === "<" && string.charCodeAt(i + 1) === FORWARD_SLASH_CHAR_CODE) { const tagName = tagStack.pop(); const tagEndIndex = tagName ? string.indexOf(">", i + 2) : -1; if (tagEndIndex === -1 || string.slice(i + 2, tagEndIndex).trim() !== tagName) { throw new Error(`Invalid HTML: ${string}`); } i = tagEndIndex + 1; nextChar = string.charAt(i); } if (i < string.length) { if (!options.breakWords) { // try to clip at word boundaries, if desired for (let j = i - indicator.length; j >= 0; j--) { const charCode = string.charCodeAt(j); if (charCode === TAG_CLOSE_CHAR_CODE || charCode === SEMICOLON_CHAR_CODE) { // these characters could be just regular characters, so if they occur in // the middle of a word, they would "break" our attempt to prevent breaking // of words, but given this seems highly unlikely and the alternative is // doing another full parsing of the preceding text, this seems acceptable. break; } else if (charCode === NEWLINE_CHAR_CODE || charCode === TAG_OPEN_CHAR_CODE) { i = j; break; } else if (isWhiteSpace(charCode)) { i = j + (indicator ? 1 : 0); break; } } } let result = string.slice(0, i); if (!isLineBreak(string, i)) { result += indicator; } while (tagStack.length) { const tagName = tagStack.pop(); result += `</${tagName}>`; } return result; } } else if (numLines > maxLines) { let result = string.slice(0, i); while (tagStack.length) { const tagName = tagStack.pop(); result += `</${tagName}>`; } return result; } return string; } function clipPlainText(string: string, maxLength: number, options: CommonClipOptions): string { const { indicator = "\u2026", maxLines = Infinity } = options; let numChars = indicator.length; let numLines = 1; let i = 0; const { length } = string; for (; i < length; i++) { numChars++; if (numChars > maxLength) { break; } const charCode = string.charCodeAt(i); if (charCode === NEWLINE_CHAR_CODE) { numLines++; if (numLines > maxLines) { break; } } else if ((charCode & 0xfc00) === 0xd800) { // high Unicode surrogate should never be separated from its matching low surrogate const nextCharCode = string.charCodeAt(i + 1); if ((nextCharCode & 0xfc00) === 0xdc00) { i++; } } } if (numChars > maxLength) { let nextChar = takeCharAt(string, i); if (indicator) { const peekIndex = i + nextChar.length; if (peekIndex === string.length) { return string; } else if (string.charCodeAt(peekIndex) === NEWLINE_CHAR_CODE) { return string.slice(0, i + nextChar.length); } } if (!options.breakWords) { // try to clip at word boundaries, if desired for (let j = i - indicator.length; j >= 0; j--) { const charCode = string.charCodeAt(j); if (charCode === NEWLINE_CHAR_CODE) { i = j; nextChar = "\n"; break; } else if (isWhiteSpace(charCode)) { i = j + (indicator ? 1 : 0); break; } } } return string.slice(0, i) + (nextChar === "\n" ? "" : indicator); } else if (numLines > maxLines) { return string.slice(0, i); } return string; } function indexOfWhiteSpace(string: string, fromIndex: number): number { const { length } = string; for (let i = fromIndex; i < length; i++) { if (isWhiteSpace(string.charCodeAt(i))) { return i; } } // Rather than -1, this function returns the length of the string if no match is found, // so it works well with the Math.min() usage above: return length; } function isCharacterReferenceCharacter(charCode: number): boolean { return ( (charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) ); } function isLineBreak(string: string, index: number): boolean { const firstCharCode = string.charCodeAt(index); if (firstCharCode === NEWLINE_CHAR_CODE) { return true; } else if (firstCharCode === TAG_OPEN_CHAR_CODE) { const newlineElements = `(${BLOCK_ELEMENTS.join("|")}|br)`; const newlineRegExp = new RegExp(`^<${newlineElements}[\t\n\f\r ]*/?>`, "i"); return newlineRegExp.test(string.slice(index)); } else { return false; } } function isWhiteSpace(charCode: number): boolean { return ( charCode === 9 || charCode === 10 || charCode === 12 || charCode === 13 || charCode === 32 ); } /** * Certain tags don't display their whitespace-only content. In such cases, we * should simplify the whitespace before counting it. */ function shouldSimplifyWhiteSpace(tagStack: Array<string>): boolean { for (let i = tagStack.length - 1; i >= 0; i--) { const tagName = tagStack[i]; if (tagName === "li" || tagName === "td") { return false; } if (tagName === "ol" || tagName === "table" || tagName === "ul") { return true; } } return false; } function simplifyWhiteSpace(string: string): string { return string.trim().replace(SIMPLIFY_WHITESPACE_REGEX, " "); } function takeCharAt(string: string, index: number): string { const charCode = string.charCodeAt(index); if ((charCode & 0xfc00) === 0xd800) { // high Unicode surrogate should never be separated from its matching low surrogate const nextCharCode = string.charCodeAt(index + 1); if ((nextCharCode & 0xfc00) === 0xdc00) { return String.fromCharCode(charCode, nextCharCode); } } return String.fromCharCode(charCode); } function takeHtmlCharAt(string: string, index: number): string { let char = takeCharAt(string, index); if (char === "&") { while (true /* eslint-disable-line */) { index++; const nextCharCode = string.charCodeAt(index); if (isCharacterReferenceCharacter(nextCharCode)) { char += String.fromCharCode(nextCharCode); } else if (nextCharCode === SEMICOLON_CHAR_CODE) { char += String.fromCharCode(nextCharCode); break; } else { break; } } } return char; }
the_stack
import * as vscode from "vscode"; const util = require("util"); const path = require("path"); const zmq = require("zeromq"); import * as child_process from "child_process"; import { readFileSync, writeFile } from "fs"; import { deserializeMarkup } from "./markdown-serializer"; import { tex2svg } from "./load-mathjax"; import { ExecutionQueue } from "./notebook-kernel"; import { KernelStatusBarItem, ExportNotebookStatusBarItem, NotebookOutputPanel } from "./ui-items"; import { NotebookConfig } from "./notebook-config"; export class WLNotebookController { readonly id = "wolfram-language-notebook-controller"; readonly notebookType = "wolfram-language-notebook"; readonly label = 'Wolfram Language'; readonly supportedLanguages = [ "wolfram" ]; private readonly controller: vscode.NotebookController; private selectedNotebooks: Set<vscode.NotebookDocument> = new Set(); private statusBarKernelItem = new KernelStatusBarItem(this.supportedLanguages); private statusBarExportItem = new ExportNotebookStatusBarItem(); private outputPanel = new NotebookOutputPanel("Wolfram Language Notebook"); private config = new NotebookConfig(); private extensionPath: string = ""; private disposables: any[] = []; private kernel: any; private socket: any; private restartAfterExitKernel = false; private connectingtoKernel = false; private executionQueue = new ExecutionQueue(); constructor() { this.extensionPath = vscode.extensions.getExtension("njpipeorgan.wolfram-language-notebook")?.extensionPath || ""; if (!this.extensionPath) { throw Error(); } this.outputPanel.print(`WLNotebookController(), this.extensionPath = ${this.extensionPath}`); this.controller = vscode.notebooks.createNotebookController(this.id, this.notebookType, this.label); this.controller.supportedLanguages = this.supportedLanguages; this.controller.supportsExecutionOrder = true; this.controller.executeHandler = this.execute.bind(this); this.controller.onDidChangeSelectedNotebooks(({ notebook, selected }) => { if (selected) { this.selectedNotebooks.add(notebook); this.outputPanel.print(`The controller is selected for a notebook ${notebook.uri.fsPath}`); if (this.selectedNotebooks.size === 1 && !this.kernelConnected()) { // when the controller is selected for the first time const defaultKernel = this.config.get("kernel.connectOnOpeningNotebook"); if (defaultKernel) { this.launchKernel(this.config.get("kernel.connectOnOpeningNotebook") as string); } } } else { this.selectedNotebooks.delete(notebook); this.outputPanel.print(`The controller is unselected for a notebook ${notebook.uri.fsPath}`); } this.outputPanel.print(`There are ${this.selectedNotebooks.size} notebook(s) for which the controller is selected.`); if (this.selectedNotebooks.size === 0 && this.config.get("kernel.quitAutomatically")) { // when the last notebook was closed, and the user choose to quit kernel automatically this.quitKernel(); } }); // when notebook config changes, send a message to the kernel this.config.onDidChange((config: NotebookConfig) => { this.postMessageToKernel({type: "set-config", config: config.getKernelRelatedConfigs()}); }); this.disposables.push(this.statusBarKernelItem); this.disposables.push(this.statusBarExportItem); this.disposables.push(this.outputPanel); this.disposables.push(this.config); this.controller.dispose = () => { this.quitKernel(); this.outputPanel.print(`Notebook controller is disposed; there are ${this.disposables.length} disposables.`); this.disposables.forEach(item => { item.dispose(); }); }; } getController() { return this.controller; } private getRandomPort(portRanges: string) { let ranges = [...portRanges.matchAll(/\s*(\d+)\s*(?:[-‐‑‒–]\s*(\d+)\s*)?/g)] .map(match => [parseInt(match[1]), parseInt(match[match[2] === undefined ? 1 : 2])]) .map(pair => [Math.max(Math.min(pair[0], pair[1]), 1), Math.min(Math.max(pair[0], pair[1]) + 1, 65536)]) .filter(pair => pair[0] < pair[1]); if (ranges.length === 0) { ranges = [[49152, 65536]]; } let cmf: number[] = []; ranges.reduce((acc, pair, i) => { cmf[i] = acc + (pair[1] - pair[0]); return cmf[i]; }, 0); const rand = Math.random() * cmf[cmf.length - 1]; for (let i = 0; i < cmf.length; ++i) { if (rand <= cmf[i]) { const lower = ranges[i][0]; const upper = ranges[i][1]; return Math.min(Math.floor(Math.random() * (upper - lower)) + lower, upper - 1); } } } private postMessageToKernel(message: any) { if (this.socket !== undefined) { this.socket.send(typeof message === 'string' ? message : JSON.stringify(message)); } else { this.outputPanel.print("The socket is not available; cannot post the message."); } } private writeFileChecked(path: string, text: string | Uint8Array) { writeFile(path, text, err => { if (err) { vscode.window.showErrorMessage(`Unable to write file ${path} \n${err.message}`, "Retry", "Save As...", "Dismiss").then(value => { if (value === "Retry") { this.writeFileChecked(path, text); } else if (value === "Save As...") { vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file(path), filters: { "All Files": ["*"] } }).then(value => { if (value) { this.writeFileChecked(value.fsPath, text); } }); } }); return; } }); } private async handleMessageFromKernel() { while (true) { let [message] = await this.socket.receive().catch(() => { if (this.kernelConnected()) { this.outputPanel.print(`Failed to receive messages from the kernel, but the kernel is connected.`); } return [new Error("receive-message")]; }); if (message instanceof Error) { return; } message = Buffer.from(message).toString("utf-8"); try { message = JSON.parse(message); } catch (error) { this.outputPanel.print("Failed to parse the following message:"); this.outputPanel.print(message); continue; } const id = message?.uuid || ""; const execution = this.executionQueue.find(id); switch (message.type) { case "show-input-name": if (execution) { const match = message.name.match(/In\[(\d+)\]/); if (match) { execution.execution.executionOrder = parseInt(match[1]); } } break; case "show-output": case "show-message": case "show-text": if (execution) { const cellLabel = String(message.name || ""); const renderMathJax = typeof message.text === "string" && Boolean(cellLabel.match("^Out\\[.+\\]//TeXForm=.*")) && this.config.get("rendering.renderTexForm") === true; const outputItems: vscode.NotebookCellOutputItem[] = []; if (renderMathJax) { outputItems.push(vscode.NotebookCellOutputItem.text( tex2svg(JSON.parse(message.text as string), {display: true}), "text/html")); } if (typeof message.html === "string" && !renderMathJax) { outputItems.push(vscode.NotebookCellOutputItem.text(message.html, "x-application/wolfram-language-html")); } if (typeof message.text === "string" && this.config.get("frontEnd.storeOutputExpressions")) { outputItems.push(vscode.NotebookCellOutputItem.text(message.text, "text/plain")); } const output = new vscode.NotebookCellOutput(outputItems); output.metadata = { cellLabel, isBoxData: message.isBoxData || false }; if (execution?.hasOutput) { execution.execution.appendOutput(output); } else { execution.execution.replaceOutput(output); execution.hasOutput = true; } } break; case "evaluation-done": if (execution && !execution.hasOutput) { execution.execution.replaceOutput([]); } this.executionQueue.end(id, true); this.checkoutExecutionQueue(); break; case "request-input": case "request-input-string": let prompt = message.prompt as string; let choices: any = null; if (prompt === "? ") { prompt = ""; } else if (message.type === "request-input-string") { const match = prompt.match(/^(.*) \(((?:.+, )*)(.+)((?:, .+)*)\) \[\3\]: $/); if (match) { prompt = match[1]; choices = [ ...match[2].split(", ").slice(0, -1), match[3], ...match[4].split(", ").slice(1) ].filter(c => (c.length > 0)); } } if (choices) { const input = await vscode.window.showQuickPick(choices, { title: "The kernel requested a choice", placeHolder: prompt, ignoreFocusOut: true }); this.postMessageToKernel({ type: "reply-input-string", text: input || "" }); } else { const input = await vscode.window.showInputBox({ title: "The kernel requested an input", placeHolder: prompt, ignoreFocusOut: true }); this.postMessageToKernel({ type: (message.type === "request-input" ? "reply-input" : "reply-input-string"), text: input || "" }); } break; case "reply-export-notebook": this.statusBarExportItem.hide(); if ((message.text || "") === "") { // when there is nothing to export, maybe due to pdf export failure vscode.window.showErrorMessage("Failed to export the notebook."); break; } const defaultFormat = message.format === "pdf" ? "pdf" : "nb"; const defaultDescription = message.format === "pdf" ? "PDF" : "Wolfram Notebook"; const exportData = message.format === "pdf" ? Buffer.from(message.text, "base64") : message.text as string; const path = await vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file((message?.path || "").replace(/\.[^/.]+$/, "." + defaultFormat)), filters: { [defaultDescription]: [defaultFormat], "All Files": ["*"] } }); if (path) { this.writeFileChecked(path.fsPath, exportData); } break; case "update-symbol-usages": break; case "update-symbol-usages-progress": break; default: this.outputPanel.print("The following message has an unexpect type:"); this.outputPanel.print(JSON.stringify(message)); } } } private quitKernel() { if (this.kernel) { // clear executionQueue only when the kernel was connected this.executionQueue.clear(); if (this.kernel.pid) { this.outputPanel.print(`Killing kernel process, pid = ${this.kernel.pid}`); } this.kernel.kill("SIGKILL"); this.kernel = undefined; this.connectingtoKernel = false; } if (this.socket !== undefined) { this.outputPanel.print("Closing socket"); this.socket.close(); this.socket = undefined; } this.statusBarKernelItem.setDisconnected(); }; private showKernelLaunchFailed(kernelName: string = "") { this.outputPanel.show(); vscode.window.showErrorMessage( `Failed to connect to the kernel${kernelName ? " \"" + kernelName + "\"" : ""}.`, "Try Again", "Test in Terminal", "Edit configurations" ).then(value => { if (value === "Try Again") { this.launchKernel(kernelName || undefined); } else if (value === "Test in Terminal") { this.launchKernel(kernelName || undefined, true); } else if (value === "Edit configurations") { vscode.commands.executeCommand( "workbench.action.openSettings", "wolframLanguageNotebook.kernel.configurations" ); } }); } private launchKernelWithName(kernelName: string, kernel: any, testInTerminal: boolean = false) { this.outputPanel.clear(); let connectionTimeout = this.config.get("kernel.connectionTimeout") as number; if (!(1000 < connectionTimeout)) { connectionTimeout = 1000; // milliseconds } const kernelIsRemote = (kernel?.type === "remote"); const kernelCommand = String(kernel?.command || ""); const sshCommand = String(kernel?.sshCommand || "ssh"); const sshHost = String(kernel?.sshHost || ""); const sshCredentialType = String(kernel?.sshCredentialType); const sshCredential = String(kernel?.sshCredential || "none"); const kernelPort = this.getRandomPort(String(kernel?.ports)); this.outputPanel.print(`kernelIsRemote = ${kernelIsRemote}, kernelPort = ${kernelPort}`); const kernelInitPath = path.join(this.extensionPath, 'resources', 'init-compressed.txt'); const kernelRenderInitPath = path.join(this.extensionPath, 'resources', 'render-html.wl'); this.outputPanel.print(`kernelInitPath = ${kernelInitPath}`); this.outputPanel.print(`kernelRenderInitPath = ${kernelRenderInitPath}`); let kernelInitString = ""; let kernelRenderInitString = ""; try { kernelInitString = readFileSync(kernelInitPath).toString(); kernelRenderInitString = readFileSync(kernelRenderInitPath).toString(); } catch (error) { vscode.window.showErrorMessage("Failed to read kernel initialization files."); this.quitKernel(); return; } const kernelInitCommands = kernelIsRemote ? `"zmqPort=${kernelPort};ToExpression[Uncompress[\\"${kernelInitString}\\"]]"` : `ToExpression["zmqPort=${kernelPort};"<>Uncompress["${kernelInitString}"]]`; if (this.kernel || this.socket) { this.quitKernel(); } let launchCommand = ""; let launchArguments = [""]; if (kernelIsRemote) { launchCommand = sshCommand || "ssh"; launchArguments = [ "-tt", ...(sshCredentialType === "key" ? ["-i", sshCredential] : []), "-o", "ExitOnForwardFailure=yes", "-L", `127.0.0.1:${kernelPort}:127.0.0.1:${kernelPort}`, sshHost, kernelCommand || "wolframscript", ...(testInTerminal ? [] : ["-code", kernelInitCommands]) ]; } else { launchCommand = kernelCommand || "wolframscript"; launchArguments = [ ...(testInTerminal ? [] : ["-code", kernelInitCommands]) ]; } this.outputPanel.print(`launchCommand = ${String(launchCommand).slice(0, 200)}`); this.outputPanel.print(`launchArguments = ${String(launchArguments).slice(0, 200)}`); if (testInTerminal) { const terminal = vscode.window.createTerminal("Wolfram Language"); this.disposables.push(terminal); terminal.show(); terminal.sendText(launchCommand + " " + launchArguments.join(" ")); } else { this.connectingtoKernel = true; this.statusBarKernelItem.setConnecting(); this.kernel = child_process.spawn(launchCommand, launchArguments, { stdio: "pipe" }); let isFirstMessage = true; this.kernel.stdout.on("data", async (data: Buffer) => { const message = data.toString(); if (message.startsWith("<ERROR> ")) { // a fatal error vscode.window.showErrorMessage("The kernel has stopped due to the following error: " + message.slice(8)); return; } if (true || this.connectingtoKernel) { this.outputPanel.print("Received the following data from kernel:"); this.outputPanel.print(`${data.toString()}`); } if (isFirstMessage) { if (message.startsWith("<INITIALIZATION STARTS>") || ("<INITIALIZATION STARTS>").startsWith(message)) { isFirstMessage = false; } else { this.outputPanel.print("The first message is expected to be <INITIALIZATION STARTS>, instead of the message above."); if (message.startsWith("Mathematica ") || message.startsWith("Wolfram ")) { this.outputPanel.print(" It seems that a WolframKernel is launched, but wolframscript is required"); } this.quitKernel(); this.showKernelLaunchFailed(kernelName); return; } } const match = message.match(/\[address tcp:\/\/(127.0.0.1:[0-9]+)\]/); if (match) { this.socket = new zmq.Pair({ linger: 0 }); this.socket.connect("tcp://" + match[1]); const rand = Math.floor(Math.random() * 1e9).toString(); try { this.postMessageToKernel({ type: "test", text: rand }); let timer: any; const [received] = await Promise.race([ this.socket.receive(), new Promise(res => timer = setTimeout(() => res([new Error("timeout")]), connectionTimeout)) ]).finally(() => clearTimeout(timer)); if (received instanceof Error) { throw received; } this.outputPanel.print("Received the following test message from kernel:"); this.outputPanel.print(`${received.toString()}`); const message = JSON.parse(received.toString()); if (message["type"] !== "test" || message["text"] !== rand) { throw new Error("test"); } this.evaluateFrontEnd(kernelRenderInitString, false); this.postMessageToKernel({type: "set-config", config: this.config.getKernelRelatedConfigs()}); this.connectingtoKernel = false; this.statusBarKernelItem.setConnected(message["version"] || "", kernelIsRemote); try { this.handleMessageFromKernel(); } catch {} this.checkoutExecutionQueue(); } catch (error) { if (error instanceof Error) { if (error.message === "timeout") { this.outputPanel.print("The kernel took too long to respond through the ZeroMQ link."); } else if (error.message === "test") { this.outputPanel.print("The kernel responded with a wrong test message, as above"); this.outputPanel.print(" The expected message should contain: " + JSON.stringify({type: "test", text: rand})); } } this.quitKernel(); this.showKernelLaunchFailed(kernelName); } } }); this.kernel.stderr.on("data", (data: Buffer) => { this.outputPanel.print("Received the following data from kernel (stderr):"); this.outputPanel.print(`${data.toString()}`); }); this.kernel.on("exit", (code: number, signal: string) => { this.quitKernel(); this.outputPanel.print(`Process exited with code ${code} and signal ${signal}.`); if (this.restartAfterExitKernel) { this.restartAfterExitKernel = false; this.launchKernel(); } else { vscode.window.showWarningMessage(`Kernel "${kernelName}" has been disconnected.`); } }); this.kernel.on("error", (err: Error) => { this.outputPanel.print(`Error occured in spwaning the kernel process: \n${err}`); this.quitKernel(); this.showKernelLaunchFailed(kernelName); }); } }; private launchKernel(kernelName: string | undefined = undefined, testInTerminal: boolean = false) { if (this.kernelConnected()) { return; } this.quitKernel(); const kernels = this.config.get("kernel.configurations") as any; const numKernels = Object.keys(kernels).length; if (kernelName === undefined) { // let the user choose the kernel const withUseWolframscript = (numKernels === 0); let leadingPicks: any[] = []; if (withUseWolframscript) { leadingPicks = [{ label: "$(debug-start) Use wolframscript", detail: "Add wolframscript to kernel configurations and connect to it" }]; } else { leadingPicks = Object.keys(kernels).map(name => { const host = kernels[name]?.type === "remote" ? String(kernels[name]?.sshHost || "remote") : "local"; return { label: `$(debug-start) ${name}`, detail: `${host}> ${String(kernels[name]?.command)}` }; }); } vscode.window.showQuickPick([ ...leadingPicks, { label: "$(new-file) Add a new kernel", detail: "" }, { label: "$(notebook-edit) Edit kernel configurations in settings", detail: "" } ]).then(value => { if (value) { if (withUseWolframscript && value?.label === "$(debug-start) Use wolframscript") { const config = vscode.workspace.getConfiguration("wolframLanguageNotebook"); const newKernel = { wolframscript: { type: "local", command: "wolframscript", ports: "49152-65535" } }; config.update("kernel.configurations", { ...config.get("kernel.configurations"), ...newKernel }, vscode.ConfigurationTarget.Global ).then(() => { // config may not be available yet; add a short delay setTimeout(() => { this.launchKernel("wolframscript", testInTerminal); }, 200); }); } else if (value.label.startsWith("$(debug-start)")) { this.launchKernel(value.label.substring(15), testInTerminal); } else if (value.label === "$(new-file) Add a new kernel") { this.addNewKernel(); } else if (value.label === "$(notebook-edit) Edit kernel configurations in settings") { vscode.commands.executeCommand( "workbench.action.openSettings", "wolframLanguageNotebook.kernel.configurations" ); } } }); } else { // try to use the specified kernel const kernel = kernels[kernelName]; if (typeof kernel === "object" && "command" in kernel) { this.launchKernelWithName(kernelName, kernel, testInTerminal); } else { vscode.window.showErrorMessage( `Failed to find the kernel ${kernelName} in configurations.\nA kernel must contain a \"command\" field.`, "Edit configurations", "Dismiss" ).then(value => { if (value === "Edit configurations") { vscode.commands.executeCommand( "workbench.action.openSettings", "wolframLanguageNotebook.kernel.configurations" ); } }); } } }; private kernelConnected() { return Boolean(this.kernel) && Boolean(this.socket); } private async addNewKernel() { const previousKernels = this.config.get("kernel.configurations") as any; const name = await vscode.window.showInputBox({ prompt: "Enter the name of a new kernel, or an existing kernel to edit it" }); if (!name) { return; } const exists = name in previousKernels && typeof previousKernels[name] === "object"; const previously = exists ? previousKernels[name] : {}; let type = await vscode.window.showQuickPick(["On this machine", "On a remote machine"], { placeHolder: `Where will this kernel be launched? ${exists ? `(was ${previously?.type === "remote" ? "remote" : "local"})` : "" }` }); if (!type) { return; } else { type = (type === "On this machine") ? "local" : "remote"; } let sshHost: any; let sshCredentialType: any; let sshCredential: any; if (type === "remote") { sshHost = await vscode.window.showInputBox({ value: exists ? previously?.sshHost : undefined, placeHolder: "user@hostname", prompt: "Enter the username and the address of the remote machine." }); if (!sshHost) { return; } sshCredentialType = await vscode.window.showQuickPick(["Private key file", "Skip"], { placeHolder: `Select SSH authentication method ${exists ? `(was ${previously?.sshCredentialType === "key" ? "a private key file" : "skipped"})` : "" }` }); if (!sshCredentialType) { return; } else { sshCredentialType = (sshCredentialType === "Private key file") ? "key" : "none"; } sshCredential = ""; if (sshCredentialType === "key") { const keyFile = await vscode.window.showOpenDialog({ defaultUri: previously?.sshCredential ? vscode.Uri.file(previously.sshCredential) : undefined }); if (keyFile === undefined || keyFile.length !== 1) { sshCredentialType = "none"; } else { sshCredential = keyFile[0].fsPath; } } } let command = await vscode.window.showInputBox({ value: exists ? previously?.command : undefined, placeHolder: "Default: wolframscript", prompt: "Enter the command to launch the kernel." }); if (command === undefined) { return; } else if (command === "") { command = "wolframscript"; } let ports = await vscode.window.showInputBox({ value: exists ? previously?.ports : undefined, placeHolder: "Default: 49152-65535", prompt: type === "remote" ? "Enter port ranges for communication to the kernel on this machine and the remote machine" : "Enter port ranges for communication to the kernel on this machine" }); if (ports === undefined) { return; } else if (ports === "") { ports = "49152-65535"; } const newKernel: any = (type === "remote") ? { [name]: { type, command, ports, sshCommand: "ssh", sshHost, sshCredentialType, sshCredential } } : { [name]: { type, command, ports } }; const prevKernelConfigJSON = JSON.stringify(this.config.get("kernel.configurations")); const newKernelConfig = {...JSON.parse(prevKernelConfigJSON), ...newKernel}; const update = await this.config.update("kernel.configurations",newKernelConfig, vscode.ConfigurationTarget.Global); vscode.window.showInformationMessage("A new kernel has been added.", "Start this kernel", "Dismiss").then(value => { if (value === "Start this kernel") { this.launchKernel(name); } }); }; manageKernel() { if (this.kernelConnected()) { vscode.window.showQuickPick([ { label: "$(debug-stop) Quit", detail: "Quit the current kernel." }, { label: "$(debug-restart) Restart", detail: "Quit the current kernel and start a new one." }, { label: "$(notebook-edit) Edit kernel configurations in settings", detail: "" } ]).then(value => { if (value?.label === "$(debug-stop) Quit") { this.quitKernel(); } else if (value?.label === "$(debug-restart) Restart") { this.quitKernel(); this.restartAfterExitKernel = true; } else if (value?.label === "$(notebook-edit) Edit kernel configurations in settings") { vscode.commands.executeCommand( "workbench.action.openSettings", "wolframLanguageNotebook.kernel.configurations" ); } }); } else { this.launchKernel(); } }; private execute( cells: vscode.NotebookCell[], _notebook: vscode.NotebookDocument, _controller: vscode.NotebookController ): void { for (let cell of cells) { const execution = this.controller.createNotebookCellExecution(cell); const id = this.executionQueue.push(execution); const self = this; execution.token.onCancellationRequested(() => { self.abortEvaluation(id); }); } this.checkoutExecutionQueue(); } private abortEvaluation(id: string) { if (!this.executionQueue.empty()) { const execution = this.executionQueue.find(id); if (execution) { if (execution?.started) { this.postMessageToKernel({ type: "abort-evaluations" }); } // remove it from the execution queue this.executionQueue.end(id, false); } } this.checkoutExecutionQueue(); } private checkoutExecutionQueue() { const execution = this.executionQueue.getNextPendingExecution(); if (execution) { if (this.kernelConnected()) { // the kernel is ready const text = execution.execution.cell.document.getText().replace(/\r\n/g, "\n"); if (text) { this.postMessageToKernel({ type: "evaluate-cell", uuid: execution.id, text: text }); this.executionQueue.start(execution.id); } else { this.executionQueue.start(execution.id); this.executionQueue.end(execution.id, false); } } else if (this.connectingtoKernel) { // trying to connect to kernel, then do nothing } else { this.launchKernel(); } } } async exportNotebook(uri: vscode.Uri) { let notebook: vscode.NotebookDocument | undefined; this.selectedNotebooks.forEach(current => { if (current.uri.toString() === uri.toString()) { notebook = current; } }); if (!notebook) { return; } const choice = await vscode.window.showQuickPick([ { label: "Wolfram Language Package/Script", detail: "Export code cells only" }, { label: "Wolfram Notebook", detail: "Export all cells" }, { label: "PDF", detail: "Export all cells" } ], { placeHolder: "Export As..." }); if (!(choice?.label)) { return; } if ((choice.label === "Wolfram Notebook" || choice.label === "PDF") && !this.kernelConnected()) { const start = await vscode.window.showErrorMessage( "Exporting as Wolfram Notebook/PDF requires a connected Wolfram Kernel", "Connect", "Dismiss" ); if (start === "Connect") { this.launchKernel(); } return; } const cellData: { type: string; // Title, Section, Text, Input, ... label: string; // In[...]:= , Out[...]= text: string | any[]; isBoxData?: boolean; }[] = []; const decoder = new util.TextDecoder(); notebook.getCells().forEach(cell => { if (cell.kind === vscode.NotebookCellKind.Markup) { cellData.push(...deserializeMarkup(cell.document.getText().replace(/\r\n/g, "\n"))); } else if (cell.kind === vscode.NotebookCellKind.Code) { const executionOrder = cell.executionSummary?.executionOrder; cellData.push({ type: "Input", label: executionOrder ? `In[${executionOrder}]:=` : "", text: cell.document.getText().replace(/\r\n/g, "\n") }); cell.outputs.forEach(output => { const item = output.items.find(item => item.mime === "text/plain"); cellData.push({ type: "Output", label: (output?.metadata?.cellLabel || "").toString(), text: decoder.decode(item?.data || new Uint8Array([])), isBoxData: output?.metadata?.isBoxData || false }); }); } }); if (choice.label === "Wolfram Language Package/Script") { const serializedCells = cellData.filter(data => data.type === "Input").map(data => data.text + "\n"); let documentText = "(* ::Package:: *)\n\n" + serializedCells.join("\n\n"); const path = await vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file((notebook.uri.fsPath || "").replace(/\.[^/.]+$/, ".wl")), filters: { "Wolfram Language Package": ["wl"], "Wolfram Language Script": ["wls"], "All Files": ["*"] } }); if (path) { if (path.fsPath.match(/\.wls$/)) { documentText = "#!/usr/bin/env wolframscript\n" + documentText; } this.writeFileChecked(path.fsPath, documentText); } } else if (choice.label === "Wolfram Notebook" || choice.label === "PDF") { this.statusBarExportItem.show(); this.postMessageToKernel({ type: "request-export-notebook", format: choice.label === "Wolfram Notebook" ? "nb" : "pdf", path: notebook.uri.fsPath, cells: cellData }); } } evaluateFrontEnd(text: string, asynchronous: boolean = false) { if (this.kernelConnected()) { this.postMessageToKernel({ type: "evaluate-front-end", async: asynchronous, text: text }); } } }
the_stack
module android.widget { import AbsSeekBar = android.widget.AbsSeekBar; import ProgressBar = android.widget.ProgressBar; import SeekBar = android.widget.SeekBar; import AttrBinder = androidui.attr.AttrBinder; /** * A RatingBar is an extension of SeekBar and ProgressBar that shows a rating in * stars. The user can touch/drag or use arrow keys to set the rating when using * the default size RatingBar. The smaller RatingBar style ( * {@link android.R.attr#ratingBarStyleSmall}) and the larger indicator-only * style ({@link android.R.attr#ratingBarStyleIndicator}) do not support user * interaction and should only be used as indicators. * <p> * When using a RatingBar that supports user interaction, placing widgets to the * left or right of the RatingBar is discouraged. * <p> * The number of stars set (via {@link #setNumStars(int)} or in an XML layout) * will be shown when the layout width is set to wrap content (if another layout * width is set, the results may be unpredictable). * <p> * The secondary progress should not be modified by the client as it is used * internally as the background for a fractionally filled star. * * @attr ref android.R.styleable#RatingBar_numStars * @attr ref android.R.styleable#RatingBar_rating * @attr ref android.R.styleable#RatingBar_stepSize * @attr ref android.R.styleable#RatingBar_isIndicator */ export class RatingBar extends AbsSeekBar { private mNumStars:number = 5; private mProgressOnStartTracking:number = 0; private mOnRatingBarChangeListener:RatingBar.OnRatingBarChangeListener; constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle=android.R.attr.ratingBarStyle) { super(context, bindElement, defStyle); const a = context.obtainStyledAttributes(bindElement, defStyle); const numStars = a.getInt('numStars', this.mNumStars); this.setIsIndicator(a.getBoolean('isIndicator', !this.mIsUserSeekable)); const rating = a.getFloat('rating', -1); const stepSize = a.getFloat('stepSize', -1); a.recycle(); if (numStars > 0 && numStars != this.mNumStars) { this.setNumStars(numStars); } if (stepSize >= 0) { this.setStepSize(stepSize); } else { this.setStepSize(0.5); } if (rating >= 0) { this.setRating(rating); } // A touch inside a star fill up to that fractional area (slightly more // than 1 so boundaries round up). this.mTouchProgressOffset = 1.1; } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('numStars', { setter(v:RatingBar, value:any, a:AttrBinder) { v.setNumStars(a.parseInt(value, v.mNumStars)); }, getter(v:RatingBar) { return v.mNumStars; } }).set('isIndicator', { setter(v:RatingBar, value:any, a:AttrBinder) { v.setIsIndicator(a.parseBoolean(value, !v.mIsUserSeekable)); }, getter(v:RatingBar) { return v.isIndicator(); } }).set('stepSize', { setter(v:RatingBar, value:any, a:AttrBinder) { v.setStepSize(a.parseFloat(value, 0.5)); }, getter(v:RatingBar) { return v.getStepSize(); } }).set('rating', { setter(v:RatingBar, value:any, a:AttrBinder) { v.setRating(a.parseFloat(value, v.getRating())); }, getter(v:RatingBar) { return v.getRating(); } }); } //constructor( context:Context, attrs:AttributeSet, defStyle:number) { // super(context, attrs, defStyle); // let a:TypedArray = context.obtainStyledAttributes(attrs, R.styleable.RatingBar, defStyle, 0); // const numStars:number = a.getInt(R.styleable.RatingBar_numStars, this.mNumStars); // this.setIsIndicator(a.getBoolean(R.styleable.RatingBar_isIndicator, !this.mIsUserSeekable)); // const rating:number = a.getFloat(R.styleable.RatingBar_rating, -1); // const stepSize:number = a.getFloat(R.styleable.RatingBar_stepSize, -1); // a.recycle(); // if (numStars > 0 && numStars != this.mNumStars) { // this.setNumStars(numStars); // } // if (stepSize >= 0) { // this.setStepSize(stepSize); // } else { // this.setStepSize(0.5); // } // if (rating >= 0) { // this.setRating(rating); // } // // A touch inside a star fill up to that fractional area (slightly more // // than 1 so boundaries round up). // this.mTouchProgressOffset = 1.1; //} /** * Sets the listener to be called when the rating changes. * * @param listener The listener. */ setOnRatingBarChangeListener(listener:RatingBar.OnRatingBarChangeListener):void { this.mOnRatingBarChangeListener = listener; } /** * @return The listener (may be null) that is listening for rating change * events. */ getOnRatingBarChangeListener():RatingBar.OnRatingBarChangeListener { return this.mOnRatingBarChangeListener; } /** * Whether this rating bar should only be an indicator (thus non-changeable * by the user). * * @param isIndicator Whether it should be an indicator. * * @attr ref android.R.styleable#RatingBar_isIndicator */ setIsIndicator(isIndicator:boolean):void { this.mIsUserSeekable = !isIndicator; this.setFocusable(!isIndicator); } /** * @return Whether this rating bar is only an indicator. * * @attr ref android.R.styleable#RatingBar_isIndicator */ isIndicator():boolean { return !this.mIsUserSeekable; } /** * Sets the number of stars to show. In order for these to be shown * properly, it is recommended the layout width of this widget be wrap * content. * * @param numStars The number of stars. */ setNumStars(numStars:number):void { if (numStars <= 0) { return; } let step = this.getStepSize(); this.mNumStars = numStars; this.setStepSize(step); // This causes the width to change, so re-layout this.requestLayout(); } /** * Returns the number of stars shown. * @return The number of stars shown. */ getNumStars():number { return this.mNumStars; } /** * Sets the rating (the number of stars filled). * * @param rating The rating to set. */ setRating(rating:number):void { this.setProgress(Math.round(rating * this.getProgressPerStar())); } /** * Gets the current rating (number of stars filled). * * @return The current rating. */ getRating():number { return this.getProgress() / this.getProgressPerStar(); } /** * Sets the step size (granularity) of this rating bar. * * @param stepSize The step size of this rating bar. For example, if * half-star granularity is wanted, this would be 0.5. */ setStepSize(stepSize:number):void { if (Number.isNaN(stepSize) || !Number.isFinite(stepSize) || stepSize <= 0) { return; } const newMax:number = this.mNumStars / stepSize; let newProgress:number = Math.floor((newMax / this.getMax() * this.getProgress())); if(Number.isNaN(newProgress)) newProgress = 0; this.setMax(Math.floor(newMax)); this.setProgress(newProgress); } /** * Gets the step size of this rating bar. * * @return The step size. */ getStepSize():number { return <number> this.getNumStars() / this.getMax(); } /** * @return The amount of progress that fits into a star */ private getProgressPerStar():number { if (this.mNumStars > 0) { return 1 * this.getMax() / this.mNumStars; } else { return 1; } } //getDrawableShape():Shape { // // TODO: Once ProgressBar's TODOs are fixed, this won't be needed // return new RectShape(); //} onProgressRefresh(scale:number, fromUser:boolean):void { super.onProgressRefresh(scale, fromUser); // Keep secondary progress in sync with primary this.updateSecondaryProgress(this.getProgress()); if (!fromUser) { // Callback for non-user rating changes this.dispatchRatingChange(false); } } /** * The secondary progress is used to differentiate the background of a * partially filled star. This method keeps the secondary progress in sync * with the progress. * * @param progress The primary progress level. */ private updateSecondaryProgress(progress:number):void { const ratio:number = this.getProgressPerStar(); if (ratio > 0) { const progressInStars:number = progress / ratio; const secondaryProgress:number = Math.floor((Math.ceil(progressInStars) * ratio)); this.setSecondaryProgress(secondaryProgress); } } protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (this.mSampleTile != null) { // TODO: Once ProgressBar's TODOs are gone, this can be done more // cleanly than mSampleTile const width:number = this.mSampleTile.getIntrinsicWidth() * this.mNumStars; this.setMeasuredDimension(RatingBar.resolveSizeAndState(width, widthMeasureSpec, 0), this.getMeasuredHeight()); } } onStartTrackingTouch():void { this.mProgressOnStartTracking = this.getProgress(); super.onStartTrackingTouch(); } onStopTrackingTouch():void { super.onStopTrackingTouch(); if (this.getProgress() != this.mProgressOnStartTracking) { this.dispatchRatingChange(true); } } onKeyChange():void { super.onKeyChange(); this.dispatchRatingChange(true); } dispatchRatingChange(fromUser:boolean):void { if (this.mOnRatingBarChangeListener != null) { this.mOnRatingBarChangeListener.onRatingChanged(this, this.getRating(), fromUser); } } setMax(max:number):void { // Disallow max progress = 0 if (max <= 0) { return; } super.setMax(max); } } export module RatingBar{ /** * A callback that notifies clients when the rating has been changed. This * includes changes that were initiated by the user through a touch gesture * or arrow key/trackball as well as changes that were initiated * programmatically. */ export interface OnRatingBarChangeListener { /** * Notification that the rating has changed. Clients can use the * fromUser parameter to distinguish user-initiated changes from those * that occurred programmatically. This will not be called continuously * while the user is dragging, only when the user finalizes a rating by * lifting the touch. * * @param ratingBar The RatingBar whose rating has changed. * @param rating The current rating. This will be in the range * 0..numStars. * @param fromUser True if the rating change was initiated by a user's * touch gesture or arrow key/horizontal trackbell movement. */ onRatingChanged(ratingBar:RatingBar, rating:number, fromUser:boolean):void ; } } }
the_stack
'use strict'; import _ = require('lodash'); import AsyncOptions = require('./AsyncOptions'); import BluePromise = require('bluebird'); import chalk = require('chalk'); import ClassesMap = require('../lib/classes-map'); import CodeWriter = require('../lib/code-writer'); import debug = require('debug'); import findJavaHome = require('find-java-home'); import fs = require('fs'); import glob = require('glob'); import Immutable = require('immutable'); import java = require('java'); import mkdirp = require('mkdirp'); import path = require('path'); import program = require('commander'); import readJson = require('read-package-json'); import TsJavaOptions = require('../lib/TsJavaOptions'); import ClassDefinition = ClassesMap.ClassDefinition; import ClassDefinitionMap = ClassesMap.ClassDefinitionMap; // Typescript & bluebird.promisify needs some assistance with functions such as fs.writefile. // Node.d.ts declares writeFile as follows, with the exception that the callback argument is declared optional. interface WriteFile { (filename: string, data: any, callback: (err: NodeJS.ErrnoException) => void): void; } BluePromise.longStackTraces(); var writeFilePromise = BluePromise.promisify(<WriteFile> fs.writeFile); var readFilePromise = BluePromise.promisify(fs.readFile); var mkdirpPromise = BluePromise.promisify(mkdirp); var readJsonPromise = BluePromise.promisify(readJson); var globPromise = BluePromise.promisify(glob); var findJavaHomePromise = BluePromise.promisify(findJavaHome); // ts-java must use asyncOptions that are 'compatible' with the java/java.d.ts in Definitely typed, // which uses the following settings. // Options are incompatible if a different value is defined for any of the three properties, // but any of them can be left undefined. var expectedAsyncOptions: AsyncOptions = { syncSuffix: '', asyncSuffix: 'A', promiseSuffix: 'P' }; function areCompatibleAsyncOptions(opts: AsyncOptions): boolean { return _.isEqual(expectedAsyncOptions, _.defaults({}, opts, expectedAsyncOptions)); } interface Func { (result: any): void; } var dlog = debug('ts-java:main'); var bold = chalk.bold; var error = bold.red; var warn = bold.yellow; class Main { private packagePath: string; private options: TsJavaOptions; private classesMap: ClassesMap; constructor(param: TsJavaOptions | string) { this.packagePath = undefined; this.options = undefined; if (typeof param === 'string') { this.packagePath = param; } else { this.options = param; } } run(): BluePromise<ClassesMap> { return this.load() .then(() => BluePromise.join(this.writeJsons(), this.writeInterpolatedFiles(), this.writeTsJavaModule())) .then(() => dlog('run() completed.')) .then(() => this.outputSummaryDiagnostics()) .then(() => this.classesMap); } load(): BluePromise<ClassesMap> { var start: BluePromise<void> = this.options ? this.initFromOptions() : this.initFromPackagePath(); return start .then(() => this.initJava()) .then(() => { this.classesMap = new ClassesMap(this.options); return this.classesMap.initialize(); }) .then(() => this.classesMap); } getOptions(): TsJavaOptions { return this.options; } private initFromPackagePath(): BluePromise<void> { return readJsonPromise(this.packagePath, console.error, false) .then((packageContents: any) => { if (!('tsjava' in packageContents)) { return BluePromise.reject(new Error('package.json does not contain a tsjava property')); } else { this.options = packageContents.tsjava; return this.initFromOptions(); } }); } private initFromOptions(): BluePromise<void> { if (this.options.granularity !== 'class') { this.options.granularity = 'package'; } if (!this.options.promisesPath) { // TODO: Provide more control over promises this.options.promisesPath = '../bluebird/bluebird.d.ts'; } if (!this.options.javaTypingsPath) { this.options.javaTypingsPath = 'typings/java/java.d.ts'; } if (!this.options.asyncOptions) { this.options.asyncOptions = expectedAsyncOptions; } else if (!areCompatibleAsyncOptions(this.options.asyncOptions)) { console.warn(warn('tsjava.asyncOptions are not compatible with the asyncOptions used in the standard typings/java/java.d.ts')); } if (!this.options.packages && this.options.whiteList) { console.warn(warn('tsjava.whiteList in package.json is deprecated. Please use tsjava.packages instead.')); this.options.packages = this.options.whiteList; this.options.whiteList = undefined; } if (!this.options.classes && this.options.seedClasses) { console.warn(warn('tsjava.seedClasses in package.json is deprecated. Please use tsjava.classes instead.')); this.options.classes = this.options.seedClasses; this.options.seedClasses = undefined; } var deprecated: string = _.find(this.options.packages, (s: string) => { return s.slice(-2) !== '.*' && s.slice(-3) !== '.**'; }); if (deprecated) { console.warn(warn('tsjava.packages should have expressions ending in .* or .**')); dlog('Deprecated package expression:', deprecated); } return BluePromise.resolve(); } private writeInterpolatedFiles() : BluePromise<void> { var classesMap: ClassesMap = this.classesMap; return this.options.granularity === 'class' ? this.writeClassFiles(classesMap) : this.writePackageFiles(classesMap); } private writeJsons(): BluePromise<void> { if (!program.opts().json) { return; } var classes: ClassDefinitionMap = this.classesMap.getClasses(); dlog('writeJsons() entered'); return mkdirpPromise('o/json') .then(() => { var parray: BluePromise<void>[] = _.map(_.keys(classes), (className: string) => { var classMap = classes[className]; var p: BluePromise<any> = writeFilePromise('o/json/' + classMap.shortName + '.json', JSON.stringify(classMap, null, ' ')); return p; }); return parray; }) .then((promises: BluePromise<void>[]) => BluePromise.all(promises)) .then(() => dlog('writeJsons() completed.')); } private writeClassFiles(classesMap: ClassesMap): BluePromise<void> { dlog('writeClassFiles() entered'); return mkdirpPromise('o/lib') .then(() => { var templatesDirPath = path.resolve(__dirname, '..', 'ts-templates'); var tsWriter = new CodeWriter(classesMap, templatesDirPath); var classes: ClassDefinitionMap = classesMap.getClasses(); return _.map(_.keys(classes), (name: string) => tsWriter.writeLibraryClassFile(name, this.options.granularity)); }) .then((promises: Promise<any>[]) => BluePromise.all(promises)) .then(() => dlog('writeClassFiles() completed.')); } private writePackageFiles(classesMap: ClassesMap): BluePromise<void> { dlog('writePackageFiles() entered'); if (!this.options.outputPath) { dlog('No java.d.ts outputPath specified, skipping generation.'); return BluePromise.resolve(); } else { var templatesDirPath = path.resolve(__dirname, '..', 'ts-templates'); var tsWriter = new CodeWriter(classesMap, templatesDirPath); return mkdirpPromise(path.dirname(this.options.outputPath)) .then(() => tsWriter.writePackageFile(this.options)) .then(() => dlog('writePackageFiles() completed')); } } private writeTsJavaModule(): BluePromise<void> { dlog('writeTsJavaModule() entered'); if (this.options.tsJavaModulePath === undefined) { dlog('No tsJavaModulePath specified, skipping generation.'); return BluePromise.resolve(); } else { var templatesDirPath = path.resolve(__dirname, '..', 'ts-templates'); var tsWriter = new CodeWriter(this.classesMap, templatesDirPath); return mkdirpPromise(path.dirname(this.options.tsJavaModulePath)) .then(() => tsWriter.writeTsJavaModule(this.options)) .then(() => dlog('writeTsJavaModule() completed')); } } private checkForUnrecognizedClasses(): void { var allClasses: Immutable.Set<string> = this.classesMap.getAllClasses(); var configuredClasses = Immutable.Set<string>(this.classesMap.getOptions().classes); var unrecognizedClasses = configuredClasses.subtract(allClasses); unrecognizedClasses.forEach((className: string) => { console.log(warn('tsjava.classes contained classes not in classpath:'), error(className)); }); } private checkForUselessPackageExpresions(): void { var packages: Immutable.Set<string> = Immutable.Set<string>(this.classesMap.getOptions().packages); var classes: Immutable.Set<string> = this.classesMap.getAllClasses(); packages.forEach((expr: string) => { var pattern = this.classesMap.packageExpressionToRegExp(expr); var match: boolean = classes.some((className: string) => pattern.test(className)); if (!match) { console.log(warn('tsjava.packages contained package expression that didn\'t match any classes in classpath:'), error(expr)); } }); } private outputSummaryDiagnostics(): BluePromise<void> { if (program.opts().quiet) { return; } var classesMap: ClassDefinitionMap = this.classesMap.getClasses(); var classList = _.keys(classesMap).sort(); if (program.opts().details) { console.log(bold('Generated classes:')); classList.forEach((clazz: string) => console.log(' ', clazz)); } else { // TODO: remove support for generating java.d.ts files. if (this.options.outputPath) { console.log('Generated %s with %d classes.', this.options.outputPath, classList.length); } // TODO: always generate tsJavaModule.ts files, by using a default when value not specified. if (this.options.tsJavaModulePath) { console.log('Generated %s with %d classes.', this.options.tsJavaModulePath, classList.length); } } if (!this.classesMap.unhandledTypes.isEmpty()) { if (program.opts().details) { console.log(bold('Classes that were referenced, but excluded by the current configuration:')); this.classesMap.unhandledTypes.sort().forEach((clazz: string) => console.log(' ', clazz)); } else { console.log('Excluded %d classes referenced as method parameters.', this.classesMap.unhandledTypes.size); } } if (!this.classesMap.unhandledInterfaces.isEmpty()) { if (program.opts().details) { console.log(warn('Classes that were referenced as *interfaces*, but excluded by the current configuration:')); this.classesMap.unhandledInterfaces.sort().forEach((clazz: string) => console.log(' ', clazz)); } else { console.log(warn('Excluded %d classes referenced as *interfaces*.'), this.classesMap.unhandledInterfaces.size); } } if (!this.classesMap.unhandledSuperClasses.isEmpty()) { if (program.opts().details) { console.log(warn('Classes that were referenced as *superclasses*, but excluded by the current configuration:')); this.classesMap.unhandledSuperClasses.sort().forEach((clazz: string) => console.log(' ', clazz)); } else { console.log(warn('Excluded %d classes referenced as *superclasses*.'), this.classesMap.unhandledSuperClasses.size); } } this.checkForUnrecognizedClasses(); this.checkForUselessPackageExpresions(); return; } private initJava(): BluePromise<void> { var classpath: Array<string> = []; return BluePromise.all(_.map(this.options.classpath, (globExpr: string) => globPromise(globExpr))) .then((pathsArray: Array<Array<string>>) => _.flatten(pathsArray)) .then((paths: Array<string>) => { _.forEach(paths, (path: string) => { dlog('Adding to classpath:', path); java.classpath.push(path); classpath.push(path); }); }) .then(() => findJavaHomePromise()) .then((javaHome: string) => { // Add the Java runtime library to the class path so that ts-java is aware of java.lang and java.util classes. var rtJarPath = path.join(javaHome, 'jre', 'lib', 'rt.jar'); dlog('Adding rt.jar to classpath:', rtJarPath); classpath.push(rtJarPath); }) .then(() => { // The classpath in options is an array of glob expressions. // It is convenient to replace it here with the equivalent expanded array jar file paths. this.options.classpath = classpath; }); } } export = Main;
the_stack
import {IAugmentedJQuery, IFilterService} from 'angular' import moment, {MomentInput} from 'moment' export type TimeFramesDisplayMode = 'visible' | 'cropped' | 'hidden' export interface TimeFrameOptions { start?: moment.Moment end?: moment.Moment working?: boolean magnet?: boolean default?: boolean color?: string classes?: string[] internal?: boolean } /** * TimeFrame represents time frame in any day. parameters are given using options object. * * @param {moment|string} start start of timeFrame. If a string is given, it will be parsed as a moment. * @param {moment|string} end end of timeFrame. If a string is given, it will be parsed as a moment. * @param {boolean} working is this timeFrame flagged as working. * @param {boolean} magnet is this timeFrame will magnet. * @param {boolean} default is this timeFrame will be used as default. * @param {color} css color attached to this timeFrame. * @param {string} classes css classes attached to this timeFrame. * * @constructor */ export class TimeFrame implements TimeFrameOptions { start?: moment.Moment end?: moment.Moment working?: boolean magnet?: boolean default?: boolean color?: string classes?: string[] internal?: boolean left: number width: number hidden: boolean originalSize: { left: number; width: number } cropped: boolean $element: IAugmentedJQuery constructor (options: TimeFrameOptions) { if (options === undefined) { options = {} } this.start = options.start this.end = options.end this.working = options.working this.magnet = options.magnet !== undefined ? options.magnet : true this.default = options.default this.color = options.color this.classes = options.classes this.internal = options.internal } updateView () { if (this.$element) { let cssStyles = {} if (this.left !== undefined) { cssStyles['left'] = this.left + 'px' } else { cssStyles['left'] = '' } if (this.width !== undefined) { cssStyles['width'] = this.width + 'px' } else { cssStyles['width'] = '' } if (this.color !== undefined) { cssStyles['background-color'] = this.color } else { cssStyles['background-color'] = '' } this.$element.css(cssStyles) let classes = ['gantt-timeframe' + (this.working ? '' : '-non') + '-working'] if (this.classes) { classes = classes.concat(this.classes) } // tslint:disable:one-variable-per-declaration for (let i = 0, l = classes.length; i < l; i++) { this.$element.toggleClass(classes[i], true) } } } getDuration () { if (this.end !== undefined && this.start !== undefined) { return this.end.diff(this.start, 'milliseconds') } } clone () { return new TimeFrame(this) } } export interface TimeFrameMappingFunction {(date: moment.Moment): string[]} /** * TimeFrameMapping defines how timeFrames will be placed for each days. parameters are given using options object. * * @param {function} func a function with date parameter, that will be evaluated for each distinct day of the gantt. * this function must return an array of timeFrame names to apply. * @constructor */ export class TimeFrameMapping { private func: TimeFrameMappingFunction constructor (func: TimeFrameMappingFunction) { this.func = func } getTimeFrames (date: moment.Moment): string[] { let ret: string[] = this.func(date) if (!(ret instanceof Array)) { ret = [ret] } return ret } clone () { return new TimeFrameMapping(this.func) } } interface DateFrameOptions { evaluator: { (date: moment.Moment): boolean } date?: MomentInput start?: moment.Moment end?: moment.Moment default?: boolean targets: any } /** * A DateFrame is date range that will use a specific TimeFrameMapping, configured using a function (evaluator), * a date (date) or a date range (start, end). parameters are given using options object. * * @param {function} evaluator a function with date parameter, that will be evaluated for each distinct day of the gantt. * this function must return a boolean representing matching of this dateFrame or not. * @param {moment} date date of dateFrame. * @param {moment} start start of date frame. * @param {moment} end end of date frame. * @param {array} targets array of TimeFrameMappings/TimeFrames names to use for this date frame. * @param {boolean} default is this dateFrame will be used as default. * @constructor */ export class DateFrame { evaluator: { (date: moment.Moment): boolean } start: moment.Moment end: moment.Moment default: boolean targets: string[] constructor (options: DateFrameOptions) { this.evaluator = options.evaluator if (options.date) { this.start = moment(options.date).startOf('day') this.end = moment(options.date).endOf('day') } else { this.start = options.start this.end = options.end } if (options.targets instanceof Array) { this.targets = options.targets } else { this.targets = [options.targets] } this.default = options.default } dateMatch (date: moment.Moment) { if (this.evaluator) { return this.evaluator(date) } else if (this.start && this.end) { return date >= this.start && date <= this.end } else { return false } } clone () { return new DateFrame(this) } } /** * Register TimeFrame, TimeFrameMapping and DateMapping objects into Calendar object, * and use Calendar#getTimeFrames(date) function to retrieve effective timeFrames for a specific day. * * @constructor */ export class GanttCalendar { static $filter: IFilterService timeFrames: {[name: string]: TimeFrame} = {} timeFrameMappings: {[name: string]: TimeFrameMapping} = {} dateFrames: {[name: string]: DateFrame} = {} /** * Remove all objects. */ clear () { this.timeFrames = {} this.timeFrameMappings = {} this.dateFrames = {} } /** * Register TimeFrame objects. * * @param {object} timeFrames with names of timeFrames for keys and TimeFrame objects for values. */ registerTimeFrames (timeFrames: {[name: string]: TimeFrameOptions}) { for (let name in timeFrames) { let timeFrame = timeFrames[name] this.timeFrames[name] = new TimeFrame(timeFrame) } } /** * Removes TimeFrame objects. * * @param {array} timeFrames names of timeFrames to remove. */ removeTimeFrames (timeFrames: string[]) { for (let name in timeFrames) { delete this.timeFrames[name] } } /** * Remove all TimeFrame objects. */ clearTimeFrames () { this.timeFrames = {} } /** * Register TimeFrameMapping objects. * * @param {object} mappings object with names of timeFrames mappings for keys and TimeFrameMapping objects for values. */ registerTimeFrameMappings (mappings: {(date: moment.Moment): TimeFrameMappingFunction}) { for (let name in mappings) { let timeFrameMapping = mappings[name] this.timeFrameMappings[name] = new TimeFrameMapping(timeFrameMapping) } } /** * Removes TimeFrameMapping objects. * * @param {array} mappings names of timeFrame mappings to remove. */ removeTimeFrameMappings (mappings: string[]) { for (let name in mappings) { delete this.timeFrameMappings[name] } } /** * Removes all TimeFrameMapping objects. */ clearTimeFrameMappings () { this.timeFrameMappings = {} } /** * Register DateFrame objects. * * @param {object} dateFrames object with names of dateFrames for keys and DateFrame objects for values. */ registerDateFrames (dateFrames: {[name: string]: DateFrameOptions}) { for (let name in dateFrames) { let dateFrame = dateFrames[name] this.dateFrames[name] = new DateFrame(dateFrame) } } /** * Remove DateFrame objects. * * @param {array} dateFrames names of date frames to remove. */ removeDateFrames (dateFrames: string[]) { for (let name in dateFrames) { delete this.dateFrames[name] } } /** * Removes all DateFrame objects. */ clearDateFrames () { this.dateFrames = {} } filterDateFrames (inputDateFrames: {[name: string]: DateFrame}, date: moment.Moment): DateFrame[] { let dateFrames = [] for (let name in inputDateFrames) { let dateFrame = inputDateFrames[name] if (dateFrame.dateMatch(date)) { dateFrames.push(dateFrame) } } if (dateFrames.length === 0) { for (let name in inputDateFrames) { let dateFrame = inputDateFrames[name] if (dateFrame.default) { dateFrames.push(dateFrame) } } } return dateFrames } /** * Retrieves TimeFrame objects for a given date, using whole configuration for this Calendar object. * * @param {moment} date * * @return {array} an array of TimeFrame objects. */ getTimeFrames (date: moment.Moment): TimeFrame[] { let timeFrames: TimeFrame[] = [] let dateFrames = this.filterDateFrames(this.dateFrames, date) for (let dateFrame of dateFrames) { if (dateFrame !== undefined) { let targets = dateFrame.targets for (let target of targets) { let timeFrameMapping = this.timeFrameMappings[target] if (timeFrameMapping !== undefined) { // If a timeFrame mapping is found let names = timeFrameMapping.getTimeFrames(date) for (let name of names) { let timeFrame = this.timeFrames[name] timeFrames.push(timeFrame) } } else { // If no timeFrame mapping is found, try using direct timeFrame let timeFrame = this.timeFrames[target] if (timeFrame !== undefined) { timeFrames.push(timeFrame) } } } } } let dateYear = date.year() let dateMonth = date.month() let dateDate = date.date() let validatedTimeFrames = [] if (timeFrames.length === 0) { for (let name in this.timeFrames) { let timeFrame = this.timeFrames[name] if (timeFrame.default) { timeFrames.push(timeFrame) } } } for (let name in timeFrames) { let timeFrame = timeFrames[name] let cTimeFrame = timeFrame.clone() if (cTimeFrame.start !== undefined) { cTimeFrame.start.year(dateYear) cTimeFrame.start.month(dateMonth) cTimeFrame.start.date(dateDate) } if (cTimeFrame.end !== undefined) { cTimeFrame.end.year(dateYear) cTimeFrame.end.month(dateMonth) cTimeFrame.end.date(dateDate) if (moment(cTimeFrame.end).startOf('day') === cTimeFrame.end) { cTimeFrame.end.add(1, 'day') } } validatedTimeFrames.push(cTimeFrame) } return validatedTimeFrames } /** * Solve timeFrames. * * Smaller timeFrames have priority over larger one. * * @param {array} timeFrames Array of timeFrames to solve * @param {moment} startDate * @param {moment} endDate */ solve (timeFrames: TimeFrame[], startDate, endDate) { let color: string let classes: string[] let minDate: moment.Moment let maxDate: moment.Moment for (let timeFrame of timeFrames) { if (minDate === undefined || minDate > timeFrame.start) { minDate = timeFrame.start } if (maxDate === undefined || maxDate < timeFrame.end) { maxDate = timeFrame.end } if (color === undefined && timeFrame.color) { color = timeFrame.color } if (timeFrame.classes !== undefined) { if (classes === undefined) { classes = [] } classes = classes.concat(timeFrame.classes) } } if (startDate === undefined) { startDate = minDate } if (endDate === undefined) { endDate = maxDate } let solvedTimeFrames: TimeFrame[] = [new TimeFrame({start: startDate, end: endDate, internal: true})] timeFrames = GanttCalendar.$filter('filter')(timeFrames, (timeFrame) => { return (timeFrame.start === undefined || timeFrame.start < endDate) && (timeFrame.end === undefined || timeFrame.end > startDate) }) for (let timeFrame of timeFrames) { if (!timeFrame.start) { timeFrame.start = startDate } if (!timeFrame.end) { timeFrame.end = endDate } } let orderedTimeFrames = GanttCalendar.$filter('orderBy')(timeFrames, (timeFrame) => { return -timeFrame.getDuration() }) let k for (let oTimeFrame of orderedTimeFrames) { let tmpSolvedTimeFrames = solvedTimeFrames.slice() k = 0 let dispatched = false let treated = false for (let sTimeFrame of solvedTimeFrames) { if (!treated) { if (!oTimeFrame.end && !oTimeFrame.start) { // timeFrame is infinite. tmpSolvedTimeFrames.splice(k, 0, oTimeFrame) treated = true dispatched = false } else if (oTimeFrame.end > sTimeFrame.start && oTimeFrame.start < sTimeFrame.end) { // timeFrame is included in this solvedTimeFrame. // solvedTimeFrame:|ssssssssssssssssssssssssssssssssss| // timeFrame: |tttttt| // result:|sssssssss|tttttt|sssssssssssssssss| let newSolvedTimeFrame = sTimeFrame.clone() sTimeFrame.end = moment(oTimeFrame.start) newSolvedTimeFrame.start = moment(oTimeFrame.end) tmpSolvedTimeFrames.splice(k + 1, 0, oTimeFrame.clone(), newSolvedTimeFrame) treated = true dispatched = false } else if (!dispatched && oTimeFrame.start < sTimeFrame.end) { // timeFrame is dispatched on two solvedTimeFrame. // First part // solvedTimeFrame:|sssssssssssssssssssssssssssssssssss|s+1;s+1;s+1;s+1;s+1;s+1| // timeFrame: |tttttt| // result:|sssssssssssssssssssssssssssssss|tttttt|;s+1;s+1;s+1;s+1;s+1| sTimeFrame.end = moment(oTimeFrame.start) tmpSolvedTimeFrames.splice(k + 1, 0, oTimeFrame.clone()) dispatched = true } else if (dispatched && oTimeFrame.end > sTimeFrame.start) { // timeFrame is dispatched on two solvedTimeFrame. // Second part sTimeFrame.start = moment(oTimeFrame.end) dispatched = false treated = true } k++ } } solvedTimeFrames = tmpSolvedTimeFrames } solvedTimeFrames = GanttCalendar.$filter('filter')(solvedTimeFrames, (timeFrame) => { return !timeFrame.internal && (timeFrame.start === undefined || timeFrame.start < endDate) && (timeFrame.end === undefined || timeFrame.end > startDate) }) return solvedTimeFrames } } export default function ($filter: IFilterService) { 'ngInject' GanttCalendar.$filter = $filter return GanttCalendar }
the_stack
import joplin from 'api'; import { MenuItem, MenuItemLocation } from 'api/types'; import { ChangeEvent } from 'api/JoplinSettings'; import { FavoriteType, IFavorite, Favorites } from './favorites'; import { Settings } from './settings'; import { Panel } from './panel'; import { Dialog } from './dialog'; joplin.plugins.register({ onStart: async function () { const CLIPBOARD = joplin.clipboard; const COMMANDS = joplin.commands; const DATA = joplin.data; const SETTINGS = joplin.settings; const WORKSPACE = joplin.workspace; // settings const settings: Settings = new Settings(); await settings.register(); // favorites const favorites = new Favorites(settings); // panel const panel = new Panel(favorites, settings); await panel.register(); // dialogs const addDialog = new Dialog('Add'); await addDialog.register(); const editDialog = new Dialog('Edit'); await editDialog.register([ { id: 'delete', title: 'Delete', }, { id: 'ok', title: 'OK' }, { id: 'cancel', title: 'Cancel' } ]); //#region HELPERS /** * Check if favorite target still exists - otherwise ask to remove favorite */ async function checkAndRemoveFavorite(favorite: IFavorite, index: number): Promise<boolean> { try { await DATA.get([Favorites.getDesc(favorite).dataType, favorite.value], { fields: ['id'] }); } catch (err) { const result: number = await Dialog.showMessage(`Cannot open favorite. Seems that the target ${Favorites.getDesc(favorite).name.toLocaleLowerCase()} was deleted.\n\nDo you want to delete the favorite also?`); if (!result) { await favorites.delete(index); await panel.updateWebview(); return true; } } return false; } /** * Check if note/todo is still of the same type - otherwise change type */ async function checkAndUpdateType(favorite: IFavorite, index: number) { let newType: FavoriteType; const note: any = await DATA.get([Favorites.getDesc(favorite).dataType, favorite.value], { fields: ['id', 'is_todo'] }); if (Favorites.isNote(favorite) && note.is_todo) newType = FavoriteType.Todo; if (Favorites.isTodo(favorite) && (!note.is_todo)) newType = FavoriteType.Note; if (newType) { await favorites.changeType(index, newType); await panel.updateWebview(); } } /** * Add new favorite entry */ async function addFavorite(value: string, title: string, type: FavoriteType, showDialog: boolean, targetIdx?: number) { let newValue: string = value; let newTitle: string = title; // check whether a favorite with handled value already exists const index: number = favorites.indexOf(value); if (index >= 0) { // if so... open editFavorite dialog await COMMANDS.execute('favsEditFavorite', index); } else { // otherwise create new favorite, with or without user interaction if (showDialog) { // open dialog and handle result const result: any = await addDialog.open(favorites.create(newValue, newTitle, type)); if (result.id == 'ok' && result.formData != null) { newTitle = result.formData.inputForm.title; if (result.formData.inputForm.value) newValue = result.formData.inputForm.value; } else return; } if (newValue === '' || newTitle === '') return; await favorites.add(newValue, newTitle, type, targetIdx); await panel.updateWebview(); } } //#endregion //#region COMMANDS // Command: favsOpenFavorite (INTERNAL) // Desc: Internal command to open a favorite await COMMANDS.register({ name: 'favsOpenFavorite', execute: async (index: number) => { const favorite: IFavorite = favorites.get(index); if (!favorite) return; switch (favorite.type) { case FavoriteType.Folder: if (await checkAndRemoveFavorite(favorite, index)) return; COMMANDS.execute('openFolder', favorite.value); break; case FavoriteType.Note: case FavoriteType.Todo: if (await checkAndRemoveFavorite(favorite, index)) return; await checkAndUpdateType(favorite, index); COMMANDS.execute('openNote', favorite.value); break; case FavoriteType.Tag: if (await checkAndRemoveFavorite(favorite, index)) return; COMMANDS.execute('openTag', favorite.value); break; case FavoriteType.Search: // TODO there is a command `~\app-desktop\gui\MainScreen\commands\search.ts` avaiable, but currently empty // use this once it is implemented // currently there's no command to trigger a global search, so the following workaround is used // 1. copy saved search to clipboard await CLIPBOARD.writeText(favorites.getDecodedValue(favorite)); // 2. focus global search bar via command await COMMANDS.execute('focusSearch'); // 3. paste clipboard content to current cursor position (should be search bar now) // TODO how? break; default: break; } await panel.updateWebview(); } }); // Command: favsEditFavorite (INTERNAL) // Desc: Internal command to edit a favorite await COMMANDS.register({ name: 'favsEditFavorite', execute: async (index: number) => { const favorite: IFavorite = favorites.get(index); if (!favorite) return; // open dialog and handle result const result: any = await editDialog.open(favorite); if (result.id == "ok" && result.formData != null) { await favorites.changeTitle(index, result.formData.inputForm.title); await favorites.changeValue(index, result.formData.inputForm.value); } else if (result.id == "delete") { await favorites.delete(index); } else { return; } await panel.updateWebview(); } }); // Command: favsAddFolder // Desc: Add selected folder to favorites await COMMANDS.register({ name: 'favsAddFolder', label: 'Add notebook to Favorites', iconName: 'fas fa-book', enabledCondition: 'oneFolderSelected', execute: async (folderId: string, targetIdx?: number) => { if (folderId) { const folder = await DATA.get(['folders', folderId], { fields: ['id', 'title'] }); if (!folder) return; await addFavorite(folder.id, folder.title, FavoriteType.Folder, settings.editBeforeAdd, targetIdx); } else { const selectedFolder: any = await WORKSPACE.selectedFolder(); if (!selectedFolder) return; await addFavorite(selectedFolder.id, selectedFolder.title, FavoriteType.Folder, settings.editBeforeAdd, targetIdx); } } }); // Command: favsAddNote // Desc: Add selected note to favorites await COMMANDS.register({ name: 'favsAddNote', label: 'Add note to Favorites', iconName: 'fas fa-sticky-note', enabledCondition: "someNotesSelected", execute: async (noteIds: string[], targetIdx?: number) => { if (noteIds) { // in case multiple notes are selected - add them directly without user interaction for (const noteId of noteIds) { if (noteIds.length > 1 && favorites.hasFavorite(noteId)) continue; const note = await DATA.get(['notes', noteId], { fields: ['id', 'title', 'is_todo'] }); if (!note) return; // never show dialog for multiple notes const showDialog: boolean = (settings.editBeforeAdd && noteIds.length == 1); await addFavorite(note.id, note.title, note.is_todo ? FavoriteType.Todo : FavoriteType.Note, showDialog, targetIdx); } } else { const selectedNote: any = await WORKSPACE.selectedNote(); if (!selectedNote) return; await addFavorite(selectedNote.id, selectedNote.title, selectedNote.is_todo ? FavoriteType.Todo : FavoriteType.Note, settings.editBeforeAdd, targetIdx); } } }); // Command: favsAddTag // Desc: Add tag to favorites await COMMANDS.register({ name: 'favsAddTag', label: 'Add tag to Favorites', iconName: 'fas fa-tag', execute: async (tagId: string) => { if (tagId) { const tag = await DATA.get(['tags', tagId], { fields: ['id', 'title'] }); if (!tag) return; await addFavorite(tag.id, tag.title, FavoriteType.Tag, settings.editBeforeAdd); } } }); // Command: favsAddSearch // Desc: Add entered search query to favorites await COMMANDS.register({ name: 'favsAddSearch', label: 'Add new search to Favorites', iconName: 'fas fa-search', execute: async () => { await addFavorite('', 'New Search', FavoriteType.Search, true); // always add with dialog } }); // Command: favsClear // Desc: Remove all favorites await COMMANDS.register({ name: 'favsClear', label: 'Remove all Favorites', iconName: 'fas fa-times', execute: async () => { // ask user before removing favorites const result: number = await Dialog.showMessage('Do you really want to remove all Favorites?'); if (result) return; await settings.clearFavorites(); await panel.updateWebview(); } }); // Command: favsToggleVisibility // Desc: Toggle panel visibility await COMMANDS.register({ name: 'favsToggleVisibility', label: 'Toggle Favorites visibility', iconName: 'fas fa-eye-slash', execute: async () => { await panel.toggleVisibility(); } }); // prepare commands menu const commandsSubMenu: MenuItem[] = [ { commandName: 'favsAddFolder', label: 'Add active notebook' }, { commandName: 'favsAddNote', label: 'Add selected note(s)' }, { commandName: 'favsAddSearch', label: 'Add new search' }, // { // commandName: "favsAddActiveSearch", // label: 'Add current active search' // }, { commandName: 'favsClear', label: 'Remove all Favorites' }, { commandName: 'favsToggleVisibility', label: 'Toggle panel visibility' } ]; await joplin.views.menus.create('toolsFavorites', 'Favorites', commandsSubMenu, MenuItemLocation.Tools); // add commands to folders context menu await joplin.views.menuItems.create('foldersContextMenuAddFolder', 'favsAddFolder', MenuItemLocation.FolderContextMenu); // add commands to tags context menu await joplin.views.menuItems.create('tagsContextMenuAddNote', 'favsAddTag', MenuItemLocation.TagContextMenu); // add commands to notes context menu await joplin.views.menuItems.create('notesContextMenuAddNote', 'favsAddNote', MenuItemLocation.NoteListContextMenu); // add commands to editor context menu await joplin.views.menuItems.create('editorContextMenuAddNote', 'favsAddNote', MenuItemLocation.EditorContextMenu); //#endregion //#region EVENTS // let onChangeCnt = 0; SETTINGS.onChange(async (event: ChangeEvent) => { // console.debug(`onChange() hits: ${onChangeCnt++}`); await settings.read(event); await panel.updateWebview(); }); //#endregion await panel.updateWebview(); } });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormConnection_Information { interface Header extends DevKit.Controls.IHeader { /** Choose the primary account, contact, or other record involved in the connection. */ Record1Id: DevKit.Controls.Lookup; } interface tab_details_Sections { connect_from: DevKit.Controls.Section; details: DevKit.Controls.Section; } interface tab_info_Sections { description: DevKit.Controls.Section; info_s: DevKit.Controls.Section; } interface tab_details extends DevKit.Controls.ITab { Section: tab_details_Sections; } interface tab_info extends DevKit.Controls.ITab { Section: tab_info_Sections; } interface Tabs { details: tab_details; info: tab_info; } interface Body { Tab: Tabs; /** Type additional information to describe the connection, such as the length or quality of the relationship. */ Description: DevKit.Controls.String; /** Enter the end date of the connection. */ EffectiveEnd: DevKit.Controls.Date; /** Enter the start date of the connection. */ EffectiveStart: DevKit.Controls.Date; /** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */ OwnerId: DevKit.Controls.Lookup; /** Choose the primary account, contact, or other record involved in the connection. */ Record1Id: DevKit.Controls.Lookup; /** Choose the primary party's role or relationship with the second party. */ Record1RoleId: DevKit.Controls.Lookup; /** Select the secondary account, contact, or other record involved in the connection. */ Record2Id: DevKit.Controls.Lookup; /** Choose the secondary party's role or relationship with the primary party. */ Record2RoleId: DevKit.Controls.Lookup; } interface Footer extends DevKit.Controls.IFooter { /** Shows whether the connection is active or inactive. Inactive connections are read-only and can't be edited unless they are reactivated. */ StateCode: DevKit.Controls.OptionSet; } } class FormConnection_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form Connection_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Connection_Information */ Body: DevKit.FormConnection_Information.Body; /** The Footer section of form Connection_Information */ Footer: DevKit.FormConnection_Information.Footer; /** The Header section of form Connection_Information */ Header: DevKit.FormConnection_Information.Header; } class ConnectionApi { /** * DynamicsCrm.DevKit ConnectionApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the connection. */ ConnectionId: DevKit.WebApi.GuidValue; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Type additional information to describe the connection, such as the length or quality of the relationship. */ Description: DevKit.WebApi.StringValue; /** Enter the end date of the connection. */ EffectiveEnd_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the start date of the connection. */ EffectiveStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** The default image for the entity. */ EntityImage: DevKit.WebApi.StringValue; EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly; EntityImage_URL: DevKit.WebApi.StringValueReadonly; /** For internal use only. */ EntityImageId: DevKit.WebApi.GuidValueReadonly; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Unique identifier of the data import or data migration that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Indicates that this is the master record. */ IsMaster: DevKit.WebApi.BooleanValueReadonly; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Name of the connection. */ Name: DevKit.WebApi.StringValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Shows the business unit that the record owner belongs to. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team who owns the connection. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who owns the connection. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_account: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_activitypointer: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_appointment: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ profileruleid1: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_contact: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_email: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_fax: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_goal: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_knowledgearticle: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_knowledgebaserecord: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_letter: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_phonecall: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_position: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_processsession: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_recurringappointmentmaster: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_socialactivity: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_socialprofile: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_systemuser: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_task: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_team: DevKit.WebApi.LookupValue; /** Choose the primary account, contact, or other record involved in the connection. */ record1id_territory: DevKit.WebApi.LookupValue; /** Shows the record type of the source record. */ Record1ObjectTypeCode: DevKit.WebApi.OptionSetValueReadonly; /** Choose the primary party's role or relationship with the second party. */ Record1RoleId: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_account: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_activitypointer: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_appointment: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ channelaccessprofileruleid: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_contact: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_email: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_fax: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_goal: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_knowledgearticle: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_knowledgebaserecord: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_letter: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_phonecall: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_position: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_processsession: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_recurringappointmentmaster: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_socialactivity: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_socialprofile: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_systemuser: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_task: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_team: DevKit.WebApi.LookupValue; /** Select the secondary account, contact, or other record involved in the connection. */ record2id_territory: DevKit.WebApi.LookupValue; /** Shows the record type of the target record. */ Record2ObjectTypeCode: DevKit.WebApi.OptionSetValueReadonly; /** Choose the secondary party's role or relationship with the primary party. */ Record2RoleId: DevKit.WebApi.LookupValue; /** Unique identifier for the reciprocal connection record. */ RelatedConnectionId: DevKit.WebApi.LookupValueReadonly; /** Shows whether the connection is active or inactive. Inactive connections are read-only and can't be edited unless they are reactivated. */ StateCode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the connection. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Version number of the connection. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace Connection { enum Record1ObjectTypeCode { /** 1 */ Account, /** 4200 */ Activity, /** 4201 */ Appointment, /** 9400 */ Channel_Access_Profile_Rule, /** 2 */ Contact, /** 4202 */ Email, /** 4204 */ Fax, /** 9600 */ Goal, /** 9953 */ Knowledge_Article, /** 9930 */ Knowledge_Base_Record, /** 4207 */ Letter, /** 4210 */ Phone_Call, /** 50 */ Position, /** 4710 */ Process_Session, /** 4251 */ Recurring_Appointment, /** 4216 */ Social_Activity, /** 99 */ Social_Profile, /** 4212 */ Task, /** 9 */ Team, /** 2013 */ Territory, /** 8 */ User } enum Record2ObjectTypeCode { /** 1 */ Account, /** 4200 */ Activity, /** 4201 */ Appointment, /** 9400 */ Channel_Access_Profile_Rule, /** 2 */ Contact, /** 4202 */ Email, /** 4204 */ Fax, /** 9600 */ Goal, /** 9953 */ Knowledge_Article, /** 9930 */ Knowledge_Base_Record, /** 4207 */ Letter, /** 4210 */ Phone_Call, /** 50 */ Position, /** 4710 */ Process_Session, /** 4251 */ Recurring_Appointment, /** 4216 */ Social_Activity, /** 99 */ Social_Profile, /** 4212 */ Task, /** 9 */ Team, /** 2013 */ Territory, /** 8 */ User } enum StateCode { /** 0 */ Active, /** 1 */ Inactive } enum StatusCode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { ByteStr, asciiByteStr } from '../bytestr' import { Num, numIsZero } from '../num' import { Pos, NoPos } from '../pos' import { Config } from './config' import { Op } from './op' import { ops, opinfo, fmtop } from "./ops" import { PrimType, NumType, FunType, types } from "../ast" import { postorder } from './postorder' import { Register } from './reg' import { LocalSlot } from './localslot' import { LoopNest, loopnest } from './loopnest' import { dominators } from "./dom" import { BlockTree } from "./blocktree" const byteStr_main = asciiByteStr("main") const byteStr_anonfun = asciiByteStr("anonfun") export type ID = int // Location is the storage location of a value. Either a register or stack // slot. export type Location = Register | LocalSlot // Aux is an auxiliary value of Value // export type Aux = ByteStr | Uint8Array | PrimType // Value is a three-address-code operation // export class Value { id :ID // unique identifier pos :Pos = NoPos // source position op :Op // operation that computes this value type :PrimType b :Block // containing block aux :Aux|null // auxiliary info for this value auxInt :Num // auxiliary integer info for this value args :Value[] = [] // arguments of this value comment :string = '' // human readable short comment for IR formatting prevv :Value|null = null // previous value (list link) nextv :Value|null = null // next value (list link) reg :Register|null = null // allocated register uses :int = 0 // use count. Each appearance in args or b.control counts once // users = new Set<Value|Block>() constructor(id :ID, b :Block, op :Op, type :PrimType, auxInt :Num, aux :Aux|null) { this.id = id this.op = op this.type = type this.b = b this.auxInt = auxInt this.aux = aux assert(type instanceof PrimType) // assert(type.mem > 0, `ir.Value assigned abstract type ${type}`) } // clone returns a new value that is a clean copy of the receiver. // The returned clone will have zero uses and null linked-list links. clone() :Value { const a = this const b = new Value(a.b.f.newValueID(), a.b, a.op, a.type, a.auxInt, a.aux) b.pos = a.pos b.b = a.b b.args = a.args.slice() b.comment = a.comment b.reg = a.reg for (let u of a.args) { u.uses++ } return b } toString() { return 'v' + this.id } auxIsZero() :bool { return numIsZero(this.auxInt) } reset(op :Op) { const v = this v.op = op // if (op != ops.Copy && notStmtBoundary(op)) { // // Special case for OpCopy because of how it is used in rewrite // v.pos = posWithNotStmt(v.pos) // } v.resetArgs() v.auxInt = 0 v.aux = null } setArgs1(a :Value) { this.resetArgs() this.addArg(a) } setArg(i :int, v :Value) { assert(this.args[i], `setArg on null slot ${i}`) this.args[i].uses-- this.args[i] = v v.uses++ } removeArg(i :int) { let v = this.args[i] // v.users.delete(this) v.uses-- this.args.splice(i, 1) } resetArgs() { for (let a of this.args) { a.uses-- } this.args.length = 0 } addArg(v :Value) { assert(v !== this, `using self as arg to self`) v.uses++ // v.users.add(this) this.args.push(v) } // rematerializeable reports whether a register allocator should recompute // a value instead of spilling/restoring it. rematerializeable() :bool { if (!opinfo[this.op].rematerializeable) { return false } for (let a of this.args) { // SP and SB (generated by ops.SP and ops.SB) are always available. if (a.op !== ops.SP && a.op !== ops.SB) { return false } } return true } addComment(comment :string) { if (this.comment.length > 0) { this.comment += "; " + comment } else { this.comment = comment } } } // Edge represents a CFG edge. // Example edges for b branching to either c or d. // (c and d have other predecessors.) // b.Succs = [{c,3}, {d,1}] // c.Preds = [?, ?, ?, {b,0}] // d.Preds = [?, {b,1}, ?] // These indexes allow us to edit the CFG in constant time. // In addition, it informs phi ops in degenerate cases like: // b: // if k then c else c // c: // v = Phi(x, y) // Then the indexes tell you whether x is chosen from // the if or else branch from b. // b.Succs = [{c,0},{c,1}] // c.Preds = [{b,0},{b,1}] // means x is chosen if k is true. export class Edge { // block edge goes to (in a succs list) or from (in a preds list) block :Block // index of reverse edge. Invariant: // e := x.succs[idx] // e.block.preds[e.index] = Edge(x, idx) // and similarly for predecessors. index :int constructor(block :Block, index :int) { this.block = block this.index = index } } // BlockKind denotes what specific kind a block is // // kind control (x) successors notes // ---------- -------------- -------------- -------- // Plain (nil) [next] e.g. "goto" // If boolean [then, else] // Ret memory [] // // First boolean [always, never] // // BlockKind.First is used by optimizer to mark otherwise conditional // branches as always taking a certain path. // // For instance, say we have this: // // foo ()->int // b0: // v0 = ConstI32 <i32> [0] // v1 = ConstI32 <i32> [1] // v2 = ConstI32 <i32> [2] // if v0 -> b1, b2 // b1: // v3 = Copy <i32> v1 // cont -> b3 // b2: // v4 = Copy <i32> v2 // cont -> b3 // b1: // v5 = Phi v3 v4 // ret // // Now, b0's control will always route us to b1 and never b2, // since v0 is constant "1". // The optimizer may rewrite b0 as kind==First; information that // a later "deadcode" pass will use to eliminate b1 and its values: // // foo ()->int // b0: // v0 = ConstI32 <i32> [0] // v1 = ConstI32 <i32> [1] // v2 = ConstI32 <i32> [2] // first v0 -> b1, b2 // b1: // v3 = Copy <i32> v1 // cont -> b3 // b2: // v4 = Copy <i32> v2 // cont -> b3 // b1: // v5 = Phi v3 v4 // ret // // After the optimizer pipeline is done, the code will have been // reduced to simply: // // foo ()->int // b0: // v1 = ConstI32 <i32> [1] // ret // // export enum BlockKind { Invalid = 0, Plain, // a single successor If, // 2 successors, if control goto succs[0] else goto succs[1] Ret, // no successors, control value is memory result First, // 2 successors, always takes the first one (second is dead) } export enum BranchPrediction { Unlikely = -1, Unknown = 0, Likely = 1, } // Block represents a basic block // export class Block { id :ID pos :Pos = NoPos // source position kind :BlockKind = BlockKind.Invalid // The kind of block succs :Block[] = [] // Successor/subsequent blocks (CFG) preds :Block[] = [] // Predecessors (CFG) control :Value|null = null // A value that determines how the block is exited. Its value depends // on the kind of the block. For instance, a BlockKind.If has a boolean // control value and BlockKind.Exit has a memory control value. f :Fun // containing function values :Value[] = [] // three-address code values sealed :bool = false // true if no further predecessors will be added comment :string = '' // human readable short comment for IR formatting // Likely direction for branches. // If BranchLikely, succs[0] is the most likely branch taken. // If BranchUnlikely, succs[1] is the most likely branch taken. // Ignored if succs.length < 2. // Fatal if not BranchUnknown and succs.length > 2. likely :BranchPrediction = BranchPrediction.Unknown constructor(kind :BlockKind, id :ID, f :Fun) { this.kind = kind this.id = id this.f = f } // pushValueFront adds v to the top of the block // pushValueFront(v :Value) { this.values.unshift(v) } // insertValue inserts v before refv // insertValue(refv :Value, v :Value) { let i = this.values.indexOf(refv) assert(i != -1) this.values.splice(i, 0, v) } // insertValue inserts v after refv // insertValueAfter(refv :Value, v :Value) { let i = this.values.indexOf(refv) assert(i != -1) this.values.splice(i + 1, 0, v) } // removeValue removes all uses of v // removeValue(v :Value) :int { let count = 0 for (let i = 0; i < this.values.length; ) { if (this.values[i] === v) { this.values.splice(i, 1) assert(v.prevv !== v) assert(v.nextv !== v) if (v.prevv) { v.prevv.nextv = v.nextv } if (v.nextv) { v.nextv.prevv = v.prevv } v.uses-- } else { i++ } } if (count) { this.f.freeValue(v) } return count } // // replaceValue replaces all uses of existingv value with newv // // // replaceValue(existingv :Value, newv :Value) { // assert(existingv !== newv, 'trying to replace V with V') // // TODO: there must be a better way to replace values and retain their // // edges with users. // // for (let user of existingv.users) { // // assert(user !== newv, // // `TODO user==newv (newv=${newv} existingv=${existingv}) -- CYCLIC USE!`) // // for (let i = 0; i < user.args.length; i++) { // // if (user.args[i] === existingv) { // // dlog(`replace ${existingv} in user ${user} with ${newv}`) // // user.args[i] = newv // // newv.users.add(user) // // newv.uses++ // // existingv.uses-- // // } // // } // // } // // existingv.users.clear() // // Remove self. // // Note that we don't decrement this.uses since the definition // // site doesn't count toward "uses". // this.f.freeValue(existingv) // // clear block pointer. // // Note: "uses" does not count for the value's ref to its block, so // // we don't decrement this.uses here. // ;(existingv as any).b = null // } setControl(v :Value|null) { let existing = this.control if (existing) { existing.uses-- // existing.users.delete(this) } this.control = v if (v) { v.uses++ // v.users.add(this) } } // removePred removes the ith input edge e from b. // It is the responsibility of the caller to remove the corresponding // successor edge. // removePred(i :int) { this.preds.splice(i, 1) this.f.invalidateCFG() } // removeSucc removes the ith output edge from b. // It is the responsibility of the caller to remove // the corresponding predecessor edge. removeSucc(i :int) { this.succs.splice(i, 1) this.f.invalidateCFG() } // addEdgeTo adds an edge from this block to successor block b. // Used during building of the SSA graph; do not use on an already-completed SSA graph. addEdgeTo(b :Block) { assert(!b.sealed, `cannot modify ${b}.preds after ${b} was sealed`) // let i = this.succs.length // let j = b.preds.length // this.succs.push(new Edge(b, j)) // b.preds.push(new Edge(this, i)) this.succs.push(b) b.preds.push(this) this.f.invalidateCFG() } // // Like removeNthPred but takes a block reference and returns the index // // of that block as it was in this.preds // // // removePred(e :Block) :int { // let i = this.preds.indexOf(e) // assert(i > -1, `${e} not a predecessor of ${this}`) // this.removeNthPred(i) // return i // } // // Like removeNthSucc but takes a block reference and returns the index // // of that block as it was in this.succs // // // removeSucc(s :Block) :int { // let i = this.succs.indexOf(s) // assert(i > -1, `${s} not a successor of ${this}`) // this.removeNthSucc(i) // return i // } newPhi(t :PrimType) :Value { let v = this.f.newValue(this, ops.Phi, t, 0, null) if (this.values.length > 0 && this.values[this.values.length-1].op != ops.Phi) { this.values.unshift(v) } else { this.values.push(v) } return v } // newValue0 return a value with no args newValue0(op :Op, t :PrimType|null = null, auxInt :Num = 0, aux :Aux|null = null) :Value { let v = this.f.newValue(this, op, t, auxInt, aux) this.values.push(v) return v } // newValue1 returns a new value in the block with one argument newValue1(op :Op, t :PrimType|null, arg0 :Value, auxInt :Num = 0, aux :Aux|null = null) :Value { let v = this.f.newValue(this, op, t, auxInt, aux) v.args = [arg0] arg0.uses++ //; arg0.users.add(v) this.values.push(v) return v } newValue1NoAdd(op :Op, t :PrimType|null, arg0 :Value, auxInt :Num, aux :Aux|null) :Value { let v = this.f.newValue(this, op, t, auxInt, aux) v.args = [arg0] arg0.uses++ //; arg0.users.add(v) return v } // newValue2 returns a new value in the block with two arguments newValue2( op :Op, t :PrimType|null, arg0 :Value, arg1 :Value, auxInt :Num = 0, aux :Aux|null = null, ) :Value { let v = this.f.newValue(this, op, t, auxInt, aux) v.args = [arg0, arg1] arg0.uses++ //; arg0.users.add(v) arg1.uses++ //; arg1.users.add(v) this.values.push(v) return v } // newValue3 returns a new value in the block with three arguments newValue3( op :Op, t :PrimType|null, arg0 :Value, arg1 :Value, arg2 :Value, auxInt :Num = 0, aux :Aux|null = null, ) :Value { let v = this.f.newValue(this, op, t, auxInt, aux) v.args = [arg0, arg1, arg2] arg0.uses++ //; arg0.users.add(v) arg1.uses++ //; arg1.users.add(v) arg2.uses++ //; arg2.users.add(v) this.values.push(v) return v } containsCall() :bool { for (let v of this.values) { if (opinfo[v.op].call) { return true } } return false } toString() :string { return 'b' + this.id } } export interface NamedValueEnt { local :LocalSlot values :Value[] } export class Fun { id :int // function identifier (unique within package) config :Config entry :Block blocks :Block[] type :FunType name :ByteStr pos :Pos = NoPos // source position (start) nargs :int // number of arguments bid :ID = 0 // block ID allocator vid :ID = 0 // value ID allocator // constants cache consts :Map<Op,Map<Num,Value>> | null = null // implementation statistics ncalls :int = 0 // number of function calls that this function makes // nglobalw :int = 0 // number of writes to globals (0 = pure) stacksize :int = 0 // size of stack frame in bytes (aligned) // map from LocalSlot to set of Values that we want to store in that slot. namedValues = new Map<string,NamedValueEnt>() // when register allocation is done, maps value ids to locations regAlloc :Location[]|null = null // Cached CFG data _cachedPostorder :Block[]|null = null _cachedLoopnest :LoopNest|null = null _cachedIdom :(Block|null)[]|null = null // cached immediate dominators _cachedSdom :BlockTree|null = null // cached dominator tree constructor(id :int, config :Config, type :FunType, name :ByteStr|null, nargs :int) { this.id = id this.config = config this.entry = new Block(BlockKind.Plain, this.bid++, this) this.blocks = [this.entry] this.type = type this.name = name || byteStr_anonfun this.nargs = nargs } newBlock(k :BlockKind) :Block { let b = this.newBlockNoAdd(k) this.blocks.push(b) return b } newBlockNoAdd(k :BlockKind) :Block { assert(this.bid < 0xFFFFFFFF, "too many block IDs generated") return new Block(k, this.bid++, this) } freeBlock(b :Block) { assert(b.f != null, `trying to free an already freed block ${b}`) b.f = null as any as Fun // TODO: put into free list } newValue(b :Block, op :Op, t :PrimType|null, auxInt :Num, aux :Aux|null) :Value { assert(this.vid < 0xFFFFFFFF, "too many value IDs generated") // TODO we could use a free list and return values when they die assert(opinfo[op] !== undefined, `no opinfo for op ${op}`) // assert( // !t || // !opinfo[op].type || // opinfo[op].type!.mem == 0 || // t === opinfo[op].type, // `op ${fmtop(op)} with different concrete type ` + // `(op.type=${opinfo[op].type}, t=${t})` // ) let typ = t || opinfo[op].type || types.nil return new Value(this.vid++, b, op, typ, auxInt, aux) } newValueNoBlock(op :Op, t :PrimType|null, auxInt :Num, aux :Aux|null) :Value { return this.newValue(null as any as Block, op, t, auxInt, aux) } newValueID() :ID { return this.vid++ } freeValue(v :Value) { assert(v.b, `trying to free an already freed value ${v}`) assert(v.uses == 0, `value ${v} still has ${v.uses} uses`) assert(v.args.length == 0, `value ${v} still has ${v.args.length} args`) // TODO: put into free list } // constVal returns a constant Value representing c for type t // constVal(t :NumType, c :Num) :Value { let f = this // Select operation based on type let op :Op = ops.Invalid switch (t) { case types.bool: op = ops.ConstBool; break case types.u8: case types.i8: op = ops.ConstI8; break case types.u16: case types.i16: op = ops.ConstI16; break case types.u32: case types.i32: op = ops.ConstI32; break case types.u64: case types.i64: op = ops.ConstI64; break case types.f32: op = ops.ConstF32; break case types.f64: op = ops.ConstF64; break default: assert(false, `invalid constant type ${t}`) break } if (!f.consts) { f.consts = new Map<Op,Map<Num,Value>>() } let nvmap = f.consts.get(op) if (!nvmap) { nvmap = new Map<Num,Value>() f.consts.set(op, nvmap) } let v = nvmap.get(c) if (!v) { // create new const value in function's entry block v = f.blocks[0].newValue0(op, t, c) nvmap.set(c, v) // put into cache } return v as Value } constBool(c :bool) :Value { return this.constVal(types.bool, c ? 1 : 0) } removeBlock(b :Block) { let i = this.blocks.indexOf(b) assert(i != -1, `block ${b} not part of function`) this.removeBlockAt(i) } removeBlockAt(i :int) { let b = this.blocks[i]! assert(b) this.blocks.splice(i, 1) this.invalidateCFG() this.freeBlock(b) } // moveBlockToEnd moves block at index i to end of this.blocks // moveBlockToEnd(i :int) { let b = this.blocks[i]! ; assert(b) this.blocks.copyWithin(i, i + 1) this.blocks[this.blocks.length - 1] = b // let endi = this.blocks.length - 1 // if (i != endi) { // let b = this.blocks[i]! ; assert(b) // this.blocks.copyWithin(i, i + 1) // this.blocks[endi] = b // } } // numBlocks returns an integer larger than the id of any Block in the Fun. // numBlocks() :int { return this.bid } // numValues returns an integer larger than the id of any Value of any Block // in the Fun. // numValues() :int { return this.vid } postorder() :Block[] { if (!this._cachedPostorder) { this._cachedPostorder = postorder(this) } return this._cachedPostorder } loopnest() :LoopNest { return this._cachedLoopnest || (this._cachedLoopnest = loopnest(this)) } // idom returns a map from block id to the immediate dominator of that block. // f.entry.id maps to null. Unreachable blocks map to null as well. idom() :(Block|null)[] { return this._cachedIdom || (this._cachedIdom = dominators(this)) } // sdom returns a tree representing the dominator relationships // among the blocks of f. sdom() :BlockTree { return this._cachedSdom || (this._cachedSdom = new BlockTree(this, this.idom())) } // invalidateCFG tells the function that its CFG has changed // invalidateCFG() { this._cachedPostorder = null this._cachedLoopnest = null this._cachedIdom = null this._cachedSdom = null } toString() { let s = this.name.toString() if (this.id >= 0) { s += "#" + this.id } return s } } // Pkg represents a package with functions and data // export class Pkg { funs :Fun[] = [] // functions indexed by funid init :Fun|null = null // init functions (merged into one) addFun(f :Fun) { assert(this.funs[f.id] === undefined) this.funs[f.id] = f } // mainFun returns the "main" function of the package, if any. // mainFun() :Fun|null { for (let f of this.funs) { if (byteStr_main.equals(f.name)) { return f } } return null } } // export const nilFun = new Fun(new FunType([], types.nil), null, 0) // export const nilBlock = new Block(BlockKind.First, -1, nilFun) // export const nilValue = new Value(-1, nilBlock, ops.Invalid, types.nil, 0, null) export const nilValue = new Value(-1, null as any as Block, ops.Invalid, types.nil, 0, null)
the_stack
import {AbstractComponent} from "@common/component/abstract.component"; import {Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild} from "@angular/core"; import {Organization} from "@domain/organization/organization"; import {ActivatedRoute} from "@angular/router"; import {OrganizationService} from "../../../service/organization.service"; import {Alert} from "@common/util/alert.util"; import {Location} from '@angular/common'; import {Modal} from "@common/domain/modal"; import {ConfirmModalComponent} from "@common/component/modal/confirm/confirm.component"; import {OrganizationMember} from "@domain/organization/organization-member"; import {Role} from "@domain/user/role/role"; import {UpdateOrganizationManagementListComponent} from "../update-list/update-organization-management-list.component"; import {UpdateContainerOrganizationManagementComponent} from "../update-list/update-container-organization-management.component"; import {OrganizationGroup} from "@domain/organization/organization-group"; import {CommonUtil} from "@common/util/common.util"; @Component({ selector: 'app-detail-organization-list', templateUrl: 'detail-organization-management-list.component.html' }) export class DetailOrganizationManagementListComponent extends AbstractComponent implements OnInit, OnDestroy{ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 조직 코드 private _orgCode: string; // 공통 팝업 모달 @ViewChild(ConfirmModalComponent) private _confirmModalComponent: ConfirmModalComponent; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 조직 데이터 public orgData: Organization = new Organization(); // 조직 이름 수정 public editName: string; // 조직 설명 수정 public editDesc: string; // 조직 코드 수정 public editCode: string; // 조직 이름 수정 플래그 public editNameFlg: boolean; // 조직 코드 수정 플래그 public editCodeFlg: boolean; // 조직 설명 수정 플래그 public editDescFlg: boolean; public role: Role = new Role(); public members: OrganizationMember[] = []; public groups: OrganizationGroup[] = []; public defaultTab: number; public isSetMemberGroupOpen: boolean = false; public simplifiedMemberList = []; public simplifiedGroupList = []; public isMembersDropdownOpen: boolean = false; public isGroupsDropdownOpen: boolean = false; @ViewChild(UpdateOrganizationManagementListComponent) public updateOrganizationComponent: UpdateOrganizationManagementListComponent; @ViewChild(UpdateContainerOrganizationManagementComponent) public updateContainerOrganizationComponent: UpdateContainerOrganizationManagementComponent; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 생성자 constructor(private activatedRoute: ActivatedRoute, protected element: ElementRef, private organizationService: OrganizationService, private _location: Location, protected injector: Injector) { super(element, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ public ngOnInit() { super.ngOnInit(); // url orgCode 받아오기 this.activatedRoute.params.subscribe((params) => { // orgCode this._orgCode = params['orgCode']; // ui init this._initView(); // organization 상세 조회 this._getOrgDetail(this._orgCode, true); }); } // Destory public ngOnDestroy() { // Destory super.ngOnDestroy(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * Open / close member drop down */ public openMembersDropdown() { this.isMembersDropdownOpen ? this.isMembersDropdownOpen = false : this.isMembersDropdownOpen = true; } /** * Open / close group drop down */ public openGroupsDropdown() { this.isGroupsDropdownOpen ? this.isGroupsDropdownOpen = false : this.isGroupsDropdownOpen = true; } /** * Open edit popup * @param type {string} members or groups */ public openEditPopup(type: string) { if (type === 'members') { this.defaultTab = 0; this.isSetMemberGroupOpen = true; } else if (type === 'groups') { this.defaultTab = 1; this.isSetMemberGroupOpen = true; } } /** * Close set member and group popup */ public closeSetMemberGroupPopup() { this.isSetMemberGroupOpen = false; } /** * Get members without first index */ public filteredMembers() { return this.members.filter((item, index) => { if (index !== 0) { return item; } }) } /** * Get groups without first index */ public filteredGroups() { return this.groups.filter((item, index) => { if (index !== 0) { return item; } }) } /** * 그룹 상세화면으로 들어가기 * @param {string} groupId */ public onClickLinkGroup(groupId: string): void { // 쿠키에 현재 url 저장 this._savePrevRouterUrl(); // 그룹 상세화면으로 이동 this.router.navigate(['/admin/user/groups', groupId]); } public updateDetail() { this.isSetMemberGroupOpen = false; this._getMembersInOrg(this.orgData.code); } /** * 그룹 삭제 */ public deleteOrganization(): void{ // 로딩 show this.loadingShow(); this.organizationService.deleteOrganization(this.orgData.code).then(() => { // alert Alert.success(this.translateService.instant('msg.organization.alert.delete')); // loading hide this.loadingHide(); // 기존에 저장된 route 삭제 this.cookieService.delete('PREV_ROUTER_URL'); // 그룹 관리 목록으로 돌아가기 this._location.back(); }).catch((error) => { // alert Alert.error(error); // 로딩 hide this.loadingHide(); }); } /** * 조직 이름 변경 모드 */ public orgNameEditMode(): void { // 현재 조직 이름 this.editName = this.orgData.name; // flag this.editNameFlg = true; } /** * 조직 코드 변경 모드 */ public orgCodeEditMode(): void { // 현재 조직 코드 this.editCode = this.orgData.code; // flag this.editCodeFlg = true; } /** * 조직 설명 변경 모드 */ public orgDescEditMode(): void { // 현재 조직 설명 this.editDesc = this.orgData.description; // flag this.editDescFlg = true; } /** * 조직 이름 수정 */ public updateOrgName(): void { // 이벤트 전파 stop event.stopImmediatePropagation(); // validation if (this._nameValidation()) { const params = { name: this.editName }; params['description'] = this.orgData.description; // 로딩 show this.loadingShow(); // 그룹 수정 this._updateOrganization(params) .then(() => { // alert Alert.success(this.translateService.instant('msg.organization.alert.org.update.success')); // flag this.editNameFlg = false; // 그룹 정보 재조회 this._getOrgDetail(this._orgCode); }) .catch((error) => { // 로딩 hide this.loadingHide(); // error show if (error.hasOwnProperty('details') && error.details.includes('Duplicate')) { Alert.warning(this.translateService.instant('msg.organization.alert.name.used')); } }); } } // /** // * 조직 코드 수정 // */ // public updateOrgCode(): void { // // 이벤트 전파 stop // event.stopImmediatePropagation(); // // validation // if (this._codeValidation()) { // const params = { // code: this.editCode // }; // // 로딩 show // this.loadingShow(); // // 그룹 수정 // this._updateOrganization(params) // .then(() => { // // alert // Alert.success(this.translateService.instant('msg.organization.alert.org.update.success')); // // flag // this.editCodeFlg = false; // // 그룹 정보 재조회 // this._getOrgDetail(this._orgCode); // }) // .catch((error) => { // // 로딩 hide // this.loadingHide(); // // error show // if (error.hasOwnProperty('details') && error.details.includes('Duplicate')) { // Alert.warning(this.translateService.instant('msg.organization.alert.code.used')); // } // }); // } // } /** * 조직 설명 수정 */ public updateOrgDesc(): void { // 이벤트 전파 stop event.stopImmediatePropagation(); // validation if (this._descValidation()) { const params = { description: this.editDesc }; // 로딩 show this.loadingShow(); // 그룹 수정 this._updateOrganization(params) .then(() => { // alert Alert.success(this.translateService.instant('msg.organization.alert.org.update.success')); // flag this.editDescFlg = false; // 그룹 정보 재조회 this._getOrgDetail(this._orgCode); }) .catch((error) => { // 로딩 hide this.loadingHide(); // error Alert.error(error); }); } } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method - event |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 조직 목록으로 돌아가기 */ public onClickPrevOrgList(): void{ const url = this.cookieService.get('PREV_ROUTER_URL'); if(url) { this.cookieService.delete('PREV_ROUTER_URL'); this.router.navigate([url]).then(); } else { this._location.back(); } } /** * 조직 삭제 클릭 * @param orgCode */ public onClickDeleteOrganization(): void{ const modal = new Modal(); modal.name = this.translateService.instant('msg.organization.ui.delete.title'); modal.description = this.translateService.instant('msg.organization.ui.delete.description'); modal.btnName = this.translateService.instant('msg.organization.ui.delete.btn'); // 팝업 창 오픈 this._confirmModalComponent.init(modal); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * ui init * @private */ private _initView() { this.orgData = new Organization(); } private _getOrgDetail(orgCode: string, firstFlg: boolean = false): void{ // 로딩 show this.loadingShow(); // 상세정보 조회 this.organizationService.getOrganizationDetail(orgCode).then((result) => { // organization 데이터 this.orgData = result; // 최조 조회인지 확인 firstFlg ? this._getMembersInOrg(orgCode) : this.loadingHide(); }).catch((error) => { // alert Alert.error(error); // loading hide this.loadingHide(); }) } private _getMembersInOrg(orgCode: string): void{ // 로딩 show this.loadingShow(); const pageParam = {size: 10000, page: 0}; // 멤버 유저 정보 조회 this.organizationService.getOrganizationUsers(orgCode, pageParam).then((result) => { // 사용자 목록 초기화 this.members = []; // 사용자 데이터 수 초기화 this.orgData.userCount = 0; if(result.content){ // 사용자 데이터 this.members = result.content; // 사용자 데이터 수 변경 this.orgData.userCount = result.content.length; this.simplifiedMemberList = []; this.members.map((item) => { this.simplifiedMemberList.push({ directoryId: item.memberId, directoryName: item.profile.fullName, type: item.type }); }) } else { this.members = []; this.simplifiedMemberList = []; } }).catch((error) => { this.commonExceptionHandler(error); // loading hide this.loadingHide(); }); // 멤버 그룹 정보 조회 this.organizationService.getOrganizationGroups(orgCode, pageParam).then((result) => { // 그룹 목록 초기화 this.groups = []; // 그룹 목록 초기화 this.orgData.groupCount = 0; this.simplifiedGroupList = []; if(result.content){ // 그룹 데이터 this.groups = result.content; // 그룹 데이터 수 변경 this.orgData.groupCount = result.content.lenth; this.groups.map((item) => { this.simplifiedGroupList.push({ directoryId: item.memberId, directoryName: item.profile.name, type: item.type }); }) } else { this.groups = []; this.simplifiedGroupList = []; } }).catch((error) => { this.commonExceptionHandler(error); // loading hide this.loadingHide(); }); this.loadingHide(); } /** * 현재 url을 쿠키서비스에 저장 * @private */ private _savePrevRouterUrl(): void { this.cookieService.set('PREV_ROUTER_URL', this.router.url); } /** * name validation * @private */ private _nameValidation(): boolean { // 조직 이름이 비어 있다면 if(this.isNullOrUndefined(this.editName) || this.editName.trim() === ''){ Alert.warning(this.translateService.instant('msg.organization.alert.name.empty')); return false; } // 조직 이름 길이 체크 if (CommonUtil.getByte(this.editName.trim()) > 150){ Alert.warning(this.translateService.instant('msg.organization.alert.name.len')); return false; } return true; } /** * code validation * @private */ // private _codeValidation(): boolean{ // // 코드가 비어 있다면 // if(StringUtil.isEmpty(this.editCode)){ // Alert.warning(this.translateService.instant('msg.organization.alert.code.empty')); // return false; // } // // 코드 길이 체크 // if (StringUtil.isNotEmpty(this.editCode) && CommonUtil.getByte(this.editCode.trim()) > 20) { // Alert.warning(this.translateService.instant('msg.organization.alert.code.len')); // return false; // } // // 코드 공백 체크 // if (StringUtil.isNotEmpty(this.editCode) && this.editCode.trim().includes(' ')){ // Alert.warning(this.translateService.instant('msg.organization.alert.code.blank')); // return false; // } // return true; // } /** * description validation * @private */ private _descValidation(): boolean{ if (!this.isNullOrUndefined(this.editDesc) && this.editDesc.trim() !== '') { // 설명 길이 체크 if (this.editDesc.trim() !== '' && CommonUtil.getByte(this.editDesc.trim()) > 900) { Alert.warning(this.translateService.instant('msg.organization.alert.desc.len')); return false; } return true; } return true; } /** * 조직 수정 * @param params * @private */ private _updateOrganization(params: object): Promise<any>{ return new Promise((resolve, reject) => { // 수정 요청 this.organizationService.updateOrganization(this._orgCode, params).then((result) => { resolve(result); }).catch(error => { reject(error); }); }); } }
the_stack
import { h } from "@siteimprove/alfa-dom/h"; import { test } from "@siteimprove/alfa-test"; import { Device } from "@siteimprove/alfa-device"; import * as predicate from "../../../src/common/predicate/is-visible"; const isVisible = predicate.isVisible(Device.standard()); test("isVisible() returns true when an element is visible", (t) => { const element = <div>Hello world</div>; t.equal(isVisible(element), true); }); test(`isVisible() returns false when an element is hidden using the \`hidden\` attribute`, (t) => { const element = <div hidden>Hello World</div>; // Attach the element to a document to ensure that the user agent style sheet // is applied. h.document([element]); t.equal(isVisible(element), false); }); test(`isVisible() returns false when an element is hidden using the \`visibility: hidden\` property`, (t) => { const element = <div style={{ visibility: "hidden" }}>Hello World</div>; t.equal(isVisible(element), false); }); test(`isVisible() returns false when an element is hidden by reducing its size to 0 and clipping overflow`, (t) => { for (const element of [ <div style={{ width: "0", overflowX: "hidden" }}>Hello World</div>, <div style={{ width: "0", overflowY: "hidden" }}>Hello World</div>, <div style={{ height: "0", overflowX: "hidden" }}>Hello World</div>, <div style={{ height: "0", overflowY: "hidden" }}>Hello World</div>, <div style={{ width: "0", height: "0", overflow: "hidden" }}> Hello World </div>, ]) { t.equal(isVisible(element), false); } }); test(`isVisible() returns false when an element is hidden by reducing its size to 1x1 pixels and clipping overflow`, (t) => { const element = ( <div style={{ width: "1px", height: "1px", overflow: "hidden" }}> Hello World </div> ); t.equal(isVisible(element), false); }); test(`isVisible() returns false when an element scrolls its overflow and its size is reduced to 0 pixel, thus hiding the scrollbar`, (t) => { for (const element of [ <div style={{ width: "0", overflowX: "scroll" }}>Hello World</div>, <div style={{ width: "0", overflowY: "scroll" }}>Hello World</div>, <div style={{ height: "0", overflowX: "scroll" }}>Hello World</div>, <div style={{ height: "0", overflowY: "scroll" }}>Hello World</div>, <div style={{ width: "0", height: "0", overflow: "scroll" }}> Hello World </div>, ]) { t.equal(isVisible(element), false); } }); test(`isVisible() returns false when an element has its overflow set to auto and its size is reduced to 0 pixel, thus hidding the scrollbar`, (t) => { for (const element of [ <div style={{ width: "0", overflowX: "auto" }}>Hello World</div>, <div style={{ width: "0", overflowY: "auto" }}>Hello World</div>, <div style={{ height: "0", overflowX: "auto" }}>Hello World</div>, <div style={{ height: "0", overflowY: "auto" }}>Hello World</div>, <div style={{ width: "0", height: "0", overflow: "auto" }}> Hello World </div>, ]) { t.equal(isVisible(element), false); } }); test("isVisible() returns false on empty elements", (t) => { const element = <div />; t.equal(isVisible(element), false); }); test("isVisible() returns false when no child is visible", (t) => { const element = ( <div> <span hidden>Hello</span>{" "} <span style={{ visibility: "hidden" }}>World</span> </div> ); // Attach the element to a document to ensure that the user agent style sheet // is applied. h.document([element]); t.equal(isVisible(element), false); }); test("isVisible() returns true when at least one child is visible", (t) => { const element = ( <div> <span hidden>Hello</span> <span>World</span> </div> ); // Attach the element to a document to ensure that the user agent style sheet // is applied. h.document([element]); t.equal(isVisible(element), true); }); test("isVisible() returns true for replaced elements with no child", (t) => { const element = <img src="foo.jpg" />; t.equal(isVisible(element), true); }); test(`isVisible() returns false for an element that has been pulled offscreen by position: absolute and left: 9999px`, (t) => { const element = ( <div style={{ position: "absolute", left: "9999px", }} > Hello world </div> ); t.equal(isVisible(element), false); }); test(`isVisible() returns false for an element that has been pulled offscreen by position: absolute and left: -9999px`, (t) => { const element = ( <div style={{ position: "absolute", left: "-9999px", }} > Hello world </div> ); t.equal(isVisible(element), false); }); test(`isVisible() returns false for an element that has been pulled offscreen by position: absolute and right: 9999px`, (t) => { const element = ( <div style={{ position: "absolute", right: "9999px", }} > Hello world </div> ); t.equal(isVisible(element), false); }); test(`isVisible() returns false for an element that has been pulled offscreen by position: absolute and right: -9999px`, (t) => { const element = ( <div style={{ position: "absolute", right: "-9999px", }} > Hello world </div> ); t.equal(isVisible(element), false); }); test("isVisible() returns false for a text node with no data", (t) => { const text = h.text(""); t.equal(isVisible(text), false); }); test("isVisible() returns false for a text node with only whitespace", (t) => { const text = h.text(" "); t.equal(isVisible(text), false); }); test("isVisible() returns false for a text node with a transparent color", (t) => { const text = h.text("Hello world"); const div = ( <div style={{ color: "transparent", }} > {text} </div> ); t.equal(isVisible(text), false); t.equal(isVisible(div), false); }); test("isVisible() returns false for a text node with a font size of 0", (t) => { const text = h.text("Hello world"); const div = ( <div style={{ fontSize: "0", }} > {text} </div> ); t.equal(isVisible(text), false); t.equal(isVisible(div), false); }); test("isVisible() returns true for a text node with a font size of 1px", (t) => { const text = h.text("Hello world"); const div = ( <div style={{ fontSize: "1px", }} > {text} </div> ); t.equal(isVisible(text), true); t.equal(isVisible(div), true); }); test(`isVisible() returns false for a text node with hidden overflow and a 100% text indent`, (t) => { const text = h.text("Hello world"); const div = ( <div style={{ overflow: "hidden", whiteSpace: "nowrap", textIndent: "100%", }} > {text} </div> ); t.equal(isVisible(text), false); t.equal(isVisible(div), false); }); test(`isVisible() returns true for a text node with hidden overflow and a 20% text indent`, (t) => { const text = h.text("Hello world"); const div = ( <div style={{ overflow: "hidden", whiteSpace: "nowrap", textIndent: "20%", }} > {text} </div> ); t.equal(isVisible(text), true); t.equal(isVisible(div), true); }); test(`isVisible() returns false for a text node with hidden overflow and a -100% text indent`, (t) => { const text = h.text("Hello world"); const div = ( <div style={{ overflow: "hidden", textIndent: "-100%", }} > {text} </div> ); t.equal(isVisible(text), false); t.equal(isVisible(div), false); }); test(`isVisible() returns false for a text node with hidden overflow and a 999px text indent`, (t) => { const text = h.text("Hello world"); const div = ( <div style={{ overflow: "hidden", whiteSpace: "nowrap", textIndent: "999px", }} > {text} </div> ); t.equal(isVisible(text), false); t.equal(isVisible(div), false); }); test(`isVisible() returns true for a text node with hidden overflow and a 20px text indent`, (t) => { const text = h.text("Hello world"); const div = ( <div style={{ overflow: "hidden", whiteSpace: "nowrap", textIndent: "20px", }} > {text} </div> ); t.equal(isVisible(text), true); t.equal(isVisible(div), true); }); test(`isVisible() returns false for a text node with hidden overflow and a -999px text indent`, (t) => { const text = h.text("Hello world"); const div = ( <div style={{ overflow: "hidden", textIndent: "-999px", }} > {text} </div> ); t.equal(isVisible(text), false); t.equal(isVisible(div), false); }); test("isVisible() returns true for textarea with no child", (t) => { const element = <textarea />; t.equal(isVisible(element), true); }); test(`isVisible() returns false for an absolutely positioned element clipped by \`rect(1px, 1px, 1px, 1px)\``, (t) => { const element = ( <div style={{ clip: "rect(1px, 1px, 1px, 1px)", position: "absolute" }}> Invisible text </div> ); t.equal(isVisible(element), false); }); test(`isVisible() returns true for a relatively positioned element clipped by \`rect(1px, 1px, 1px, 1px)\``, (t) => { const element = ( <div style={{ clip: "rect(1px, 1px, 1px, 1px)" }}>Invisible text</div> ); t.equal(isVisible(element), true); }); test(`isVisible() returns false for a text node with a parent element with \`opacity: 0\``, (t) => { const text = h.text("Hello world"); const element = <div style={{ opacity: "0" }}>{text}</div>; t.equal(isVisible(text), false); t.equal(isVisible(element), false); }); test(`isVisible() returns false for an element with a fully clipped ancestor`, (t) => { const spanSize = <span>Hello World</span>; const spanIndent = <span>Hello World</span>; const spanMask = <span>Hello World</span>; h.document([ <div style={{ height: "0px", width: "0px", overflow: "hidden" }}> {spanSize} </div>, <div style={{ textIndent: "100%", whiteSpace: "nowrap", overflow: "hidden" }} > {spanIndent} </div>, <div style={{ clip: "rect(1px, 1px, 1px, 1px)", position: "absolute" }}> {spanMask} </div>, ]); for (const target of [spanSize, spanIndent, spanMask]) { t.equal(isVisible(target), false); } });
the_stack
import "mocha"; //const proxyFacade = require('./proxyFacade'); import { ProxyFacade } from "./proxy.facade"; import { expect } from "chai"; import { toCompleteUrl } from "../../../src/util/url.converter"; import { DependencyInjection } from "../../../src/proxy/dependency.injection"; import { TYPES } from "../../../src/proxy/dependency.injection.types"; import { IConfigServer } from "../../../src/proxy/interfaces/i.config.server"; import { IConfigStore } from "../../../src/proxy/interfaces/i.config.store"; import { NtlmConfig } from "../../../src/models/ntlm.config.model"; import { NtlmSsoConfig } from "../../../src/models/ntlm.sso.config.model"; import { osSupported } from "win-sso"; import { IPortsConfigStore } from "../../../src/proxy/interfaces/i.ports.config.store"; describe("Config API (ConfigServer deep tests)", () => { let configApiUrl: string; let dependencyInjection = new DependencyInjection(); let configServer: IConfigServer; let configStore: IConfigStore; let portsConfigStore: IPortsConfigStore; let hostConfig: NtlmConfig; before(async function () { configServer = dependencyInjection.get<IConfigServer>(TYPES.IConfigServer); // Cannot resolve these from DI since that would yield new instances configStore = (configServer as any)["_configController"]["_configStore"]; portsConfigStore = (configServer as any)["_configController"][ "_portsConfigStore" ]; configServer.init(); configApiUrl = await configServer.start(); }); beforeEach(function () { configStore.clear(); }); after(async function () { await configServer.stop(); }); describe("ntlm-config", function () { it("should return bad request if the username contains backslash", async function () { // Arrange hostConfig = { ntlmHosts: ["*.acme.org", "google.com", "localhost:5000"], username: "nisse\\nisse", password: "dummy", domain: "mptest", ntlmVersion: 2, }; // Act let res = await ProxyFacade.sendNtlmConfig(configApiUrl, hostConfig); expect(res.status).to.equal(400); expect(res.data).to.equal( "Config parse error. Username contains invalid characters or is too long." ); expect(configStore.exists(toCompleteUrl("localhost:5000", false))).to.be .false; }); it("should return bad request if the domain contains backslash", async function () { // Arrange hostConfig = { ntlmHosts: ["*.acme.org", "google.com", "localhost:5000"], username: "nisse", password: "dummy", domain: "mptest\\mptest", ntlmVersion: 2, }; // Act let res = await ProxyFacade.sendNtlmConfig(configApiUrl, hostConfig); expect(res.status).to.equal(400); expect(res.data).to.equal( "Config parse error. Domain contains invalid characters or is too long." ); expect(configStore.exists(toCompleteUrl("localhost:5000", false))).to.be .false; }); it("should return bad request if the ntlmHost includes a path", async function () { // Arrange hostConfig = { ntlmHosts: ["*.acme.org", "google.com", "localhost:5000/search"], username: "nisse", password: "dummy", domain: "mptest", ntlmVersion: 2, }; // Act let res = await ProxyFacade.sendNtlmConfig(configApiUrl, hostConfig); expect(res.status).to.equal(400); expect(res.data).to.equal( "Config parse error. Invalid host [localhost:5000/search] in ntlmHosts, must be one of: 1) a hostname or FQDN, wildcards accepted. 2) hostname or FQDN with port, wildcards not accepted (localhost:8080 or www.google.com or *.acme.com are ok, https://www.google.com:443/search is not ok)." ); expect(configStore.exists(toCompleteUrl("localhost:5000", false))).to.be .false; }); it("should return bad request if the ntlmHost includes a protocol", async function () { // Arrange hostConfig = { ntlmHosts: ["*.acme.org", "google.com", "http://localhost:5000"], username: "nisse", password: "dummy", domain: "mptest", ntlmVersion: 2, }; // Act let res = await ProxyFacade.sendNtlmConfig(configApiUrl, hostConfig); expect(res.status).to.equal(400); expect(res.data).to.equal( "Config parse error. Invalid host [http://localhost:5000] in ntlmHosts, must be one of: 1) a hostname or FQDN, wildcards accepted. 2) hostname or FQDN with port, wildcards not accepted (localhost:8080 or www.google.com or *.acme.com are ok, https://www.google.com:443/search is not ok)." ); expect(configStore.exists(toCompleteUrl("localhost:5000", false))).to.be .false; }); it("should return ok if the config is ok", async function () { // Arrange hostConfig = { ntlmHosts: ["*.acme.org", "google.com", "localhost:5000"], username: "nisse", password: "dummy", domain: "mptest", ntlmVersion: 2, }; // Act let res = await ProxyFacade.sendNtlmConfig(configApiUrl, hostConfig); expect(res.status).to.equal(200); expect(res.data).to.equal("OK"); expect(configStore.exists(toCompleteUrl("localhost:5000", false))).to.be .true; expect(configStore.exists(toCompleteUrl("www.acme.org", false))).to.be .true; expect(configStore.exists(toCompleteUrl("google.com", false))).to.be.true; }); it("should allow reconfiguration", async function () { // Arrange hostConfig = { ntlmHosts: ["*.acme.org", "google.com", "localhost:5000"], username: "nisse", password: "dummy", domain: "mptest", ntlmVersion: 2, }; let completeUrl = toCompleteUrl("localhost:5000", false); // Act let res = await ProxyFacade.sendNtlmConfig(configApiUrl, hostConfig); expect(res.status).to.equal(200); expect(res.data).to.equal("OK"); expect(configStore.exists(completeUrl)).to.be.true; expect(configStore.get(completeUrl).username).to.be.equal("nisse"); hostConfig.username = "dummy"; res = await ProxyFacade.sendNtlmConfig(configApiUrl, hostConfig); expect(res.status).to.equal(200); expect(res.data).to.equal("OK"); expect(configStore.exists(completeUrl)).to.be.true; expect(configStore.get(completeUrl).username).to.be.equal("dummy"); }); }); describe("ntlm-sso on Window", function () { before("Check SSO support", function () { // Check SSO support if (osSupported() === false) { this.skip(); return; } }); it("should return ok if the config is ok", async function () { // Arrange let ssoConfig: NtlmSsoConfig = { ntlmHosts: ["localhost"], }; // Act let res = await ProxyFacade.sendNtlmSsoConfig(configApiUrl, ssoConfig); expect(res.status).to.equal(200); expect(res.data).to.equal("OK"); expect(configStore.useSso(toCompleteUrl("http://localhost:5000", false))) .to.be.true; }); it("should return bad request if the ntlmHosts includes anything else than hostnames / FQDNs", async function () { // Arrange let ssoConfig: NtlmSsoConfig = { ntlmHosts: ["localhost", "https://google.com"], }; // Act let res = await ProxyFacade.sendNtlmSsoConfig(configApiUrl, ssoConfig); expect(res.status).to.equal(400); expect(res.data).to.equal( "SSO config parse error. Invalid host [https://google.com] in ntlmHosts, must be only a hostname or FQDN (localhost or www.google.com is ok, https://www.google.com:443/search is not ok). Wildcards are accepted." ); expect(configStore.useSso(toCompleteUrl("http://localhost:5000", false))) .to.be.false; expect(configStore.useSso(toCompleteUrl("https://google.com", false))).to .be.false; }); it("should allow reconfiguration", async function () { // Arrange let ssoConfig: NtlmSsoConfig = { ntlmHosts: ["localhost"], }; let ssoConfig2: NtlmSsoConfig = { ntlmHosts: ["nisse.com", "assa.com"], }; // Act let res = await ProxyFacade.sendNtlmSsoConfig(configApiUrl, ssoConfig); expect(res.status).to.equal(200); expect(res.data).to.equal("OK"); expect(configStore.useSso(toCompleteUrl("http://localhost:5000", false))) .to.be.true; res = await ProxyFacade.sendNtlmSsoConfig(configApiUrl, ssoConfig2); expect(res.status).to.equal(200); expect(res.data).to.equal("OK"); expect(configStore.useSso(toCompleteUrl("http://assa.com:5000", false))) .to.be.true; expect(configStore.useSso(toCompleteUrl("http://localhost:5000", false))) .to.be.false; }); }); describe("ntlm-sso on non-Window", function () { before("Check SSO support", function () { // Check SSO support if (osSupported() === true) { this.skip(); return; } }); it("should return fail even if the config is ok", async function () { // Arrange let ssoConfig: NtlmSsoConfig = { ntlmHosts: ["localhost"], }; // Act let res = await ProxyFacade.sendNtlmSsoConfig(configApiUrl, ssoConfig); expect(res.status).to.equal(400); expect(res.data).to.equal( "SSO is not supported on this platform. Only Windows OSs are supported." ); expect(configStore.useSso(toCompleteUrl("http://localhost:5000", false))) .to.be.false; }); }); describe("reset", function () { it("should return response", async function () { // Act let res = await ProxyFacade.sendNtlmReset(configApiUrl); expect(res.status).to.equal(200); expect(res.data).to.equal("OK"); }); }); describe("alive", function () { it("should return response", async function () { portsConfigStore.ntlmProxyUrl = "http://localhost:8012"; // Act let res = await ProxyFacade.sendAliveRequest(configApiUrl); expect(res.status).to.equal(200); expect(res.data).to.deep.equal({ configApiUrl: configApiUrl, ntlmProxyUrl: "http://localhost:8012", }); }); }); });
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/peeringServicesMappers"; import * as Parameters from "../models/parameters"; import { PeeringManagementClientContext } from "../peeringManagementClientContext"; /** Class representing a PeeringServices. */ export class PeeringServices { private readonly client: PeeringManagementClientContext; /** * Create a PeeringServices. * @param {PeeringManagementClientContext} client Reference to the service client. */ constructor(client: PeeringManagementClientContext) { this.client = client; } /** * Gets an existing peering service with the specified name under the given subscription and * resource group. * @param resourceGroupName The name of the resource group. * @param peeringServiceName The name of the peering. * @param [options] The optional parameters * @returns Promise<Models.PeeringServicesGetResponse> */ get(resourceGroupName: string, peeringServiceName: string, options?: msRest.RequestOptionsBase): Promise<Models.PeeringServicesGetResponse>; /** * @param resourceGroupName The name of the resource group. * @param peeringServiceName The name of the peering. * @param callback The callback */ get(resourceGroupName: string, peeringServiceName: string, callback: msRest.ServiceCallback<Models.PeeringService>): void; /** * @param resourceGroupName The name of the resource group. * @param peeringServiceName The name of the peering. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, peeringServiceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PeeringService>): void; get(resourceGroupName: string, peeringServiceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PeeringService>, callback?: msRest.ServiceCallback<Models.PeeringService>): Promise<Models.PeeringServicesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, peeringServiceName, options }, getOperationSpec, callback) as Promise<Models.PeeringServicesGetResponse>; } /** * Creates a new peering service or updates an existing peering with the specified name under the * given subscription and resource group. * @param resourceGroupName The name of the resource group. * @param peeringServiceName The name of the peering service. * @param peeringService The properties needed to create or update a peering service. * @param [options] The optional parameters * @returns Promise<Models.PeeringServicesCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, peeringServiceName: string, peeringService: Models.PeeringService, options?: msRest.RequestOptionsBase): Promise<Models.PeeringServicesCreateOrUpdateResponse>; /** * @param resourceGroupName The name of the resource group. * @param peeringServiceName The name of the peering service. * @param peeringService The properties needed to create or update a peering service. * @param callback The callback */ createOrUpdate(resourceGroupName: string, peeringServiceName: string, peeringService: Models.PeeringService, callback: msRest.ServiceCallback<Models.PeeringService>): void; /** * @param resourceGroupName The name of the resource group. * @param peeringServiceName The name of the peering service. * @param peeringService The properties needed to create or update a peering service. * @param options The optional parameters * @param callback The callback */ createOrUpdate(resourceGroupName: string, peeringServiceName: string, peeringService: Models.PeeringService, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PeeringService>): void; createOrUpdate(resourceGroupName: string, peeringServiceName: string, peeringService: Models.PeeringService, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PeeringService>, callback?: msRest.ServiceCallback<Models.PeeringService>): Promise<Models.PeeringServicesCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, peeringServiceName, peeringService, options }, createOrUpdateOperationSpec, callback) as Promise<Models.PeeringServicesCreateOrUpdateResponse>; } /** * Deletes an existing peering service with the specified name under the given subscription and * resource group. * @param resourceGroupName The name of the resource group. * @param peeringServiceName The name of the peering service. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, peeringServiceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param resourceGroupName The name of the resource group. * @param peeringServiceName The name of the peering service. * @param callback The callback */ deleteMethod(resourceGroupName: string, peeringServiceName: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName The name of the resource group. * @param peeringServiceName The name of the peering service. * @param options The optional parameters * @param callback The callback */ deleteMethod(resourceGroupName: string, peeringServiceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, peeringServiceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, peeringServiceName, options }, deleteMethodOperationSpec, callback); } /** * Updates tags for a peering service with the specified name under the given subscription and * resource group. * @param resourceGroupName The name of the resource group. * @param peeringServiceName The name of the peering service. * @param [options] The optional parameters * @returns Promise<Models.PeeringServicesUpdateResponse> */ update(resourceGroupName: string, peeringServiceName: string, options?: Models.PeeringServicesUpdateOptionalParams): Promise<Models.PeeringServicesUpdateResponse>; /** * @param resourceGroupName The name of the resource group. * @param peeringServiceName The name of the peering service. * @param callback The callback */ update(resourceGroupName: string, peeringServiceName: string, callback: msRest.ServiceCallback<Models.PeeringService>): void; /** * @param resourceGroupName The name of the resource group. * @param peeringServiceName The name of the peering service. * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, peeringServiceName: string, options: Models.PeeringServicesUpdateOptionalParams, callback: msRest.ServiceCallback<Models.PeeringService>): void; update(resourceGroupName: string, peeringServiceName: string, options?: Models.PeeringServicesUpdateOptionalParams | msRest.ServiceCallback<Models.PeeringService>, callback?: msRest.ServiceCallback<Models.PeeringService>): Promise<Models.PeeringServicesUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, peeringServiceName, options }, updateOperationSpec, callback) as Promise<Models.PeeringServicesUpdateResponse>; } /** * Lists all of the peering services under the given subscription and resource group. * @param resourceGroupName The name of the resource group. * @param [options] The optional parameters * @returns Promise<Models.PeeringServicesListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.PeeringServicesListByResourceGroupResponse>; /** * @param resourceGroupName The name of the resource group. * @param callback The callback */ listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.PeeringServiceListResult>): void; /** * @param resourceGroupName The name of the resource group. * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PeeringServiceListResult>): void; listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PeeringServiceListResult>, callback?: msRest.ServiceCallback<Models.PeeringServiceListResult>): Promise<Models.PeeringServicesListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.PeeringServicesListByResourceGroupResponse>; } /** * Lists all of the peerings under the given subscription. * @param [options] The optional parameters * @returns Promise<Models.PeeringServicesListBySubscriptionResponse> */ listBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.PeeringServicesListBySubscriptionResponse>; /** * @param callback The callback */ listBySubscription(callback: msRest.ServiceCallback<Models.PeeringServiceListResult>): void; /** * @param options The optional parameters * @param callback The callback */ listBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PeeringServiceListResult>): void; listBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PeeringServiceListResult>, callback?: msRest.ServiceCallback<Models.PeeringServiceListResult>): Promise<Models.PeeringServicesListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec, callback) as Promise<Models.PeeringServicesListBySubscriptionResponse>; } /** * Lists all of the peering services under the given subscription and resource group. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.PeeringServicesListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PeeringServicesListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PeeringServiceListResult>): 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.PeeringServiceListResult>): void; listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PeeringServiceListResult>, callback?: msRest.ServiceCallback<Models.PeeringServiceListResult>): Promise<Models.PeeringServicesListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.PeeringServicesListByResourceGroupNextResponse>; } /** * Lists all of the peerings under the given subscription. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.PeeringServicesListBySubscriptionNextResponse> */ listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PeeringServicesListBySubscriptionNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PeeringServiceListResult>): 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.PeeringServiceListResult>): void; listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PeeringServiceListResult>, callback?: msRest.ServiceCallback<Models.PeeringServiceListResult>): Promise<Models.PeeringServicesListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listBySubscriptionNextOperationSpec, callback) as Promise<Models.PeeringServicesListBySubscriptionNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}", urlParameters: [ Parameters.resourceGroupName, Parameters.peeringServiceName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PeeringService }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}", urlParameters: [ Parameters.resourceGroupName, Parameters.peeringServiceName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "peeringService", mapper: { ...Mappers.PeeringService, required: true } }, responses: { 200: { bodyMapper: Mappers.PeeringService }, 201: { bodyMapper: Mappers.PeeringService }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}", urlParameters: [ Parameters.resourceGroupName, Parameters.peeringServiceName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}", urlParameters: [ Parameters.resourceGroupName, Parameters.peeringServiceName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: { tags: [ "options", "tags" ] }, mapper: { ...Mappers.ResourceTags, required: true } }, responses: { 200: { bodyMapper: Mappers.PeeringService }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices", urlParameters: [ Parameters.resourceGroupName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PeeringServiceListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listBySubscriptionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.Peering/peeringServices", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PeeringServiceListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PeeringServiceListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listBySubscriptionNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.PeeringServiceListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import Histogram from 'goog:proto.featureStatistics.Histogram'; import RankHistogram from 'goog:proto.featureStatistics.RankHistogram'; import {OverviewDataModel} from '../../common/overview_data_model'; import * as utils from '../../common/utils'; declare var plottable_helpers: any; Polymer({ is: 'facets-overview-chart', properties: { data: {type: Object, observer: '_updateData'}, dataModel: Object, feature: String, _maxBucketsForBarChart: {type: Number, value: 10, readOnly: true}, _chartAlpha: { type: Number, value: 1 // Initially charts are opaque. }, logScale: Boolean, showWeighted: Boolean, showPercentage: Boolean, chartSelection: {type: Number, observer: '_updateChartSelection'}, // Clicking on a slice/point on a chart causes that piece of that feature to // be "selected". The selection is outlined and also is provided a property // to the client. In this way, the selection can be used to drive other // logic/visualization. This object is a FeatureSelection object. selection: {type: Object, observer: '_updateSelectionVisibility', notify: true}, expandChart: Boolean, _selectionElem: Object, _minBarHeightRatio: {type: Number, value: 0.01, readOnly: true}, _onClick: Object, _onClickFunction: Object, _onPointer: Object, _onPointerEnterFunction: Object, _onPointerExitFunction: Object, _tableData: Array, _showTable: {type: Boolean, value: false}, _chartType: Object, _chartClass: {type: String, computed: '_getChartClass(_showTable)'}, _chartSvgClass: {type: String, computed: '_getChartSvgClass(expandChart)'}, _xAxisSvgClass: {type: String, computed: '_getXAxisSvgClass(expandChart)'}, _tableDataClass: {type: String, computed: '_getTableDataClass(expandChart)'}, }, observers: ['_render(data, logScale, showWeighted, chartSelection, _showTable, ' + 'expandChart, showPercentage, dataModel)'], // tslint:disable-next-line:no-any typescript/polymer temporary issue _updateData(this: any, chartData: utils.HistogramForDataset[]) { // Reset settings on new data. this._showTable = false; }, // tslint:disable-next-line:no-any typescript/polymer temporary issue _updateChartSelection(this: any, chartSelection: string) { this._showTable = false; }, _hasWeightedHistogram(chartData: utils.HistogramForDataset[]) { return utils.hasWeightedHistogram(chartData); }, _hasQuantiles(chartData: utils.HistogramForDataset[]) { return utils.hasQuantiles(chartData); }, _isStringChart(chartType: utils.ChartType, chartSelection: string) { return (chartType === utils.ChartType.CUMDIST_CHART || chartType === utils.ChartType.BAR_CHART) && (chartSelection !== utils.CHART_SELECTION_LIST_QUANTILES && chartSelection !== utils.CHART_SELECTION_FEATURE_LIST_LENGTH_QUANTILES); }, _disableLogCheckbox(showTable: boolean, chartSelection: string) { return showTable || chartSelection !== utils.CHART_SELECTION_STANDARD; }, _render( this: any, chartData: utils.HistogramForDataset[], logScale: boolean, showWeighted: boolean, chartSelection: string, showData: boolean, expandChart: boolean, showPercentage: boolean, dataModel: OverviewDataModel) { // Remove all previously-set pointers to avoid issues with Plottable's // global interaction sets when these components are reused by the iron-list // of the table. if (this._onPointer) { this._onPointer.offPointerMove(this._onPointerEnterFunction); this._onPointer.offPointerMove(this._onPointerExitFunction); } if (this._onClick) { this._onClick.offClick(this._onClickFunction); } if (!chartData) { return; } this._chartAlpha = dataModel.getChartAlpha(); // Create the appopriate chart for the provided data. const chartBuckets = chartData.map(d => this._getBuckets(d, showWeighted, chartSelection)); this._chartType = utils.determineChartTypeForData(chartData, chartSelection, this._maxBucketsForBarChart); const names = chartData.map(d => d.name); if (chartSelection === utils.CHART_SELECTION_LIST_QUANTILES || chartSelection === utils.CHART_SELECTION_FEATURE_LIST_LENGTH_QUANTILES || chartSelection === utils.CHART_SELECTION_QUANTILES) { this._renderQuantileChart(chartBuckets, names, logScale); } else { if (this._chartType === utils.ChartType.HISTOGRAM) { this._renderHistogramChart( chartBuckets, names, logScale, showPercentage); } else if (this._chartType === utils.ChartType.CUMDIST_CHART) { this._renderCdfChart(chartBuckets, names, logScale); } else { this._renderBarChart(chartBuckets, names, logScale, showPercentage); } } }, _renderHistogramChart( // tslint:disable-next-line:no-any typescript/polymer temporary issue this: any, chartData: utils.GenericHistogramBucket[][], names: string[], logScale: boolean, showPercentage: boolean) { // Create the histogram rectangles for each bucket of each dataset. // Also calculate the average width of buckets as a sanity width for buckets // that terminate at an infinite value. const widths: number[] = []; const bars = new Plottable.Plots.Rectangle(); let min = Infinity; let max = -Infinity; let maxCount = 0; if (showPercentage) { chartData = utils.convertToPercentage(chartData); } chartData.forEach((buckets, i) => { buckets.forEach((genericBucket: utils.GenericHistogramBucket) => { const b = genericBucket as Histogram.Bucket; const low = utils.getNumberFromField(b.getLowValue()); const high = utils.getNumberFromField(b.getHighValue()); const count = utils.getNumberFromField(b.getSampleCount()); if (low < min) { min = low; } if (high > max) { max = high; } if (count > maxCount) { maxCount = count; } if (isFinite(low) && isFinite(high)) { widths.push(high - low); } }); bars.addDataset(new Plottable.Dataset(buckets, {name: names[i]})); }); let avgWidth = widths.length > 0 ? widths.reduce(function(a, b) { return a + b; }) / widths.length : 0; // If average width is 0 (there is only a single value), then use 1 as // the default width so that the bucket has visual appearance. if (avgWidth === 0) { avgWidth = 1; } // If the min is finite, set the min value of the domain for the x axis // scale. const xDomain: number[] = []; if (isFinite(min)) { xDomain.push(min); // If the max is also finite, set the max value of the domain. if (isFinite(max)) { xDomain.push(max); } } const xScale = new Plottable.Scales.Linear(); if (xDomain.length > 0) { xScale.domain(xDomain); } const yScale = this._getScale(logScale).domain([0]); const xAxis = new Plottable.Axes.Numeric(xScale, 'bottom'); const yAxis = new Plottable.Axes.Numeric(yScale, 'left'); yAxis.formatter(this._chartAxisScaleFormatter()); xAxis.formatter(this._chartAxisScaleFormatter()); // Set the rectangle boundaries based on the bucket values. If the bucket // ends in infinity or has zero width, then use the average bucket width. // tslint:disable-next-line:no-any plottable typings issue (bars as any).x((d: Histogram.Bucket) => { let x = utils.getNumberFromField(d.getLowValue()); if (x === -Infinity || x === d.getHighValue()) { const value = utils.getNumberFromField(d.getHighValue()); if (!isFinite(value)) { // A bucket with only -Infinity values should be situated below 0. x = 0; if (value === -Infinity) { x -= avgWidth; } } else { x = value - avgWidth; } } return x; }, xScale) .x2((d: Histogram.Bucket) => { let x = utils.getNumberFromField(d.getHighValue()); if (x === Infinity || x === d.getLowValue()) { const value = utils.getNumberFromField(d.getLowValue()); if (!isFinite(value)) { // A bucket with only Infinity values should be situated above 0. x = 0; if (value === Infinity) { x += avgWidth; } } else { x = value + avgWidth; } } return x; }) .y(() => 0, yScale) .y2((d: Histogram.Bucket) => this._getCountWithFloor(d, maxCount, logScale)); // Set the rectangle attributes. bars.attr( 'fill', (d: {}, i: number, dataset: Plottable.Dataset) => dataset.metadata().name, this.dataModel.getColorScale()) .attr('opacity', this._chartAlpha); this._renderChart( bars, xAxis, yAxis, null, null, (p: Plottable.Point) => bars.entitiesAt(p), (datum: any) => utils .roundToPlaces(utils.getNumberFromField(datum.getLowValue()), 2) .toLocaleString() + '-' + utils .roundToPlaces( utils.getNumberFromField(datum.getHighValue()), 2) .toLocaleString() + ': ' + utils.getNumberFromField(datum.getSampleCount()).toLocaleString(), (datum: Histogram.Bucket) => new utils.FeatureSelection( this.feature, undefined, utils.getNumberFromField(datum.getLowValue()), utils.getNumberFromField(datum.getHighValue())), (foreground: d3.Selection<HTMLElement, {}, null, undefined>) => foreground.append('rect') .attr('stroke', 'black') .attr('fill', 'none') .attr('stroke-width', '1px'), (elem: d3.Selection<HTMLElement, {}, null, undefined>, entity: Plottable.IEntity<any>) => elem.attr( 'x', entity.position.x - (entity.selection as any) ._groups[0][0] .width.baseVal.value / 2) .attr( 'y', entity.position.y - (entity.selection as any) ._groups[0][0] .height.baseVal.value / 2) .attr( 'width', (entity.selection as any)._groups[0][0].width.baseVal.value) .attr( 'height', (entity.selection as any) ._groups[0][0] .height.baseVal.value)); }, _renderQuantileChart( // tslint:disable-next-line:no-any typescript/polymer temporary issue this: any, chartData: utils.GenericHistogramBucket[][], names: string[], logScale: boolean) { const line = new Plottable.Plots.Line(); const points = new Plottable.Plots.Scatter(); let min = Infinity; let max = -Infinity; chartData.forEach((buckets, datasetIndex) => { const quantiles: utils.QuantileInfo[] = []; const numQuantiles = buckets.length; buckets.forEach( (genericBucket: utils.GenericHistogramBucket, quantileIndex: number) => { const b = genericBucket as Histogram.Bucket; const low = utils.getNumberFromField(b.getLowValue()); const high = utils.getNumberFromField(b.getHighValue()); if (low < min) { min = low; } if (high > max) { max = high; } const quantile = new utils.QuantileInfo(); quantile.bucket = b; quantile.datasetIndex = datasetIndex; quantile.quantile = quantileIndex * 100 / numQuantiles; quantiles.push(quantile); }); // Add a final bucket to represent the 100% quantile point. if (buckets.length > 0) { const lastBucket = new Histogram.Bucket(); lastBucket.setLowValue( (buckets[buckets.length - 1] as Histogram.Bucket).getHighValue()); lastBucket.setHighValue( (buckets[buckets.length - 1] as Histogram.Bucket).getHighValue()); lastBucket.setSampleCount(buckets[buckets.length - 1].getSampleCount()); const lastQuantile = new utils.QuantileInfo(); lastQuantile.bucket = lastBucket; lastQuantile.datasetIndex = datasetIndex; lastQuantile.quantile = 100; quantiles.push(lastQuantile); } line.addDataset( new Plottable.Dataset(quantiles, {name: names[datasetIndex]})); points.addDataset( new Plottable.Dataset(quantiles, {name: names[datasetIndex]})); }); // If the min is finite, set the min value of the domain for the x axis // scale. Add padding around the min and max domain to frame the // chart well. const xDomainPadding = (isFinite(min) && isFinite(max)) ? ((max === min) ? 1 : (max - min) / 10) : 0; const xDomain: number[] = []; if (isFinite(min)) { xDomain.push(min - xDomainPadding); // If the max is also finite, set the max value of the domain. if (isFinite(max)) { xDomain.push(max + xDomainPadding); } } const xScale = this._getScale(logScale); if (xDomain.length > 0) { xScale.domain(xDomain); } // Set the yScale to be able to show all quantile lines with padding above // and below (hence the extended domain). Pass false to _getScale as we // never want a log y-axis scale with quantiles as the y axis is just used // to evenly space the lines. The log checkbox is greyed out when quantile // mode is enabled. Pass false to _getScale as we // never want a log y-axis scale with quantiles as the y axis is just used // to evenly space the lines. The log checkbox is greyed out when quantile // mode is enabled. const yScale = this._getScale(false).domain([-chartData.length + .5, 1]); const xAxis = new Plottable.Axes.Numeric(xScale, 'bottom'); xAxis.formatter(this._chartAxisScaleFormatter()); line.x((d: utils.QuantileInfo) => utils.getNumberFromField( d.bucket.getLowValue()), xScale) .y((d: utils.QuantileInfo) => -1 * d.datasetIndex, yScale); points.x((d: utils.QuantileInfo) => utils.getNumberFromField( d.bucket.getLowValue()), xScale) .y((d: utils.QuantileInfo) => -d.datasetIndex, yScale) // Use a larger mark for the 50% marker. .size((d: utils.QuantileInfo) => d.quantile === 50 ? 15 : 8) .symbol((d: utils.QuantileInfo) => Plottable.SymbolFactories.cross()); // Set the point and line attributes. line.attr('stroke', 'gray') .attr('opacity', this._chartAlpha); points .attr( 'fill', (d: {}, i: number, dataset: Plottable.Dataset) => dataset.metadata().name, this.dataModel.getColorScale()) .attr('opacity', this._chartAlpha); const plots = new Plottable.Components.Group([line, points]); this._renderChart( plots, xAxis, null, null, null, (p: Plottable.Point) => points.entitiesAt(p), (datum: utils.QuantileInfo) => datum.quantile + '%: ' + utils .roundToPlaces( utils.getNumberFromField(datum.bucket.getLowValue()), 2) .toLocaleString(), (datum: utils.QuantileInfo) => new utils.FeatureSelection( this.feature, undefined, utils.getNumberFromField(datum.bucket.getLowValue()), utils.getNumberFromField(datum.bucket.getHighValue())), (foreground: d3.Selection<HTMLElement, {}, null, undefined>) => foreground.append('circle') .attr('r', 3) .attr('stroke', 'black') .attr('fill', 'none') .attr('stroke-width', '1px'), (elem: d3.Selection<HTMLElement, {}, null, undefined>, entity: Plottable.IEntity<any>) => elem.attr('cx', entity.position.x).attr('cy', entity.position.y)); }, _renderBarChart( // tslint:disable-next-line:no-any typescript/polymer temporary issue this: any, chartData: utils.GenericHistogramBucket[][], names: string[], logScale: boolean, showPercentage: boolean) { // Create a list of all labels across all datasets for use on the X-axis. const allLabels = utils.getAllLabels(chartData); const xScale = new Plottable.Scales.Linear(); const xScaleCat = new Plottable.Scales.Category(); const yScale = this._getScale(logScale); xScaleCat.domain(allLabels); const xAxis = new Plottable.Axes.Category(xScaleCat, 'bottom'); const yAxis = new Plottable.Axes.Numeric(yScale, 'left'); yAxis.formatter(this._chartAxisScaleFormatter()); if (showPercentage) { chartData = utils.convertToPercentage(chartData); } let maxCount = 0; const chartDataBuckets = chartData.map((buckets, datasetIndex) => { buckets.forEach((genericBucket: utils.GenericHistogramBucket) => { const b = genericBucket as Histogram.Bucket; const count = utils.getNumberFromField(b.getSampleCount()); if (count > maxCount) { maxCount = count; } }); const ret = new utils.BucketsForDataset(); ret.name = names[datasetIndex]; ret.rawBuckets = buckets as RankHistogram.Bucket[]; return ret; }); this._tableData = utils.getValueAndCountsArrayWithLabels( chartDataBuckets, allLabels); // Create the bars for each bucket of each dataset. const bars = new Plottable.Plots.Bar(); chartData.forEach( (buckets, datasetIndex) => bars.addDataset( new Plottable.Dataset(buckets, {name: names[datasetIndex]}))); // Set the x-position and height of each bar based on its label and count. bars.x((d: RankHistogram.Bucket) => allLabels.indexOf(utils.getPrintableLabel(d.getLabel())), xScale) .y((d: RankHistogram.Bucket) => this._getCountWithFloor(d, maxCount, logScale), yScale); // Set the bar attributes. bars.attr( 'fill', (d, i, dataset) => dataset.metadata().name, this.dataModel.getColorScale()) .attr('opacity', this._chartAlpha); this._renderChart( bars, xAxis, yAxis, null, null, (p: Plottable.Point) => bars.entitiesAt(p), (datum: RankHistogram.Bucket) => utils.getPrintableLabel(datum.getLabel()) + ': ' + utils.getNumberFromField(datum.getSampleCount()).toLocaleString(), (datum: RankHistogram.Bucket) => new utils.FeatureSelection(this.feature, datum.getLabel()), (foreground: d3.Selection<HTMLElement, {}, null, undefined>) => foreground.append('rect') .attr('stroke', 'black') .attr('fill', 'none') .attr('stroke-width', '1px'), (elem: d3.Selection<HTMLElement, {}, null, undefined>, entity: Plottable.IEntity<any>) => elem.attr( 'x', entity.position.x - (entity.selection as any) ._groups[0][0] .width.baseVal.value / 2) .attr('y', entity.position.y) .attr( 'width', (entity.selection as any)._groups[0][0].width.baseVal.value) .attr( 'height', (entity.selection as any) ._groups[0][0] .height.baseVal.value)); }, _renderCdfChart( // tslint:disable-next-line:no-any typescript/polymer temporary issue this: any, chartData: utils.GenericHistogramBucket[][], names: string[], logScale: boolean) { // Determine the total count of non-missing values for each dataset. const totals = names.map(name => { const commonStats = this.dataModel.getFeatureCommonStats(this.feature, name); if (commonStats != null) { return commonStats.getNumNonMissing() * commonStats.getAvgNumValues(); } else { return 0; } }); // Create a list of all elements across all datasets for use on the X-axis. // Also create a dictionary of all labels to their index, for quick lookup // during CDF data generation. const allLabels = utils.getAllLabels(chartData); const labelDict: {[label: string]: number} = {}; allLabels.forEach((val, index) => { labelDict[val] = index; }); const xScale = new Plottable.Scales.Linear().domain([0]); const yScale = this._getScale(logScale).domain([0]); const xAxis = new Plottable.Axes.Numeric(xScale, 'bottom'); const yAxis = new Plottable.Axes.Numeric(yScale, 'left'); // Create a line for each dataset, where the Y values are the cumulative // distribution ratios for each bucket. const lines = new Plottable.Plots.Line(); // TODO(jwexler): Move to utils const chartDataPercs = chartData.map((buckets: utils.GenericHistogramBucket[], i: number) => { // percBuckets will hold buckets that contain cumulative distribution // ratios for each bucket. rawBuckets will hold buckets that contain // the raw counts for each bucket. const percBuckets: utils.GenericHistogramBucket[] = []; const rawBuckets: utils.GenericHistogramBucket[] = []; const sortBuckets: utils.GenericHistogramBucket[] = []; let lastIndex = -1; buckets.forEach( (genericBucket: utils.GenericHistogramBucket, j: number) => { const inner = genericBucket as RankHistogram.Bucket; const percBucket = inner.cloneMessage() as RankHistogram.Bucket; sortBuckets.push(percBucket); }); // No need to sort the first dataset as the X axis starts with all // elements in the first dataset in order of their appearance in its // rank histogram. if (i > 0) { sortBuckets.sort( (genericBucketA: utils.GenericHistogramBucket, genericBucketB: utils.GenericHistogramBucket) => { const a = genericBucketA as RankHistogram.Bucket; const b = genericBucketB as RankHistogram.Bucket; return labelDict[utils.getPrintableLabel(a.getLabel())] - labelDict[utils.getPrintableLabel(b.getLabel())]; }); } sortBuckets.forEach( (genericBucket: utils.GenericHistogramBucket, j: number) => { const percBucket = genericBucket as RankHistogram.Bucket; const indexOfBucketLabel = labelDict[utils.getPrintableLabel(percBucket.getLabel())]; // If the next element on the X axis is not in this dataset, // then add empty entries for each element in the complete // union of all datasets that are missing from this dataset. for (let i = lastIndex + 1; i < indexOfBucketLabel; i++) { const emptyPercBucket = new RankHistogram.Bucket(); emptyPercBucket.setLabel(allLabels[i]); emptyPercBucket.setLowRank(i); emptyPercBucket.setHighRank(i); if (percBuckets.length === 0) { emptyPercBucket.setSampleCount(0); } else { emptyPercBucket.setSampleCount( percBuckets[percBuckets.length - 1].getSampleCount()); } percBuckets.push(emptyPercBucket); const emptyRawBucket = new RankHistogram.Bucket(); emptyRawBucket.setLabel(allLabels[i]); emptyRawBucket.setLowRank(i); emptyRawBucket.setHighRank(i); emptyRawBucket.setSampleCount(0); rawBuckets.push(emptyRawBucket); } lastIndex = indexOfBucketLabel; const rawBucket = percBucket.clone(); rawBuckets.push(rawBucket); if (j === 0) { percBucket.setSampleCount( utils.getNumberFromField( percBucket.getSampleCount()) / totals[i]); } else { const indexOfPrev = indexOfBucketLabel > 0 ? indexOfBucketLabel - 1 : j - 1; percBucket.setSampleCount( (utils.getNumberFromField( percBucket.getSampleCount()) / totals[i]) + utils.getNumberFromField( percBuckets[indexOfPrev].getSampleCount())); } percBucket.setLowRank(indexOfBucketLabel); percBucket.setHighRank(indexOfBucketLabel); percBuckets.push(percBucket); }); const ret = new utils.BucketsForDataset(); ret.name = names[i]; ret.percBuckets = percBuckets as RankHistogram.Bucket[]; ret.rawBuckets = rawBuckets as RankHistogram.Bucket[]; return ret; }); this._tableData = utils.getValueAndCountsArray(chartDataPercs); for (const d of chartDataPercs) { lines.addDataset(new Plottable.Dataset(d.percBuckets, {name: d.name})); } // Set the X and Y coordinates of each point in the line based on the // ratios calculated above and set the line color. lines.x((d: RankHistogram.Bucket) => utils.getNumberFromField(d.getLowRank()), xScale) .y((d: RankHistogram.Bucket) => utils.getNumberFromField(d.getSampleCount()), yScale); lines .attr( 'stroke', (d, i, dataset) => dataset.metadata().name, this.dataModel.getColorScale()) .attr('opacity', this._chartAlpha); this._renderChart( lines, xAxis, yAxis, null, null, (p: Plottable.Point) => lines.entitiesAt(p), (datum: RankHistogram.Bucket) => utils.getPrintableLabel(datum.getLabel()) + ': ' + utils .roundToPlaces( utils.getNumberFromField(datum.getSampleCount()), 4) .toLocaleString(), (datum: RankHistogram.Bucket) => new utils.FeatureSelection(this.feature, datum.getLabel()), (foreground: d3.Selection<HTMLElement, {}, null, undefined>) => foreground.append('circle') .attr('r', 3) .attr('stroke', 'black') .attr('fill', 'none') .attr('stroke-width', '1px'), (elem: d3.Selection<HTMLElement, {}, null, undefined>, entity: Plottable.IEntity<any>) => elem.attr('cx', entity.position.x).attr('cy', entity.position.y)); }, _renderChart<T>( // tslint:disable-next-line:no-any typescript/polymer temporary issue this: any, plot: Plottable.Plot, xAxis: Plottable.Axis<T>, yAxis: Plottable.Axis<T>, xLabel: Plottable.Components.AxisLabel, yLabel: Plottable.Components.AxisLabel, getEntities: (point: Plottable.Point) => Plottable.Plots.IPlotEntity[], tooltipCallback: (datum: any) => string, selectionCallback: (datum: any) => utils.FeatureSelection, selectionCreator: (foreground: d3.Selection<HTMLElement, {}, null, undefined>) => {}, selectionPositioner: ( elem: d3.Selection<HTMLElement, {}, null, undefined>, entity: Plottable.IEntity<any>) => null) { if (this._showTable) { return; } // Create separate Plottable tables, with the chart and Y axis in one table // and the X axis in another table so they can be rendered to separate // SVGs with separate bounding boxes. This allows the chart to have a // constant size regardless of the size needed for the X axis strings. const nullComp: Plottable.Component|null = null; const chartTable = new Plottable.Components.Table( [[yLabel, yAxis, plot], [nullComp!, nullComp!, nullComp!]]); const xAxisTable = new Plottable.Components.Table( [[nullComp!, nullComp!], [nullComp!, xAxis]]); // Render the chart. Use immediate rendering mode so that the chart can be // rendered first and the width of the X axis component used to position // the Y axis component. Plottable.RenderController.renderPolicy( Plottable.RenderController.Policy.immediate); const chartSelection: d3.Selection<HTMLElement, {}, null, undefined> = d3.select(this.$.chart); const axisSelection: d3.Selection<HTMLElement, {}, null, undefined> = d3.select(this.$.xaxis); const tooltip: d3.Selection<HTMLElement, {}, null, undefined> = d3.select(this.$.tooltip); this.async(() => { // Remove the chart component but not anything else as this would disable // tooltips by removing the mouse dispatcher's measure rect. chartSelection.selectAll('.component').remove(); axisSelection.selectAll('.component').remove(); chartTable.renderTo(this.$.chart); this._selectionElem = selectionCreator( plot.foreground() as d3.Selection<HTMLElement, {}, null, undefined>); this._updateSelectionVisibility(this.selection); chartSelection .on('mouseenter', () => { // Setup pointer interaction for tooltip and attach to the plot. this._onPointer = new plottable_helpers.PointerInteraction(); this._onPointerEnterFunction = (p: any) => { // For line charts, give a tooltip for the closest point on // any line. For other charts, give a tooltip for all entries // in any dataset that is overlapping with the datum nearest // the pointer (for overlapping histograms for example). const entities = getEntities(p); if (entities.length > 0) { const title = entities .map(entity => { return (entity.dataset.metadata().name == null || this.dataModel.getDatasetNames() .length === 1) ? tooltipCallback(entity.datum) : entity.dataset.metadata().name + ': ' + tooltipCallback(entity.datum); }) .join('\n'); tooltip.text(title); tooltip.style('opacity', '1'); } }; this._onPointer.onPointerMove(this._onPointerEnterFunction); this._onPointerExitFunction = function(p: {}) { tooltip.style('opacity', '0'); }; this._onPointer.onPointerExit(this._onPointerExitFunction); this._onPointer.attachTo(plot); if (this.chartSelection !== utils.CHART_SELECTION_LIST_QUANTILES) { this._onClick = new Plottable.Interactions.Click(); const self = this; this._onClickFunction = (p: any) => { const entities = getEntities(p); if (entities.length > 0) { selectionPositioner(self._selectionElem, entities[0]); const selection: utils.FeatureSelection|null = selectionCallback(entities[0].datum); self._setSelection(selection); } }; this._onClick.onClick(this._onClickFunction); this._onClick.attachTo(plot); } }) .on('mouseleave', () => { this._onPointer.detachFrom(plot); this._onClick.detachFrom(plot); }); // Add padding equal to the Y axis component to the X axis table to align // the axes. if (yAxis != null) { xAxisTable.columnPadding(chartTable.componentAt(0, 1).width() + (chartTable.componentAt(0, 0) ? chartTable.componentAt(0, 0).width() : 0)); } xAxisTable.renderTo(this.$.xaxis); }); }, // tslint:disable-next-line:no-any typescript/polymer temporary issue _setSelection(this: any, newSelection: utils.FeatureSelection) { if (newSelection.equals(this.selection)) { newSelection.clear(); } this.selection = newSelection; this.fire('feature-select', {selection: newSelection}); }, _getBuckets( data: utils.HistogramForDataset, showWeighted: boolean, chartSelection: string): utils.GenericHistogramBucket[] { return utils.getBuckets(data, showWeighted, chartSelection); }, _getScale(logScale: boolean) { return logScale ? new Plottable.Scales.ModifiedLog() : new Plottable.Scales.Linear(); }, _chartAxisScaleFormatter() { // Use a short scale formatter if the value is above 1000. const shortScaleFormatter = Plottable.Formatters.shortScale(0); return (num: number) => { if (Math.abs(num) < 1000) { return String(num); } return shortScaleFormatter(num); }; }, _getCountWithFloor( // tslint:disable-next-line:no-any typescript/polymer temporary issue this: any, bucket: utils.GenericHistogramBucket, maxCount: number, logScale: boolean) { // wouldn't be visible (this only happens in linear scale), then return // a count that would make the bucket barely visible in the chart. let count = utils.getNumberFromField(bucket.getSampleCount()); if (!logScale && count > 0 && count / maxCount < this._minBarHeightRatio) { count = maxCount * this._minBarHeightRatio; } return count; }, // tslint:disable-next-line:no-any typescript/polymer temporary issue _updateSelectionVisibility: function( this: any, selection: utils.FeatureSelection) { if (!this._selectionElem) { return; } this._selectionElem.style('display', selection == null || selection.name !== this.feature ? 'none' : 'inline'); }, // tslint:disable-next-line:no-any typescript/polymer temporary issue _toggleShowTable(this: any, e: any) { this._showTable = !this._showTable; }, _getChartClass(showData: boolean) { return showData ? 'hidechart' : 'showchart'; }, _getShowTableButtonText(showData: boolean) { return showData ? 'show chart' : 'show raw data'; }, _getChartSvgClass(expandChart: boolean) { return expandChart ? 'chart-big' : 'chart-small'; }, _getXAxisSvgClass(expandChart: boolean) { return expandChart ? 'xaxis-big' : 'xaxis-small'; }, _getTableDataClass(expandChart: boolean) { return expandChart ? 'data-list-big' : 'data-list-small'; }, // tslint:disable-next-line:no-any typescript/polymer temporary issue _rowClick(this: any, e: any) { // Set the current selection to the value represented by the table row // that was clicked. const selection = new utils.FeatureSelection(this.feature, e.currentTarget.dataValue); this._setSelection(selection); }, _getEntryRowValue(entry: utils.ValueAndCounts) { return entry.value; }, _getEntryRowClass( // tslint:disable-next-line:no-any typescript/polymer temporary issue this: any, entry: utils.ValueAndCounts, selection: utils.FeatureSelection) { // Get the CSS class(es) for a row in the table view, dependent on if the // row represents the current user-selection or not. let str = "dialog-row"; if (selection != null && selection.name === this.feature && selection.stringValue === entry.value) { str += " selected"; } return str; }, _getCountCellClass(showWeighted: boolean) { return 'dailog-row-entry count-cell' + (showWeighted ? ' weighted-cell' : ''); }, });
the_stack
* parses the content as csv * also fills the commentLinesBefore and commentLinesAfter array if comments is enabled * commentLinesAfter contains all comments after the commentLinesBefore (this includes comments in the data) * on error the errors are displayed and null is returned * @param {string} content * @returns {[string[], string[][], string[]]| null} [0] comments before, [1] csv data, [2] comments after */ function parseCsv(content: string, csvReadOptions: CsvReadOptions): ExtendedCsvParseResult | null { if (content === '') { content = defaultCsvContentIfEmpty } //comments are parses as normal text, only one cell is added const parseResult = csv.parse(content, { ...csvReadOptions, comments: false, //false gives use all lines we later check each line if it's a comment to merge the cells in that row //left trimmed lines are comments and if !== null we want to include comments as one celled row (in the ui) //papaparse parses comments with this only if the begin with the comment string (no space before!!) rowInsertCommentLines_commentsString: typeof csvReadOptions.comments === 'string' && csvReadOptions.comments !== '' ? csvReadOptions.comments : null, // fastMode: false //monkeypatch must work with normal and fast mode... /** * normally when parsing quotes are discarded as they don't change the retrieved data * true: quote information are returned as part of the parse result, for each column: * true: column was quoted * false: column was not quoted * false: quote information is returned as null or undefined (falsy) * * to determine if a column is quoted we use the first cell only (if a column has no cells then it's not quoted) * so if the first line has only 3 columns and all other more than 3 (e.g. 4) then all columns starting from 4 are treated as not quoted!! * not that there is no difference if we have column headers (first row is used) * comment rows are ignored for this */ retainQuoteInformation: true, //we keep true here and decide if we use it whe nwe output data } as any) if (parseResult.errors.length === 1 && parseResult.errors[0].type === 'Delimiter' && parseResult.errors[0].code === 'UndetectableDelimiter') { //this is ok papaparse will default to , } else { if (parseResult.errors.length > 0) { for (let i = 0; i < parseResult.errors.length; i++) { const error = parseResult.errors[i]; if (error.type === 'Delimiter' && error.code === 'UndetectableDelimiter') { // continue; } if (typeof error.row === 'number') { statusInfo.innerText = `Error` const errorMsg = `${error.message} on line ${error.row+1}` csvEditorDiv.innerText = errorMsg _error(errorMsg) //row is 0 based continue } statusInfo.innerText = `Error` const errorMsg = `${error.message}` csvEditorDiv.innerText = errorMsg _error(errorMsg) } return null } } defaultCsvWriteOptions.delimiter = parseResult.meta.delimiter newLineFromInput = parseResult.meta.linebreak updateNewLineSelect() readDelimiterTooltip.setAttribute('data-tooltip', `${readDelimiterTooltipText} (detected: ${defaultCsvWriteOptions.delimiter.replace("\t", "⇥")})`) return { data: parseResult.data, columnIsQuoted: (parseResult as any).columnIsQuoted } } /*+ * updates the new line select option (same as input) {@link newlineSameSsInputOption} from {@link newLineFromInput} */ function updateNewLineSelect() { newlineSameSsInputOption.innerText = `${newlineSameSsInputOptionText} (${newLineFromInput === `\n` ? 'LF' : 'CRLF'})` } /** * * @returns {string[][]} the current data in the handson table */ function getData(): string[][] { //hot.getSourceData() returns the original data (e.g. not sorted...) if (!hot) throw new Error('table was null') return hot.getData() } /** * if we have an header row already it is ignored here!! */ function getFirstRowWithIndex(skipCommentLines: boolean = true): HeaderRowWithIndex | null { if (!hot) return null const rowCount = hot.countRows() if (rowCount === 0) return null let firstDataRow: string[] = [] let rowIndex = -1 for (let i = 0; i < rowCount; i++) { const row = hot.getDataAtRow(i) if (row.length === 0) continue if (skipCommentLines && isCommentCell(row[0], defaultCsvReadOptions)) continue firstDataRow = [...row] //make a copy to not get a reference rowIndex = i break } if (rowIndex === -1) { return null } return { physicalIndex: rowIndex, row: firstDataRow } } function getFirstRowWithIndexByData(data: string[][], skipCommentLines: boolean = true): HeaderRowWithIndex | null { const rowCount = data.length if (rowCount === 0) return null let firstDataRow: string[] = [] let rowIndex = -1 for (let i = 0; i < rowCount; i++) { const row = data[i] if (row.length === 0) continue if (skipCommentLines && isCommentCell(row[0], defaultCsvReadOptions)) continue firstDataRow = [...row] //make a copy to not get a reference rowIndex = i break } if (rowIndex === -1) { return null } return { physicalIndex: rowIndex, row: firstDataRow } } /** * return the data in the handson table as a string (with respect to the write options) * if comments are enabled the commentLinesBefore and commentLinesAfter are also used * @param {any} csvReadOptions used to check if a row is a comment * @param {any} csvWriteOptions * @returns {string} */ function getDataAsCsv(csvReadOptions: CsvReadOptions, csvWriteOptions: CsvWriteOptions): string { const data = getData() if (csvWriteOptions.newline === '') { csvWriteOptions.newline = newLineFromInput } const _conf: import('papaparse').UnparseConfig = { ...csvWriteOptions, quotes: csvWriteOptions.quoteAllFields, //custom created option to handle null, undefined and empty string values //@ts-ignore quoteEmptyOrNullFields: csvWriteOptions.quoteEmptyOrNullFields, } if (csvWriteOptions.header) { //write the header... if (!hot) throw new Error('table was null') if (headerRowWithIndex === null) { const colHeaderCells = hot.getColHeader() as string[] //default headers... because the actual header string is html we need to generate the string only column headers data.unshift(colHeaderCells.map((p: string, index: number) => getSpreadsheetColumnLabel(index))) } else { if (headerRowWithIndex === null) { throw new Error('header row was null') } data.unshift(headerRowWithIndex.row.map<string>((val) => val !== null ? val : '')) } } for (let i = 0; i < data.length; i++) { const row = data[i]; if (row[0] === null) continue //e.g. when we add a new empty row if (typeof csvReadOptions.comments === 'string' && typeof csvWriteOptions.comments === 'string' && isCommentCell(row[0], csvReadOptions)) { //this is a comment //we expanded comment rows to have the max length //we monkeypatched papaparse so that comments are treated as normal text (1 cell) //so just take the first cell/column const index = row[0].indexOf(csvReadOptions.comments) //trim left else papaparse (and probably other programs) will not recognize the comment anymore... row[0] = `${row[0].substring(0, index)}${csvWriteOptions.comments}${row[0].substring(index+csvReadOptions.comments.length)}`.trimLeft().replace(/\n/mg, "") } } //not documented in papaparse... //@ts-ignore _conf['skipEmptyLines'] = false //a custom param //rowInsertCommentLines_commentsString: trim left comment lines and only export first cell //@ts-ignore _conf['rowInsertCommentLines_commentsString'] = typeof csvWriteOptions.comments === 'string' ? csvWriteOptions.comments : null //@ts-ignore _conf['columnIsQuoted'] = csvWriteOptions.retainQuoteInformation ? columnIsQuoted : null let dataAsString = csv.unparse(data, _conf) return dataAsString } /* --- messages back to vs code --- */ /** * called to read the source file again * @param text */ function postReloadFile() { if (!vscode) { console.log(`postReloadFile (but in browser)`) return } _postReadyMessage() } /** * called to display the given text in vs code * @param text */ var postVsInformation = (text: string) => { if (!vscode) { console.log(`postVsInformation (but in browser)`) return } vscode.postMessage({ command: 'msgBox', type: 'info', content: text }) } /** * called to display the given text in vs code * @param text */ var postVsWarning = (text: string) => { if (!vscode) { console.log(`postVsWarning (but in browser)`) return } vscode.postMessage({ command: 'msgBox', type: 'warn', content: text }) } /** * called to display the given text in vs code * @param text */ var postVsError = (text: string) => { if (!vscode) { console.log(`postVsError (but in browser)`) return } vscode.postMessage({ command: 'msgBox', type: 'error', content: text }) } /** * called to copy the text to the clipboard through vs code * @param text the text to copy */ function postCopyToClipboard(text: string) { if (!vscode) { console.log(`postCopyToClipboard (but in browser)`) navigator.clipboard.writeText(text) return } vscode.postMessage({ command: 'copyToClipboard', text }) } /** * called to change the editor title through vs code * @param text the new title */ function postSetEditorHasChanges(hasChanges: boolean) { _setHasUnsavedChangesUiIndicator(hasChanges) if (!vscode) { console.log(`postSetEditorHasChanges (but in browser)`) return } vscode.postMessage({ command: 'setHasChanges', hasChanges }) } /** * called to save the current edit state back to the file * @param csvContent * @param saveSourceFile */ function _postApplyContent(csvContent: string, saveSourceFile: boolean) { _setHasUnsavedChangesUiIndicator(false) if (!vscode) { console.log(`_postApplyContent (but in browser)`) return } vscode.postMessage({ command: 'apply', csvContent, saveSourceFile }) } function _postReadyMessage() { if (!vscode) { console.log(`_postReadyMessage (but in browser)`) return } startReceiveCsvProgBar() vscode.postMessage({ command: 'ready' }) } function handleVsCodeMessage(event: { data: ReceivedMessageFromVsCode }) { const message = event.data switch (message.command) { case 'csvUpdate': { if (typeof message.csvContent === 'string') { onReceiveCsvContentSlice({ text: message.csvContent, sliceNr: 1, totalSlices: 1 }) } else { onReceiveCsvContentSlice(message.csvContent) } break } case "applyPress": { postApplyContent(false) break } case 'applyAndSavePress': { postApplyContent(true) break } case 'changeFontSizeInPx': { changeFontSizeInPx(message.fontSizeInPx) break } case 'sourceFileChanged': { const hasAnyChanges = getHasAnyChangesUi() if (!hasAnyChanges && !isReadonlyMode) { //just relaod the file because we have no changes anyway... reloadFileFromDisk() return } toggleSourceFileChangedModalDiv(true) break } default: { _error('received unknown message from vs code') notExhaustiveSwitch(message) break } } } function onReceiveCsvContentSlice(slice: StringSlice) { // console.log(`received slice ${slice.sliceNr}/${slice.totalSlices}`) if (slice.sliceNr === 1) { initialContent = '' statusInfo.innerText = `Receiving csv...` csvEditorDiv.innerText = `` } initialContent += slice.text receivedCsvProgBar.value = slice.sliceNr * 100 / slice.totalSlices // console.log(`% = ${receivedCsvProgBar.value}`) if (slice.sliceNr === slice.totalSlices) { // intermediateReceiveCsvProgBar() //now showing because ui thread is blocked stopReceiveCsvProgBar() startRenderData() } } /** * performs the last steps to actually show the data (set status, render table, ...) * also called on reset data */ function startRenderData(){ statusInfo.innerText = `Rendering table...` //TODO as we don't longer use undo/redo with has header option this might not be necessary any longer... //we need to change defaultCsvReadOptions because the undo/redo might mess up our //defaultCsvReadOptions._hasHeader state... so ensure it's in sync with the ui if (hasHeaderReadOptionInput.checked) { isFirstHasHeaderChangedEvent = true defaultCsvReadOptions._hasHeader = true } else { isFirstHasHeaderChangedEvent = false defaultCsvReadOptions._hasHeader = false } call_after_DOM_updated(() => { resetData(initialContent, defaultCsvReadOptions) statusInfo.innerText = `Performing last steps...` //profiling shows that handsontable calls some column resize function which causes the last hang... //status display should be cleared after the handsontable operation so enqueue if (!defaultCsvReadOptions._hasHeader) { //when we apply header this will reset the status for us setTimeout(() => { statusInfo.innerText = ''; }, 0) } }) } //from https://www.freecodecamp.org/forum/t/how-to-make-js-wait-until-dom-is-updated/122067/2 function call_after_DOM_updated(fn: any) { var intermediate = function () { window.requestAnimationFrame(fn) } window.requestAnimationFrame(intermediate) } function notExhaustiveSwitch(x: never): never { throw new Error('not exhaustive switch') }
the_stack
import { pascalCase } from 'pascal-case'; import * as s3 from '@aws-cdk/aws-s3'; import * as ec2 from '@aws-cdk/aws-ec2'; import * as iam from '@aws-cdk/aws-iam'; import * as cdk from '@aws-cdk/core'; import { Vpc } from '@aws-accelerator/cdk-constructs/src/vpc'; import { InstanceProfile } from '@aws-accelerator/cdk-constructs/src/iam'; import * as c from '@aws-accelerator/common-config/src'; import { StackOutput, getStackJsonOutput, OUTPUT_SUBSCRIPTION_REQUIRED, } from '@aws-accelerator/common-outputs/src/stack-output'; import { FirewallCluster, FirewallClusterProps, FirewallInstance } from '@aws-accelerator/cdk-constructs/src/firewall'; import { AccountStacks, AccountStack } from '../../../common/account-stacks'; import { FirewallVpnConnection, CfnFirewallInstanceOutput, FirewallVpnConnectionOutputFinder, CfnFirewallConfigReplacementsOutput, } from './outputs'; import { checkAccountWarming } from '../../account-warming/outputs'; import { createIamInstanceProfileName } from '../../../common/iam-assets'; import { RegionalBucket } from '../../defaults'; import { string as StringType } from 'io-ts'; import { CfnSleep } from '@aws-accelerator/custom-resource-cfn-sleep'; import { addReplacementsToUserData } from './step-4'; import { Account } from '../../../utils/accounts'; export interface FirewallStep3Props { accountBuckets: { [accountKey: string]: RegionalBucket }; accountStacks: AccountStacks; centralBucket: s3.IBucket; config: c.AcceleratorConfig; outputs: StackOutput[]; vpcs: Vpc[]; defaultRegion: string; accounts: Account[]; } /** * Creates the firewall clusters using the EIPs and customer gateways from previous steps. * * The following outputs are necessary from previous steps: * - Firewall ports with optional VPN connections from step 2 of the firewall deployment * - VPC with the name equals firewallConfig.vpc and with the necessary subnets and security group */ export async function step3(props: FirewallStep3Props) { const { accountBuckets, accountStacks, centralBucket, config, outputs, vpcs, defaultRegion, accounts } = props; const vpcConfigs = config.getVpcConfigs(); const replacementsConfig = config.replacements; const replacements = additionalReplacements(replacementsConfig); for (const [accountKey, accountConfig] of config.getAccountConfigs()) { const firewallConfigs = accountConfig.deployments?.firewalls; if (!firewallConfigs || firewallConfigs.length === 0) { continue; } const accountWarming = checkAccountWarming(accountKey, outputs); const accountWarmingStatus = accountConfig['account-warming-required'] && !(accountWarming.accountWarmed || (accountWarming.timeLeft && accountWarming.timeLeft > 0)); if (accountWarmingStatus) { console.log(`Skipping firewall deployment: account "${accountKey}" is not warmed`); continue; } const accountBucket = accountBuckets[accountKey]; if (!accountBucket) { throw new Error(`Cannot find default account bucket for account ${accountKey}`); } const subscriptionOutputs = getStackJsonOutput(outputs, { outputType: 'AmiSubscriptionStatus', accountKey, }); for (const firewallConfig of firewallConfigs.filter(firewall => c.FirewallEC2ConfigType.is(firewall))) { if (!firewallConfig.deploy) { console.log(`Deploy set to false for "${firewallConfig.name}"`); continue; } if (!c.FirewallEC2ConfigType.is(firewallConfig)) { continue; } const attachConfig = firewallConfig['tgw-attach']; if (!c.TransitGatewayAttachConfigType.is(attachConfig)) { continue; } const subscriptionStatus = subscriptionOutputs.find(sub => sub.imageId === firewallConfig['image-id']); if (subscriptionStatus && subscriptionStatus.status === OUTPUT_SUBSCRIPTION_REQUIRED) { console.log(`AMI Marketplace subscription required for ImageId: ${firewallConfig['image-id']}`); continue; } // TODO add region check also if vpc name is not unique accross Account const vpcConfig = vpcConfigs.find(v => v.vpcConfig.name === firewallConfig.vpc)?.vpcConfig; if (!vpcConfig) { console.log(`Skipping firewall deployment because of missing VPC config "${firewallConfig.vpc}"`); continue; } const vpc = vpcs.find(v => v.name === firewallConfig.vpc); if (!vpc) { console.log(`Skipping firewall deployment because of missing VPC "${firewallConfig.vpc}"`); continue; } // Find the firewall VPN connections in the TGW account const firewallVpnConnectionOutputs = FirewallVpnConnectionOutputFinder.findAll({ outputs, accountKey: attachConfig.account, region: firewallConfig.region, }); const firewallVpnConnections = firewallVpnConnectionOutputs .flatMap(array => array) .filter(conn => conn.firewallAccountKey === accountKey && conn.firewallName === firewallConfig.name); if (firewallVpnConnections.length === 0) { console.warn(`Cannot find firewall VPN connection outputs`); continue; } const accountStack = accountStacks.tryGetOrCreateAccountStack(accountKey, firewallConfig.region); if (!accountStack) { console.warn(`Cannot find account stack ${accountStack}`); continue; } let sleep: CfnSleep | undefined; if ( accountConfig['account-warming-required'] && !accountWarming.accountWarmed && accountWarming.timeLeft && accountWarming.timeLeft > 0 ) { const existing = accountStack.node.tryFindChild('ClusterSleep'); if (existing) { sleep = existing as CfnSleep; } else { sleep = new CfnSleep(accountStack, 'ClusterSleep', { // Setting 5 minutes sleep and performing firewall cluster creation. sleep: 5 * 60 * 1000, }); } } await createFirewallCluster({ accountBucket, accountStack, centralBucket, firewallConfig, firewallVpnConnections, vpc, vpcConfig, replacements, sleep, userData: firewallConfig['user-data'] ? await addReplacementsToUserData({ userData: firewallConfig['user-data']!, accountKey, accountStack, config, defaultRegion, outputs, accounts, }) : undefined, }); } } } function findFirewallPrivateIp(props: { firewallConfig: c.FirewallEC2ConfigType; subnetName: string; az: string }) { const { firewallConfig, subnetName, az } = props; const subnetPort = firewallConfig.ports.filter(e => e.subnet === subnetName)[0]; if (subnetPort && subnetPort.hasOwnProperty('private-ips') && subnetPort['private-ips']) { const azIp = subnetPort['private-ips'].filter(e => e.az === az)[0]; if (azIp && azIp.hasOwnProperty('ip')) { return azIp.ip; } } return undefined; } /** * Create firewall for the given VPC and config in the given scope. */ async function createFirewallCluster(props: { accountBucket: RegionalBucket; accountStack: AccountStack; centralBucket: s3.IBucket; firewallConfig: c.FirewallEC2ConfigType; firewallVpnConnections: FirewallVpnConnection[]; vpc: Vpc; vpcConfig: c.VpcConfig; replacements?: { [key: string]: string }; sleep?: CfnSleep; userData?: string; }) { const { accountStack, accountBucket, centralBucket, firewallConfig, firewallVpnConnections, vpc, vpcConfig, replacements, sleep, userData, } = props; const { name: firewallName, config: configFile, license: licenseFiles, 'security-group': securityGroupName, 'fw-instance-role': instanceRoleName, 'image-id': imageId, 'instance-sizes': instanceType, 'block-device-mappings': blockDeviceMappings, 'apply-tags': tags, } = firewallConfig; const securityGroup = vpc.tryFindSecurityGroupByName(securityGroupName); if (!securityGroup) { console.warn(`Cannot find security group with name "${securityGroupName}" in VPC "${vpc.name}"`); return; } // Import role from a previous phase const instanceRoleArn = `arn:aws:iam::${accountStack.accountId}:role/${instanceRoleName}`; const instanceRole = iam.Role.fromRoleArn(accountStack, `FirewallRole${firewallName}`, instanceRoleArn, { mutable: true, }); // Import instance profile from a previous phase const instanceProfile = InstanceProfile.fromInstanceRoleName(accountStack, `FirewallInstanceProfile${firewallName}`, { instanceProfileName: createIamInstanceProfileName(instanceRoleName), }); const cluster = new FirewallCluster(accountStack, `Firewall${firewallName}`, { vpcCidrBlock: vpc.cidrBlock, additionalCidrBlocks: vpc.additionalCidrBlocks, imageId, instanceType, instanceRole, instanceProfile, configuration: { bucket: accountBucket, bucketRegion: accountBucket.region, templateBucket: centralBucket, templateConfigPath: configFile, }, blockDeviceMappings: blockDeviceMappings.map(deviceName => ({ deviceName, ebs: { encrypted: true, }, })), }); if (sleep) { cluster.node.addDependency(sleep); } // Make sure the instance can read the configuration accountBucket.grantRead(instanceRole); // We only need once firewall instance per availability zone const instancePerAz: { [az: string]: FirewallInstance } = {}; let licenseIndex: number = 0; for (const vpnConnection of firewallVpnConnections) { const az = vpnConnection.az; const subnetName = vpnConnection.subnetName; const subnet = vpc.tryFindSubnetByNameAndAvailabilityZone(subnetName, az); if (!subnet || !securityGroup) { console.warn(`Cannot find subnet with name "${subnetName}" in availability zone "${az}"`); continue; } let instance = instancePerAz[az]; let licensePath: string | undefined; let licenseBucket: s3.IBucket | undefined; if (!instance) { // Find the next available license in the firewall config license list if (licenseFiles && licenseIndex < licenseFiles.length) { licensePath = licenseFiles[licenseIndex]; licenseBucket = centralBucket; } // Create an instance for this AZ const instanceName = `${firewallName}_az${pascalCase(az)}`; instance = cluster.createInstance({ name: instanceName, hostname: instanceName, licensePath, licenseBucket, userData, }); instancePerAz[az] = instance; licenseIndex++; for (const [key, value] of Object.entries(tags || {})) { cdk.Tags.of(instance).add(key, value); } new CfnFirewallInstanceOutput(accountStack, `Fgt${firewallName}${pascalCase(az)}Output`, { id: instance.instanceId, name: firewallName, az, }); } const privateIp = findFirewallPrivateIp({ firewallConfig, subnetName: subnet.name, az: subnet.az }); const networkInterface = instance.addNetworkInterface({ name: vpnConnection.name, subnet, privateStaticIp: privateIp, securityGroup, eipAllocationId: vpnConnection.eipAllocationId, vpnTunnelOptions: vpnConnection.vpnTunnelOptions, additionalReplacements: replacements, }); const routeTables = vpcConfig['route-tables'] || []; for (const routeTable of routeTables) { const routeTableName: string = routeTable.name; const routes = routeTable.routes || []; for (const route of routes) { if ( route.target !== 'firewall' || route.name !== firewallName || route.az !== az || route.port !== vpnConnection.name ) { continue; } const routeTableId = vpc.tryFindRouteTableIdByName(routeTableName); if (!routeTableId) { console.warn(`Cannot find route table with name "${routeTableName}" in VPC ${vpc.name}`); continue; } new ec2.CfnRoute(accountStack, `${firewallName}${routeTableName}_eni_${vpnConnection.name}_${az}`, { routeTableId, destinationCidrBlock: route.destination as string, networkInterfaceId: networkInterface.ref, }); } } } for (const instance of Object.values(instancePerAz)) { const replacements: { [key: string]: string } = {}; Object.entries(instance.replacements || {}).forEach(([key, value]) => { replacements[key.replace(/[^-a-zA-Z0-9_.]+/gi, '')] = value; }); new CfnFirewallConfigReplacementsOutput(accountStack, `FirewallReplacementOutput${instance.instanceName}`, { instanceId: instance.instanceId, instanceName: instance.instanceName, name: firewallConfig.name, replacements, }); } return cluster; } export function additionalReplacements(configReplacements: c.ReplacementsConfig): { [key: string]: string } { const replacements: { [key: string]: string } = {}; for (const [key, value] of Object.entries(configReplacements)) { if (!c.ReplacementObject.is(value)) { if (StringType.is(value)) { replacements['${' + key.toUpperCase() + '}'] = value; } } else { for (const [needle, replacement] of Object.entries(value)) { if (StringType.is(replacement)) { replacements['${' + key.toUpperCase() + '_' + needle.toUpperCase() + '}'] = replacement; } } } } return replacements; }
the_stack
import { default as CallbackRegistryFactory, CallbackRegistry } from "callback-registry"; import { RequestContext, ServerMethodInfo, ServerSubscriptionInfo } from "../../server/types"; import ClientRepository from "../../client/repository"; import ServerRepository from "../../server/repository"; import { AddInterestMessage, PublishMessage, PostMessage, DropSubscriptionMessage, RemoveInterestMessage } from "./messages"; import { Glue42Core } from "../../../../glue"; import { Logger } from "../../../logger/logger"; const SUBSCRIPTION_REQUEST = "onSubscriptionRequest"; const SUBSCRIPTION_ADDED = "onSubscriptionAdded"; const SUBSCRIPTION_REMOVED = "onSubscriptionRemoved"; /** * Handles registering methods and sending data to clients */ export default class ServerStreaming { private ERR_URI_SUBSCRIPTION_FAILED = "com.tick42.agm.errors.subscription.failure"; private callbacks = CallbackRegistryFactory(); private nextStreamId = 0; constructor(private session: Glue42Core.Connection.GW3DomainSession, private repository: ClientRepository, private serverRepository: ServerRepository) { session.on("add-interest", (msg: AddInterestMessage) => { this.handleAddInterest(msg); }); session.on("remove-interest", (msg: RemoveInterestMessage) => { this.handleRemoveInterest(msg); }); } public acceptRequestOnBranch(requestContext: RequestContext, streamingMethod: ServerMethodInfo, branch: string) { if (typeof branch !== "string") { branch = ""; } if (typeof streamingMethod.protocolState.subscriptionsMap !== "object") { throw new TypeError("The streaming method is missing its subscriptions."); } if (!Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { throw new TypeError("The streaming method is missing its branches."); } const streamId = this.getStreamId(streamingMethod, branch); // Add a new subscription to the method const key = requestContext.msg.subscription_id; const subscription: ServerSubscriptionInfo = { id: key, arguments: requestContext.arguments, instance: requestContext.instance, branchKey: branch, streamId, subscribeMsg: requestContext.msg, }; streamingMethod.protocolState.subscriptionsMap[key] = subscription; // Inform the gw this.session.sendFireAndForget({ type: "accepted", subscription_id: key, stream_id: streamId, }); // Pass state above-protocol for user objects this.callbacks.execute(SUBSCRIPTION_ADDED, subscription, streamingMethod); } public rejectRequest(requestContext: RequestContext, streamingMethod: ServerMethodInfo, reason: string) { if (typeof reason !== "string") { reason = ""; } this.sendSubscriptionFailed( "Subscription rejected by user. " + reason, requestContext.msg.subscription_id, ); } public pushData(streamingMethod: ServerMethodInfo, data: object, branches: string | string[]) { if (typeof streamingMethod !== "object" || !Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { return; } // TODO validate data is a plain object if (typeof data !== "object") { throw new Error("Invalid arguments. Data must be an object."); } if (typeof branches === "string") { branches = [branches]; // user wants to push to single branch } else if (!Array.isArray(branches) || branches.length <= 0) { branches = []; } // get the StreamId's from the method's branch map const streamIdList = streamingMethod.protocolState.branchKeyToStreamIdMap .filter((br) => { if (!branches || branches.length === 0) { return true; } return branches.indexOf(br.key) >= 0; }).map((br) => { return br.streamId; }); // if (streamIdList.length === 0) { // throw new Error("0 branches exist with the supplied name/s !"); // } streamIdList.forEach((streamId) => { const publishMessage: PublishMessage = { type: "publish", stream_id: streamId, // sequence: null, // the streamingMethod might be used for this // snapshot: false, // ...and this data, }; this.session.sendFireAndForget(publishMessage); }); } public pushDataToSingle(method: ServerMethodInfo, subscription: ServerSubscriptionInfo, data: object) { // TODO validate data is a plain object if (typeof data !== "object") { throw new Error("Invalid arguments. Data must be an object."); } const postMessage: PostMessage = { type: "post", subscription_id: subscription.id, // sequence: null, // the streamingMethod might be used for this // snapshot: false, // ...and this data, }; this.session.sendFireAndForget(postMessage); } public closeSingleSubscription(streamingMethod: ServerMethodInfo, subscription: ServerSubscriptionInfo) { if (streamingMethod.protocolState.subscriptionsMap) { delete streamingMethod.protocolState.subscriptionsMap[subscription.id]; } const dropSubscriptionMessage: DropSubscriptionMessage = { type: "drop-subscription", subscription_id: subscription.id, reason: "Server dropping a single subscription", }; this.session.sendFireAndForget(dropSubscriptionMessage); const subscriber = subscription.instance; this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); } public closeMultipleSubscriptions(streamingMethod: ServerMethodInfo, branchKey?: string) { if (typeof streamingMethod !== "object" || typeof streamingMethod.protocolState.subscriptionsMap !== "object") { return; } if (!streamingMethod.protocolState.subscriptionsMap) { return; } const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; let subscriptionsToClose = Object.keys(subscriptionsMap) .map((key) => { return subscriptionsMap[key]; }); if (typeof branchKey === "string") { subscriptionsToClose = subscriptionsToClose.filter((sub) => { return sub.branchKey === branchKey; }); } subscriptionsToClose.forEach((subscription) => { delete subscriptionsMap[subscription.id]; const drop: DropSubscriptionMessage = { type: "drop-subscription", subscription_id: subscription.id, reason: "Server dropping all subscriptions on stream_id: " + subscription.streamId, }; this.session.sendFireAndForget(drop); }); } public getSubscriptionList(streamingMethod: ServerMethodInfo, branchKey?: string): ServerSubscriptionInfo[] { if (typeof streamingMethod !== "object") { return []; } let subscriptions = []; if (!streamingMethod.protocolState.subscriptionsMap) { return []; } const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; const allSubscriptions = Object.keys(subscriptionsMap) .map((key) => { return subscriptionsMap[key]; }); if (typeof branchKey !== "string") { subscriptions = allSubscriptions; } else { subscriptions = allSubscriptions.filter((sub) => { return sub.branchKey === branchKey; }); } return subscriptions; } public getBranchList(streamingMethod: ServerMethodInfo): string[] { if (typeof streamingMethod !== "object") { return []; } if (!streamingMethod.protocolState.subscriptionsMap) { return []; } const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; const allSubscriptions = Object.keys(subscriptionsMap) .map((key) => { return subscriptionsMap[key]; }); const result: string[] = []; allSubscriptions.forEach((sub) => { let branch = ""; if (typeof sub === "object" && typeof sub.branchKey === "string") { branch = sub.branchKey; } if (result.indexOf(branch) === -1) { result.push(branch); } }); return result; } public onSubAdded(callback: (subscription: ServerSubscriptionInfo, repoMethod: ServerMethodInfo) => void) { this.onSubscriptionLifetimeEvent(SUBSCRIPTION_ADDED, callback); } public onSubRequest(callback: (requestContext: RequestContext, repoMethod: ServerMethodInfo) => void) { this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REQUEST, callback); } public onSubRemoved(callback: (subscriber: ServerSubscriptionInfo, repoMethod: ServerMethodInfo) => void) { this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REMOVED, callback); } private handleRemoveInterest(msg: RemoveInterestMessage) { const streamingMethod = this.serverRepository.getById(msg.method_id); if (typeof msg.subscription_id !== "string" || typeof streamingMethod !== "object") { return; } if (!streamingMethod.protocolState.subscriptionsMap) { return; } if (typeof streamingMethod.protocolState.subscriptionsMap[msg.subscription_id] !== "object") { return; } const subscription = streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; delete streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); } private onSubscriptionLifetimeEvent(eventName: string, handlerFunc: any) { this.callbacks.add(eventName, handlerFunc); } private getNextStreamId(): string { return this.nextStreamId++ + ""; } /** * Processes a subscription request */ private handleAddInterest(msg: AddInterestMessage) { const caller = this.repository.getServerById(msg.caller_id); const instance = caller.instance; // call subscriptionRequestHandler const requestContext: RequestContext = { msg, arguments: msg.arguments_kv || {}, instance, }; const streamingMethod = this.serverRepository.getById(msg.method_id); if (streamingMethod === undefined) { const errorMsg = "No method with id " + msg.method_id + " on this server."; this.sendSubscriptionFailed(errorMsg, msg.subscription_id); return; } if (streamingMethod.protocolState.subscriptionsMap && streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]) { this.sendSubscriptionFailed("A subscription with id " + msg.subscription_id + " already exists.", msg.subscription_id, ); return; } this.callbacks.execute(SUBSCRIPTION_REQUEST, requestContext, streamingMethod); } private sendSubscriptionFailed(reason: string, subscriptionId: string) { const errorMessage = { type: "error", reason_uri: this.ERR_URI_SUBSCRIPTION_FAILED, reason, request_id: subscriptionId, // this overrides connection wrapper }; this.session.sendFireAndForget(errorMessage); } private getStreamId(streamingMethod: ServerMethodInfo, branchKey: string) { if (typeof branchKey !== "string") { branchKey = ""; } if (!streamingMethod.protocolState.branchKeyToStreamIdMap) { throw new Error(`streaming ${streamingMethod.definition.name} method without protocol state`); } const needleBranch = streamingMethod.protocolState.branchKeyToStreamIdMap.filter((branch) => { return branch.key === branchKey; })[0]; let streamId = (needleBranch ? needleBranch.streamId : undefined); if (typeof streamId !== "string" || streamId === "") { streamId = this.getNextStreamId(); streamingMethod.protocolState.branchKeyToStreamIdMap.push({ key: branchKey, streamId }); } return streamId; } }
the_stack
import {ByteOrder} from "./ByteOrder"; import {Strings} from "../"; // forward import /** * 32-bit [MurmurHash](https://en.wikipedia.org/wiki/MurmurHash) algorithm, * version 3. * @public */ export const Murmur3 = (function () { const Murmur3 = {} as { /** * Mixes a new hash `value` into the accumulated hash `code`, * and returns the accumulated hash value. */ mix(code: number, value: number): number; /** * Mixes each consecutive 4-byte word of `array` into `code`, * and returns the accumulated hash value. */ mixUint8Array(code: number, array: Uint8Array): number; /** @internal */ mixUint8ArrayBE(code: number, array: Uint8Array): number; /** @internal */ mixUInt8ArrayLE(code: number, array: Uint8Array): number; /** * Mixes each consecutive 4-byte word of the UTF-8 encoding of `string` * into `code`, and returns the accumulated hash value. */ mixString(code: number, string: string): number; /** @internal */ mixStringBE(code: number, string: string): number; /** @internal */ mixStringLE(code: number, string: string): number; /** * Finalizes a hash `code`. */ mash(code: number): number; /** @internal */ rotl(value: number, distance: number): number; }; Murmur3.mix = function (code: number, value: number): number { value = ((value & 0xffff) * 0xcc9e2d51) + (((value >>> 16) * 0xcc9e2d51 & 0xffff) << 16) & 0xffffffff; value = Murmur3.rotl(value, 15); value = ((value & 0xffff) * 0x1b873593) + (((value >>> 16) * 0x1b873593 & 0xffff) << 16) & 0xffffffff; code ^= value; code = Murmur3.rotl(code, 13); code = ((code & 0xffff) * 5) + (((code >>> 16) * 5 & 0xffff) << 16) & 0xffffffff; code = ((code & 0xffff) + 0x6b64) + (((code >>> 16) + 0xe654 & 0xffff) << 16); return code; }; Murmur3.mixUint8Array = function (code: number, array: Uint8Array): number { if (ByteOrder.NativeOrder === ByteOrder.BigEndian) { return Murmur3.mixUint8ArrayBE(code, array); } else if (ByteOrder.NativeOrder === ByteOrder.LittleEndian) { return Murmur3.mixUInt8ArrayLE(code, array); } else { throw new Error(); } }; Murmur3.mixUint8ArrayBE = function (code: number, array: Uint8Array): number { let offset = 0; const limit = array.length; while (offset + 3 < limit) { const word = (array[offset ]! & 0xff) << 24 | (array[offset + 1]! & 0xff) << 16 | (array[offset + 2]! & 0xff) << 8 | array[offset + 3]! & 0xff; code = Murmur3.mix(code, word); offset += 4; } if (offset < limit) { let word = (array[offset]! & 0xff) << 24; if (offset + 1 < limit) { word |= (array[offset + 1]! & 0xff) << 16; if (offset + 2 < limit) { word |= (array[offset + 2]! & 0xff) << 8; //assert offset + 3 === limit; } } word = ((word & 0xffff) * 0xcc9e2d51) + (((word >>> 16) * 0xcc9e2d51 & 0xffff) << 16) & 0xffffffff; word = Murmur3.rotl(word, 15); word = ((word & 0xffff) * 0x1b873593) + (((word >>> 16) * 0x1b873593 & 0xffff) << 16) & 0xffffffff; code ^= word; } return code ^ limit; }; Murmur3.mixUInt8ArrayLE = function (code: number, array: Uint8Array): number { let offset = 0; const limit = array.length; while (offset + 3 < limit) { const word = array[offset ]! & 0xff | (array[offset + 1]! & 0xff) << 8 | (array[offset + 2]! & 0xff) << 16 | (array[offset + 3]! & 0xff) << 24; code = Murmur3.mix(code, word); offset += 4; } if (offset < limit) { let word = array[offset]! & 0xff; if (offset + 1 < limit) { word |= (array[offset + 1]! & 0xff) << 8; if (offset + 2 < limit) { word |= (array[offset + 2]! & 0xff) << 16; //assert offset + 3 === limit; } } word = ((word & 0xffff) * 0xcc9e2d51) + (((word >>> 16) * 0xcc9e2d51 & 0xffff) << 16) & 0xffffffff; word = Murmur3.rotl(word, 15); word = ((word & 0xffff) * 0x1b873593) + (((word >>> 16) * 0x1b873593 & 0xffff) << 16) & 0xffffffff; code ^= word; } return code ^ limit; }; Murmur3.mixString = function (code: number, string: string): number { if (ByteOrder.NativeOrder === ByteOrder.BigEndian) { return Murmur3.mixStringBE(code, string); } else if (ByteOrder.NativeOrder === ByteOrder.LittleEndian) { return Murmur3.mixStringLE(code, string); } else { throw new Error(); } }; Murmur3.mixStringBE = function (code: number, string: string): number { let word = 0; let k = 32; let i = 0; const n = string.length; let utf8Length = 0; while (i < n) { let c = string.codePointAt(i); if (c === void 0) { c = string.charCodeAt(i); } if (c >= 0 && c <= 0x7f) { // U+0000..U+007F k -= 8; word |= c << k; if (k === 0) { code = Murmur3.mix(code, word); word = 0; k = 32; } utf8Length += 1; } else if (c >= 0x80 && c <= 0x7ff) { // U+0080..U+07FF k -= 8; word |= (0xc0 | (c >>> 6)) << k; if (k === 0) { code = Murmur3.mix(code, word); word = 0; k = 32; } k -= 8; word |= (0x80 | (c & 0x3f)) << k; if (k === 0) { code = Murmur3.mix(code, word); word = 0; k = 32; } utf8Length += 2; } else if (c >= 0x0800 && c <= 0xffff || // U+0800..U+D7FF c >= 0xe000 && c <= 0xffff) { // U+E000..U+FFFF k -= 8; word |= (0xe0 | (c >>> 12)) << k; if (k === 0) { code = Murmur3.mix(code, word); word = 0; k = 32; } k -= 8; word |= (0x80 | ((c >>> 6) & 0x3f)) << k; if (k === 0) { code = Murmur3.mix(code, word); word = 0; k = 32; } k -= 8; word |= (0x80 | (c & 0x3f)) << k; if (k === 0) { code = Murmur3.mix(code, word); word = 0; k = 32; } utf8Length += 3; } else if (c >= 0x10000 && c <= 0x10ffff) { // U+10000..U+10FFFF k -= 8; word |= (0xf0 | (c >>> 18)) << k; if (k === 0) { code = Murmur3.mix(code, word); word = 0; k = 32; } k -= 8; word |= (0x80 | ((c >>> 12) & 0x3f)) << k; if (k === 0) { code = Murmur3.mix(code, word); word = 0; k = 32; } k -= 8; word |= (0x80 | ((c >>> 6) & 0x3f)) << k; if (k === 0) { code = Murmur3.mix(code, word); word = 0; k = 32; } k -= 8; word |= (0x80 | (c & 0x3f)) << k; if (k === 0) { code = Murmur3.mix(code, word); word = 0; k = 32; } utf8Length += 4; } else { // surrogate or invalid code point k -= 8; word |= 0xef << k; if (k === 0) { code = Murmur3.mix(code, word); word = 0; k = 32; } k -= 8; word |= 0xbf << k; if (k === 0) { code = Murmur3.mix(code, word); word = 0; k = 32; } k -= 8; word |= 0xbd << k; if (k === 0) { code = Murmur3.mix(code, word); word = 0; k = 32; } utf8Length += 3; } i = Strings.offsetByCodePoints(string, i, 1); } if (k !== 32) { word = ((word & 0xffff) * 0xcc9e2d51) + (((word >>> 16) * 0xcc9e2d51 & 0xffff) << 16) & 0xffffffff; word = Murmur3.rotl(word, 15); word = ((word & 0xffff) * 0x1b873593) + (((word >>> 16) * 0x1b873593 & 0xffff) << 16) & 0xffffffff; code ^= word; } return code ^ utf8Length; }; Murmur3.mixStringLE = function (code: number, string: string): number { let word = 0; let k = 0; let i = 0; const n = string.length; let utf8Length = 0; while (i < n) { let c = string.codePointAt(i); if (c === void 0) { c = string.charCodeAt(i); } if (c >= 0 && c <= 0x7f) { // U+0000..U+007F word |= c << k; k += 8; if (k === 32) { code = Murmur3.mix(code, word); word = 0; k = 0; } utf8Length += 1; } else if (c >= 0x80 && c <= 0x7ff) { // U+0080..U+07FF word |= (0xc0 | (c >>> 6)) << k; k += 8; if (k === 32) { code = Murmur3.mix(code, word); word = 0; k = 0; } word |= (0x80 | (c & 0x3f)) << k; k += 8; if (k === 32) { code = Murmur3.mix(code, word); word = 0; k = 0; } utf8Length += 2; } else if (c >= 0x0800 && c <= 0xffff || // U+0800..U+D7FF c >= 0xe000 && c <= 0xffff) { // U+E000..U+FFFF word |= (0xe0 | (c >>> 12)) << k; k += 8; if (k === 32) { code = Murmur3.mix(code, word); word = 0; k = 0; } word |= (0x80 | ((c >>> 6) & 0x3f)) << k; k += 8; if (k === 32) { code = Murmur3.mix(code, word); word = 0; k = 0; } word |= (0x80 | (c & 0x3f)) << k; k += 8; if (k === 32) { code = Murmur3.mix(code, word); word = 0; k = 0; } utf8Length += 3; } else if (c >= 0x10000 && c <= 0x10ffff) { // U+10000..U+10FFFF word |= (0xf0 | (c >>> 18)) << k; k += 8; if (k === 32) { code = Murmur3.mix(code, word); word = 0; k = 0; } word |= (0x80 | ((c >>> 12) & 0x3f)) << k; k += 8; if (k === 32) { code = Murmur3.mix(code, word); word = 0; k = 0; } word |= (0x80 | ((c >>> 6) & 0x3f)) << k; k += 8; if (k === 32) { code = Murmur3.mix(code, word); word = 0; k = 0; } word |= (0x80 | (c & 0x3f)) << k; k += 8; if (k === 32) { code = Murmur3.mix(code, word); word = 0; k = 0; } utf8Length += 4; } else { // surrogate or invalid code point word |= 0xef << k; k += 8; if (k === 32) { code = Murmur3.mix(code, word); word = 0; k = 0; } word |= 0xbf << k; k += 8; if (k === 32) { code = Murmur3.mix(code, word); word = 0; k = 0; } word |= 0xbd << k; k += 8; if (k === 32) { code = Murmur3.mix(code, word); word = 0; k = 0; } utf8Length += 3; } i = Strings.offsetByCodePoints(string, i, 1); } if (k !== 32) { word = ((word & 0xffff) * 0xcc9e2d51) + (((word >>> 16) * 0xcc9e2d51 & 0xffff) << 16) & 0xffffffff; word = Murmur3.rotl(word, 15); word = ((word & 0xffff) * 0x1b873593) + (((word >>> 16) * 0x1b873593 & 0xffff) << 16) & 0xffffffff; code ^= word; } return code ^ utf8Length; }; Murmur3.mash = function (code: number): number { code ^= code >>> 16; code = ((code & 0xffff) * 0x85ebca6b) + (((code >>> 16) * 0x85ebca6b & 0xffff) << 16) & 0xffffffff; code ^= code >>> 13; code = ((code & 0xffff) * 0xc2b2ae35) + (((code >>> 16) * 0xc2b2ae35 & 0xffff) << 16) & 0xffffffff; code ^= code >>> 16; return code >>> 0; }; Murmur3.rotl = function (value: number, distance: number): number { return (value << distance) | (value >>> (32 - distance)); }; return Murmur3; })();
the_stack
import * as openapiToolsCommon from "@azure-tools/openapi-tools-common"; import * as amd from "@azure/openapi-markdown"; import * as msRest from "ms-rest"; import * as Sway from "yasway"; import { ResponseWrapper } from "../models/responseWrapper"; import { CommonError } from "../util/commonError"; import * as C from "../util/constants"; import * as jsonUtils from "../util/jsonUtils"; import { log } from "../util/logging"; import { ModelValidationError } from "../util/modelValidationError"; import { processErrors, setPositionAndUrl } from "../util/processErrors"; import { MultipleScenarios, Scenario } from "../util/responseReducer"; import { OperationResultType } from "../util/scenarioReducer"; import * as utils from "../util/utils"; import { getTitle } from "./specTransformer"; import { ExampleResponse, RequestValidation, SpecValidationResult, SpecValidator, ValidationResult, ValidationResultScenarios, } from "./specValidator"; const HttpRequest = msRest.WebResource; export class ModelValidator extends SpecValidator<SpecValidationResult> { private exampleJsonMap = new Map<string, Sway.SwaggerObject>(); /* * Validates the given operationIds or all the operations in the spec. * * @param {string} [operationIds] - A comma separated string specifying the operations to be * validated. * If not specified then the entire spec is validated. */ public async validateOperations(operationIds?: string): Promise<void> { if (!this.swaggerApi) { throw new Error( // tslint:disable-next-line: max-line-length `Please call "specValidator.initialize()" before calling this method, so that swaggerApi is populated.` ); } if ( operationIds !== null && operationIds !== undefined && typeof operationIds.valueOf() !== "string" ) { throw new Error(`operationIds parameter must be of type 'string'.`); } let operations = this.swaggerApi.getOperations(); if (operationIds) { const operationIdsObj: openapiToolsCommon.MutableStringMap<unknown> = {}; operationIds .trim() .split(",") .forEach((item) => (operationIdsObj[item.trim()] = 1)); const operationsToValidate = operations.filter((item) => Boolean(operationIdsObj[item.operationId]) ); if (operationsToValidate.length) { operations = operationsToValidate; } } for (const operation of operations) { this.specValidationResult.operations[operation.operationId] = { "x-ms-examples": {}, "example-in-spec": {}, }; await this.validateOperation(operation); const operationResult = this.specValidationResult.operations[operation.operationId]; if (operationResult === undefined) { throw new Error("operationResult is undefined"); } const example = operationResult[C.exampleInSpec]; if (example === undefined) { throw new Error("example is undefined"); } if (openapiToolsCommon.isMapEmpty(openapiToolsCommon.toStringMap(example))) { delete operationResult[C.exampleInSpec]; } } } private async loadExamplesForOperation(exampleFilePath: string): Promise<void> { try { if (!this.exampleJsonMap.has(exampleFilePath)) { const exampleJson = await jsonUtils.parseJson( undefined, exampleFilePath, openapiToolsCommon.defaultErrorReport ); this.exampleJsonMap.set(exampleFilePath, exampleJson); } } catch (error) { throw new Error(`Failed to load a reference example file ${exampleFilePath}. (${error})`); } } private initializeExampleResult( operationId: string, exampleType: string, scenarioName: string | undefined ): void { const initialResult = { isValid: true, request: { isValid: true, }, responses: {}, }; let operationResult = this.specValidationResult.operations[operationId]; if (!operationResult) { operationResult = {}; } if (exampleType === C.exampleInSpec) { const example = operationResult[exampleType]; if ( !example || (example && openapiToolsCommon.isMapEmpty(openapiToolsCommon.toStringMap(example))) ) { operationResult[exampleType] = initialResult; } } if (exampleType === C.xmsExamples) { const example = operationResult[exampleType]; if (example === undefined) { throw new Error("example is undefined"); } if (!example.scenarios) { example.scenarios = {}; } if (scenarioName === undefined) { throw new Error("scenarioName === undefined"); } if (!example.scenarios[scenarioName]) { example.scenarios[scenarioName] = initialResult; } } this.specValidationResult.operations[operationId] = operationResult; } private getExample( operationId: string, exampleType: OperationResultType, scenarioName: string | undefined ): { operationResult: Scenario; // OperationExampleResult part: string; } { const operation = this.specValidationResult.operations[operationId]; if (operation === undefined) { throw new Error("operation is undefined"); } const example = operation[exampleType]; if (example === undefined) { throw new Error("example is undefined"); } if (exampleType === C.xmsExamples) { const scenarios = (example as MultipleScenarios).scenarios; if (scenarios === undefined) { throw new Error("scenarios is undefined"); } const scenario = scenarios[scenarioName as string]; if (scenario === undefined) { throw new Error("scenario is undefined"); } return { operationResult: scenario, part: `for x-ms-example "${scenarioName}" in operation "${operationId}"`, }; } else { return { operationResult: example as Scenario, part: `for example in spec for operation "${operationId}"`, }; } } private constructRequestResultWrapper( operationId: string, requestValidationErrors: ModelValidationError[], requestValidationWarnings: unknown[] | undefined, exampleType: OperationResultType, scenarioName?: string, exampleFilePath?: string ): void { this.initializeExampleResult(operationId, exampleType, scenarioName); const { operationResult, part } = this.getExample(operationId, exampleType, scenarioName); const subMsg = `validating the request ${part}`; const infoMsg = `Request parameters ${part} is valid.`; let errorMsg; let warnMsg; if (requestValidationErrors && requestValidationErrors.length) { errorMsg = `Found errors in ${subMsg}.`; this.constructRequestResult( operationResult, false, errorMsg, requestValidationErrors, null, exampleFilePath ); } else { this.constructRequestResult(operationResult, true, infoMsg); } if (requestValidationWarnings && requestValidationWarnings.length) { warnMsg = `Found warnings in ${subMsg}.`; this.constructRequestResult(operationResult, true, warnMsg, null, requestValidationWarnings); } } private constructResponseResultWrapper( operationId: string, responseStatusCode: string, responseValidationErrors: ModelValidationError[], responseValidationWarnings: unknown[] | undefined, exampleType: OperationResultType, scenarioName?: string ): void { this.initializeExampleResult(operationId, exampleType, scenarioName); const { operationResult, part } = this.getExample(operationId, exampleType, scenarioName); const subMsg = `validating the response with statusCode "${responseStatusCode}" ${part}`; const infoMsg = `Response with statusCode "${responseStatusCode}" ${part} is valid.`; let errorMsg; let warnMsg; if (responseValidationErrors && responseValidationErrors.length) { errorMsg = `Found errors in ${subMsg}.`; this.constructResponseResult( operationResult, responseStatusCode, false, errorMsg, responseValidationErrors ); } else { this.constructResponseResult(operationResult, responseStatusCode, true, infoMsg); } if (responseValidationWarnings && responseValidationWarnings.length) { warnMsg = `Found warnings in ${subMsg}.`; this.constructResponseResult( operationResult, responseStatusCode, true, warnMsg, null, responseValidationWarnings ); } } /* * Constructs the validation result for an operation. * * @param {object} operation - The operation object. * * @param {object} result - The validation result that needs to be added to the uber * validationResult object for the entire spec. * * @param {string} exampleType A string specifying the type of example. "x-ms-example", * "example-in-spec". * * @return {object} xmsExample - The xmsExample object. */ private constructOperationResult( operation: Sway.Operation, result: ValidationResult, exampleType: OperationResultType, exampleFileMap?: Map<string, string> ): void { const operationId = operation.operationId; if (result.exampleNotFound) { const operationResult = this.specValidationResult.operations[operationId]; if (operationResult === undefined) { throw new Error("example is undefined"); } const example = operationResult[exampleType]; if (example === undefined) { throw new Error("example is undefined"); } example.error = result.exampleNotFound; // log.error(result.exampleNotFound) } if (exampleType === C.xmsExamples) { if (result.scenarios) { for (const [scenario, v] of openapiToolsCommon.mapEntries(result.scenarios)) { const requestValidation = v.requestValidation; if (requestValidation === undefined) { throw new Error("requestValidation is undefined"); } const validationResult = requestValidation.validationResult; if (validationResult === undefined) { throw new Error("validationResult is undefined"); } // requestValidation const requestValidationErrors = validationResult.errors; const requestValidationWarnings = validationResult.warnings; this.constructRequestResultWrapper( operationId, requestValidationErrors, requestValidationWarnings, exampleType, scenario, exampleFileMap !== undefined ? exampleFileMap.get(scenario) : undefined ); // responseValidation const responseValidation = result.scenarios[scenario].responseValidation; if (responseValidation === undefined) { throw new Error("responseValidation is undefined"); } for (const [responseStatusCode, value] of openapiToolsCommon.mapEntries( responseValidation )) { this.constructResponseResultWrapper( operationId, responseStatusCode, value.errors, value.warnings, exampleType, scenario ); } } } } else if (exampleType === C.exampleInSpec) { if ( result.requestValidation && openapiToolsCommon.toArray( openapiToolsCommon.keys(result.requestValidation as openapiToolsCommon.StringMap<unknown>) ).length ) { // requestValidation const validationResult = result.requestValidation.validationResult; if (validationResult === undefined) { throw new Error("validationResult is undefined"); } const requestValidationErrors = validationResult.errors; const requestValidationWarnings = validationResult.warnings; this.constructRequestResultWrapper( operationId, requestValidationErrors, requestValidationWarnings, exampleType ); } if (result.responseValidation && !openapiToolsCommon.isMapEmpty(result.responseValidation)) { // responseValidation for (const [responseStatusCode, value] of openapiToolsCommon.mapEntries( result.responseValidation )) { this.constructResponseResultWrapper( operationId, responseStatusCode, value.errors, value.warnings, exampleType ); } } } } /* * Validates the x-ms-examples object for an operation if specified in the swagger spec. * * @param {object} operation - The operation object. */ private async validateXmsExamples(operation: Sway.Operation): Promise<void> { if (operation === null || operation === undefined || typeof operation !== "object") { throw new Error("operation cannot be null or undefined and must be of type 'object'."); } const xmsExamples = operation[C.xmsExamples]; const resultScenarios: ValidationResultScenarios = {}; const result: ValidationResult = { scenarios: resultScenarios, }; const exampleFileMap = new Map<string, string>(); if (xmsExamples) { for (const [scenario, xmsExampleFunc] of openapiToolsCommon.mapEntries<any>(xmsExamples)) { const xmsExample = xmsExampleFunc(); resultScenarios[scenario] = { requestValidation: this.validateRequest(operation, xmsExample.parameters), responseValidation: this.validateXmsExampleResponses(operation, xmsExample.responses), }; exampleFileMap.set(scenario, xmsExample.docPath); await this.loadExamplesForOperation(xmsExample.docPath); } result.scenarios = resultScenarios; } else { const msg = `x-ms-example not found in ${operation.operationId}.`; result.exampleNotFound = this.constructErrorObject({ code: C.ErrorCodes.XmsExampleNotFoundError, message: msg, skipValidityStatusUpdate: true, source: operation.definition, }); } this.constructOperationResult(operation, result, C.xmsExamples, exampleFileMap); } /* * Validates the given operation. * * @param {object} operation - The operation object. */ private async validateOperation(operation: Sway.Operation): Promise<void> { await this.validateXmsExamples(operation); this.validateExample(operation); } /* * Validates the example provided in the spec for the given operation if specified in the spec. * * @param {object} operation - The operation object. */ private validateExample(operation: Sway.Operation): void { if (operation === null || operation === undefined || typeof operation !== "object") { throw new Error("operation cannot be null or undefined and must be of type 'object'."); } const result: ValidationResult = { requestValidation: this.validateExampleRequest(operation), responseValidation: this.validateExampleResponses(operation) as any, }; this.constructOperationResult(operation, result, C.exampleInSpec); } /* * Validates the example (request) for an operation if specified in the swagger spec. * * @param {object} operation - The operation object. * * @return {object} result - The validation result. */ private validateExampleRequest(operation: Sway.Operation): RequestValidation { if (operation === null || operation === undefined || typeof operation !== "object") { throw new Error("operation cannot be null or undefined and must be of type 'object'."); } const parameters = operation.getParameters(); // as per swagger specification // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#fixed-fields-13 // example can only be provided in a schema and schema can only be provided for a body // parameter. Hence, if the body parameter schema has an example, then we will populate sample // values for other parameters and create a request object. // This request object will be used to validate the body parameter example. Otherwise, we will // skip it. const bodyParam = parameters.find((item) => item.in === "body"); let result: RequestValidation = {}; if (bodyParam && bodyParam.schema && bodyParam.schema.example) { const exampleParameterValues: openapiToolsCommon.MutableStringMap< openapiToolsCommon.StringMap<unknown> > = {}; for (const parameter of parameters) { log.debug( `Getting sample value for parameter "${parameter.name}" in operation ` + `"${operation.operationId}".` ); // need to figure out how to register custom format validators. Till then deleting the // format uuid. if (parameter.format && parameter.format === "uuid") { delete parameter.format; delete parameter.schema.format; } exampleParameterValues[parameter.name] = parameter.getSample() as any; } exampleParameterValues[bodyParam.name] = bodyParam.schema.example; result = this.validateRequest(operation, exampleParameterValues); } return result; } /* * Validates the example responses for a given operation. * * @param {object} operation - The operation object. * * @return {object} result - The validation result. */ private validateExampleResponses( operation: Sway.Operation ): openapiToolsCommon.StringMap<Sway.ValidationResults> { if (operation === null || operation === undefined || typeof operation !== "object") { throw new Error("operation cannot be null or undefined and must be of type 'object'."); } const result: openapiToolsCommon.MutableStringMap<Sway.ValidationResults> = {}; const responses = operation.getResponses(); for (const response of responses) { if (response.examples) { for (const mimeType of Object.keys(response.examples)) { const exampleResponseBody = response.examples[mimeType]; const exampleResponseHeaders = { "content-type": mimeType }; const exampleResponse = new ResponseWrapper( response.statusCode, exampleResponseBody, exampleResponseHeaders ); const validationResult = this.validateResponse(operation, exampleResponse); result[response.statusCode] = validationResult; } } } return result; } /* * Validates the response for an operation. * * @param {object} operationOrResponse - The operation or the response object. * * @param {object} responseWrapper - The example responseWrapper. * * @return {object} result - The validation result. */ private validateResponse(operationOrResponse: Sway.Operation, responseWrapper: unknown) { if ( operationOrResponse === null || operationOrResponse === undefined || typeof operationOrResponse !== "object" ) { throw new Error( "operationOrResponse cannot be null or undefined and must be of type 'object'." ); } if ( responseWrapper === null || responseWrapper === undefined || typeof responseWrapper !== "object" ) { throw new Error("responseWrapper cannot be null or undefined and must be of type 'object'."); } // this.sampleResponse = responseWrapper // TODO: update responseWrapper return operationOrResponse.validateResponse(responseWrapper as Sway.LiveResponse); } /* * Validates the responses given in x-ms-examples object for an operation. * * @param {object} operation - The operation object. * * @param {object} exampleResponseValue - The example response value. * * @return {object} result - The validation result. */ private validateXmsExampleResponses( operation: Sway.Operation, exampleResponseValue: { [name: string]: ExampleResponse } ) { const result: openapiToolsCommon.MutableStringMap<Sway.ValidationResults> = {}; if (operation === null || operation === undefined || typeof operation !== "object") { throw new Error("operation cannot be null or undefined and must be of type 'object'."); } if ( exampleResponseValue === null || exampleResponseValue === undefined || typeof exampleResponseValue !== "object" ) { throw new Error("operation cannot be null or undefined and must be of type 'object'."); } const responsesInSwagger: openapiToolsCommon.MutableStringMap<unknown> = {}; operation.getResponses().forEach((response) => { responsesInSwagger[response.statusCode] = response.statusCode; }); for (const exampleResponseStatusCode of openapiToolsCommon.keys(exampleResponseValue)) { const response = operation.getResponse(exampleResponseStatusCode); if (responsesInSwagger[exampleResponseStatusCode]) { delete responsesInSwagger[exampleResponseStatusCode]; } const validationResults: Sway.ValidationResults = { errors: [], warnings: [], }; result[exampleResponseStatusCode] = validationResults; // have to ensure how to map negative status codes to default. There have been several issues // filed in the Autorest repo, w.r.t how // default is handled. While solving that issue, we may come up with some extension. Once that // is finalized, we should code accordingly over here. if (!response) { const msg = `Response statusCode "${exampleResponseStatusCode}" for operation ` + `"${operation.operationId}" is provided in exampleResponseValue, ` + `however it is not present in the swagger spec.`; const e = this.constructErrorObject<Sway.ValidationEntry>({ code: C.ErrorCodes.ResponseStatusCodeNotInSpec, message: msg, source: operation.definition, }); validationResults.errors.push(e); log.error(e as any); continue; } const exampleResponseHeaders = exampleResponseValue[exampleResponseStatusCode].headers || {}; const exampleResponseBody = exampleResponseValue[exampleResponseStatusCode].body; // Fail when example provides the response body but the swagger spec doesn't define the schema for the response. if (exampleResponseBody !== undefined && !response.schema) { const msg = `Response statusCode "${exampleResponseStatusCode}" for operation ` + `"${operation.operationId}" has response body provided in the example, ` + `however the response does not have a "schema" defined in the swagger spec.`; const e = this.constructErrorObject<Sway.ValidationEntry>({ code: C.ErrorCodes.ResponseSchemaNotInSpec, message: msg, source: operation.definition, }); validationResults.errors.push(e); log.error(e as any); continue; } else if (exampleResponseBody === undefined && response.schema) { // Fail when example doesn't provide the response body but the swagger spec define the schema for the response. const msg = `Response statusCode "${exampleResponseStatusCode}" for operation ` + `"${operation.operationId}" has no response body provided in the example, ` + `however the response does have a "schema" defined in the swagger spec.`; const e = this.constructErrorObject<Sway.ValidationEntry>({ code: C.ErrorCodes.ResponseBodyNotInExample, message: msg, source: operation.definition, }); validationResults.errors.push(e); log.error(e as any); continue; } // ensure content-type header is present if (!(exampleResponseHeaders["content-type"] || exampleResponseHeaders["Content-Type"])) { exampleResponseHeaders["content-type"] = utils.getJsonContentType(operation.produces); } const exampleResponse = new ResponseWrapper( exampleResponseStatusCode, exampleResponseBody, exampleResponseHeaders ); const validationResult = this.validateResponse(operation, exampleResponse); result[exampleResponseStatusCode] = validationResult; } const responseWithoutXmsExamples = openapiToolsCommon.toArray( openapiToolsCommon.filter( openapiToolsCommon.keys(responsesInSwagger), (statusCode) => statusCode !== "default" ) ); if (responseWithoutXmsExamples && responseWithoutXmsExamples.length) { const msg = `Following response status codes "${responseWithoutXmsExamples.toString()}" for ` + `operation "${operation.operationId}" were present in the swagger spec, ` + `however they were not present in x-ms-examples. Please provide them.`; const e = this.constructErrorObject<Sway.ValidationEntry>({ code: C.ErrorCodes.ResponseStatusCodeNotInExample, message: msg, source: operation.definition, }); setPositionAndUrl(e, getTitle(operation.definition)); log.error(e as any); responseWithoutXmsExamples.forEach((statusCode) => (result[statusCode] = { errors: [e] })); } return result; } /* * Validates the request for an operation. * * @param {object} operation - The operation object. * * @param {object} exampleParameterValues - The example parameter values. * * @return {object} result - The validation result. */ private validateRequest( operation: Sway.Operation, exampleParameterValues: openapiToolsCommon.StringMap<any> ): RequestValidation { if (operation === null || operation === undefined || typeof operation !== "object") { throw new Error("operation cannot be null or undefined and must be of type 'object'."); } if ( exampleParameterValues === null || exampleParameterValues === undefined || typeof exampleParameterValues !== "object" ) { throw new Error( `In operation "${operation.operationId}", exampleParameterValues cannot be null or ` + `undefined and must be of type "object" (A dictionary of key-value pairs of ` + `parameter-names and their values).` ); } const parameters = operation.getParameters(); const result: RequestValidation = { request: null, validationResult: { errors: [], warnings: [] }, }; let foundIssues = false; const options: { baseUrl?: string; [name: string]: any; } = { headers: {} }; let formDataFiles: openapiToolsCommon.MutableStringMap<unknown> | null = null; const pathObject = operation.pathObject; const parameterizedHost = pathObject.api[C.xmsParameterizedHost]; const useSchemePrefix = parameterizedHost ? (parameterizedHost as any).useSchemePrefix === undefined ? true : (parameterizedHost as any).useSchemePrefix : null; const hostTemplate = parameterizedHost && parameterizedHost.hostTemplate ? parameterizedHost.hostTemplate : null; if ( operation.pathObject && operation.pathObject.api && (operation.pathObject.api.host || hostTemplate) ) { let scheme = "https"; let basePath = ""; let host = ""; host = operation.pathObject.api.host || hostTemplate; if (host.endsWith("/")) { host = host.slice(0, host.length - 1); } if ( operation.pathObject.api.schemes && !operation.pathObject.api.schemes.some((item) => !!item && item.toLowerCase() === "https") ) { scheme = operation.pathObject.api.schemes[0]; } if (operation.pathObject.api.basePath) { basePath = operation.pathObject.api.basePath; } if (!basePath.startsWith("/")) { basePath = `/${basePath}`; } const baseUrl = host.startsWith(scheme + "://") || (hostTemplate && !useSchemePrefix) ? `${host}${basePath}` : `${scheme}://${host}${basePath}`; options.baseUrl = baseUrl; } options.method = operation.method; let pathTemplate = pathObject.path; if (pathTemplate && pathTemplate.includes("?")) { pathTemplate = pathTemplate.slice(0, pathTemplate.indexOf("?")); pathObject.path = pathTemplate; } options.pathTemplate = pathTemplate; for (const parameter of parameters) { let parameterValue = exampleParameterValues[parameter.name]; if (!parameterValue) { if (parameter.required) { const msg = `In operation "${operation.operationId}", parameter ${parameter.name} is required in ` + `the swagger spec but is not present in the provided example parameter values.`; const e = this.constructErrorObject<Sway.ValidationEntry>({ code: C.ErrorCodes.RequiredParameterExampleNotFound, message: msg, source: parameter.definition, }); if (result.validationResult === undefined) { throw new Error("result.validationResult is undefined"); } result.validationResult.errors.push(e); foundIssues = true; break; } continue; } const location = parameter.in; if (location === "path" || location === "query") { if (location === "path" && parameterValue && typeof parameterValue === "string") { // "/{scope}/scopes/resourceGroups/{resourceGroupName}" In the aforementioned path // template, we will search for the path parameter based on it's name // for example: "scope". Find it's index in the string and move backwards by 2 positions. // If the character at that position is a forward slash "/" and // the value for the parameter starts with a forward slash "/" then we have found the case // where there will be duplicate forward slashes in the url. if ( pathTemplate.charAt(pathTemplate.indexOf(`${parameter.name}`) - 2) === "/" && parameterValue.startsWith("/") ) { const msg = `In operation "${operation.operationId}", example for parameter ` + `"${parameter.name}": "${parameterValue}" starts with a forward slash ` + `and the path template: "${pathTemplate}" contains a forward slash before ` + `the parameter starts. This will cause double forward slashes ` + ` in the request url. Thus making it incorrect. Please rectify the example.`; const e = this.constructErrorObject<Sway.ValidationEntry>({ code: C.ErrorCodes.DoubleForwardSlashesInUrl, message: msg, source: parameter.definition, }); if (result.validationResult === undefined) { throw new Error("result.validationResult is undefined"); } result.validationResult.errors.push(e); foundIssues = true; break; } // replacing characters that may cause validator failed with empty string because this messes up Sways regex // validation of path segment. parameterValue = parameterValue.replace(/\//gi, ""); // replacing scheme that may cause validator failed when x-ms-parameterized-host enbaled & useSchemePrefix enabled // because if useSchemePrefix enabled ,the parameter value in x-ms-parameterized-host should not has the scheme (http://|https://) if (useSchemePrefix) { parameterValue = (parameterValue as string).replace(/^https{0,1}:/gi, ""); } } const paramType = location + "Parameters"; if (!options[paramType]) { options[paramType] = {}; } if (parameter[C.xmsSkipUrlEncoding] || utils.isUrlEncoded(parameterValue as string)) { options[paramType][parameter.name] = { value: parameterValue, skipUrlEncoding: true, }; } else { options[paramType][parameter.name] = parameterValue; } } else if (location === "body") { options.body = parameterValue; options.disableJsonStringifyOnBody = true; if (operation.consumes) { const isOctetStream = (consumes: string[]) => consumes.some((contentType) => contentType === "application/octet-stream"); options.headers["Content-Type"] = parameter.schema.format === "file" && isOctetStream(operation.consumes) ? "application/octet-stream" : operation.consumes[0]; } } else if (location === "header") { options.headers[parameter.name] = parameterValue; } else if (location === "formData") { // helper function const isFormUrlEncoded = (consumes: string[]) => consumes.some((contentType) => contentType === "application/x-www-form-urlencoded"); if (!options.formData) { options.formData = {}; } options.formData[parameter.name] = parameterValue; // set Content-Type correctly options.headers["Content-Type"] = operation.consumes && isFormUrlEncoded(operation.consumes) ? "application/x-www-form-urlencoded" : // default to formData "multipart/form-data"; // keep track of parameter type 'file' as sway expects such parameter types to be set // differently in the request object given for validation. if (parameter.type === "file") { if (!formDataFiles) { formDataFiles = {}; } formDataFiles[parameter.name] = parameterValue; } } } if (options.headers["content-type"]) { const val = delete options.headers["content-type"]; options.headers["Content-Type"] = val; } if (!options.headers["Content-Type"]) { options.headers["Content-Type"] = utils.getJsonContentType(operation.consumes); } let request: | (msRest.WebResource & { files?: openapiToolsCommon.MutableStringMap<unknown> }) | null = null; let validationResult: { errors: CommonError[]; } = { errors: [], }; if (!foundIssues) { try { request = new HttpRequest(); request = request.prepare(options as any); // set formData in the way sway expects it. if (formDataFiles) { request.files = formDataFiles; } else if (options.formData) { request.body = options.formData; } validationResult = operation.validateRequest(request); // this.sampleRequest = request } catch (err) { request = null; const e = this.constructErrorObject({ code: C.ErrorCodes.ErrorInPreparingRequest, message: err.message, innerErrors: [err], }); validationResult.errors.push(e); } } result.request = request; result.validationResult = utils.mergeObjects(validationResult, result.validationResult as any); return result; } private constructRequestResult( operationResult: Scenario, // OperationExampleResult, isValid: unknown, msg: string, requestValidationErrors?: ModelValidationError[] | null, requestValidationWarnings?: unknown, exampleFilePath?: string ): void { if (operationResult.request === undefined) { throw new Error("operationResult.result is undefined"); } if (!isValid) { operationResult.isValid = false; operationResult.request.isValid = false; if (!!requestValidationErrors && requestValidationErrors.length > 0) { if (exampleFilePath !== undefined) { requestValidationErrors.forEach((error) => { const positionInfo = openapiToolsCommon.getDescendantFilePosition( this.exampleJsonMap.get(exampleFilePath) as openapiToolsCommon.JsonRef, error.path ); if (!error.path) { error.path = ""; } const titleObj: any = { path: Array.isArray(error.path) ? [...error.path] : [error.path], position: positionInfo, url: exampleFilePath, }; error.title = JSON.stringify(titleObj); }); // process suppression for request validation errors if (this.suppression) { const requestParameterSuppressions = this.suppression.directive.filter( (item) => item.suppress === "INVALID_REQUEST_PARAMETER" ); if (requestParameterSuppressions && requestParameterSuppressions.length > 0) { requestValidationErrors = this.applySuppression( requestValidationErrors, requestParameterSuppressions ); } } } } if (requestValidationErrors && requestValidationErrors.length > 0) { const e = this.constructErrorObject({ code: C.ErrorCodes.RequestValidationError, message: msg, innerErrors: requestValidationErrors, }); operationResult.request.error = e; log.error(`${msg}:\n`, e); } else { msg = "Request parameters is valid."; operationResult.request.isValid = true; operationResult.request.result = msg; log.info(`${msg}`); } } else if (requestValidationWarnings) { operationResult.request.warning = requestValidationWarnings; log.debug(`${msg}:\n`, requestValidationWarnings); } else { operationResult.request.isValid = true; operationResult.request.result = msg; log.info(`${msg}`); } } private applySuppression( errors: ModelValidationError[], suppressionItems: amd.SuppressionItem[] ): ModelValidationError[] { const notSuppressedErrors: ModelValidationError[] = []; errors.forEach((item) => { if (!item.message || !this.existSuppression(suppressionItems, item.message)) { notSuppressedErrors.push(item); } }); return notSuppressedErrors; } private existSuppression(suppressionItems: amd.SuppressionItem[], message: string): boolean { for (const item of suppressionItems) { if (item["text-matches"] !== undefined) { const regex = new RegExp(item["text-matches"]); if (regex.test(message)) { return true; } } } return false; } private constructResponseResult( operationResult: Scenario, // OperationExampleResult, responseStatusCode: string, isValid: unknown, msg: string, responseValidationErrors?: ModelValidationError[] | null, responseValidationWarnings?: unknown ): void { if (operationResult.responses === undefined) { throw new Error("operationResult.responses is undefined"); } if (!operationResult.responses[responseStatusCode]) { operationResult.responses[responseStatusCode] = {}; } if (!isValid) { operationResult.isValid = false; operationResult.responses[responseStatusCode].isValid = false; const e = this.constructErrorObject({ code: C.ErrorCodes.ResponseValidationError, message: msg, innerErrors: responseValidationErrors, }); operationResult.responses[responseStatusCode].error = e; const pe = processErrors([e]); log.error(`${msg}:\n`, pe); } else if (responseValidationWarnings) { operationResult.responses[responseStatusCode].warning = responseValidationWarnings; log.debug(`${msg}:\n`, responseValidationWarnings); } else { operationResult.responses[responseStatusCode].isValid = true; operationResult.responses[responseStatusCode].result = msg; log.info(`${msg}`); } } }
the_stack
import * as React from 'react'; import { composeEventHandlers } from '@radix-ui/primitive'; import { createCollection } from '@radix-ui/react-collection'; import { useComposedRefs } from '@radix-ui/react-compose-refs'; import { createContextScope } from '@radix-ui/react-context'; import { useId } from '@radix-ui/react-id'; import { Primitive } from '@radix-ui/react-primitive'; import { useCallbackRef } from '@radix-ui/react-use-callback-ref'; import { useControllableState } from '@radix-ui/react-use-controllable-state'; import type * as Radix from '@radix-ui/react-primitive'; import type { Scope } from '@radix-ui/react-context'; const ENTRY_FOCUS = 'rovingFocusGroup.onEntryFocus'; const EVENT_OPTIONS = { bubbles: false, cancelable: true }; /* ------------------------------------------------------------------------------------------------- * RovingFocusGroup * -----------------------------------------------------------------------------------------------*/ const GROUP_NAME = 'RovingFocusGroup'; type ItemData = { id: string; focusable: boolean; active: boolean }; const [Collection, useCollection, createCollectionScope] = createCollection< HTMLSpanElement, ItemData >(GROUP_NAME); type ScopedProps<P> = P & { __scopeRovingFocusGroup?: Scope }; const [createRovingFocusGroupContext, createRovingFocusGroupScope] = createContextScope( GROUP_NAME, [createCollectionScope] ); type Orientation = React.AriaAttributes['aria-orientation']; type Direction = 'ltr' | 'rtl'; interface RovingFocusGroupOptions { /** * The orientation of the group. * Mainly so arrow navigation is done accordingly (left & right vs. up & down) */ orientation?: Orientation; /** * The direction of navigation between items. * @defaultValue ltr */ dir?: Direction; /** * Whether keyboard navigation should loop around * @defaultValue false */ loop?: boolean; } type RovingContextValue = RovingFocusGroupOptions & { currentTabStopId: string | null; onItemFocus(tabStopId: string): void; onItemShiftTab(): void; }; const [RovingFocusProvider, useRovingFocusContext] = createRovingFocusGroupContext<RovingContextValue>(GROUP_NAME); type RovingFocusGroupElement = RovingFocusGroupImplElement; interface RovingFocusGroupProps extends RovingFocusGroupImplProps {} const RovingFocusGroup = React.forwardRef<RovingFocusGroupElement, RovingFocusGroupProps>( (props: ScopedProps<RovingFocusGroupProps>, forwardedRef) => { return ( <Collection.Provider scope={props.__scopeRovingFocusGroup}> <Collection.Slot scope={props.__scopeRovingFocusGroup}> <RovingFocusGroupImpl {...props} ref={forwardedRef} /> </Collection.Slot> </Collection.Provider> ); } ); RovingFocusGroup.displayName = GROUP_NAME; /* -----------------------------------------------------------------------------------------------*/ type RovingFocusGroupImplElement = React.ElementRef<typeof Primitive.div>; type PrimitiveDivProps = Radix.ComponentPropsWithoutRef<typeof Primitive.div>; interface RovingFocusGroupImplProps extends Omit<PrimitiveDivProps, 'dir'>, RovingFocusGroupOptions { currentTabStopId?: string | null; defaultCurrentTabStopId?: string; onCurrentTabStopIdChange?: (tabStopId: string | null) => void; onEntryFocus?: (event: Event) => void; } const RovingFocusGroupImpl = React.forwardRef< RovingFocusGroupImplElement, RovingFocusGroupImplProps >((props: ScopedProps<RovingFocusGroupImplProps>, forwardedRef) => { const { __scopeRovingFocusGroup, orientation, dir = 'ltr', loop = false, currentTabStopId: currentTabStopIdProp, defaultCurrentTabStopId, onCurrentTabStopIdChange, onEntryFocus, ...groupProps } = props; const ref = React.useRef<RovingFocusGroupImplElement>(null); const composedRefs = useComposedRefs(forwardedRef, ref); const [currentTabStopId = null, setCurrentTabStopId] = useControllableState({ prop: currentTabStopIdProp, defaultProp: defaultCurrentTabStopId, onChange: onCurrentTabStopIdChange, }); const [isTabbingBackOut, setIsTabbingBackOut] = React.useState(false); const handleEntryFocus = useCallbackRef(onEntryFocus); const getItems = useCollection(__scopeRovingFocusGroup); const isClickFocusRef = React.useRef(false); React.useEffect(() => { const node = ref.current; if (node) { node.addEventListener(ENTRY_FOCUS, handleEntryFocus); return () => node.removeEventListener(ENTRY_FOCUS, handleEntryFocus); } }, [handleEntryFocus]); return ( <RovingFocusProvider scope={__scopeRovingFocusGroup} orientation={orientation} dir={dir} loop={loop} currentTabStopId={currentTabStopId} onItemFocus={React.useCallback( (tabStopId) => setCurrentTabStopId(tabStopId), [setCurrentTabStopId] )} onItemShiftTab={React.useCallback(() => setIsTabbingBackOut(true), [])} > <Primitive.div tabIndex={isTabbingBackOut ? -1 : 0} data-orientation={orientation} {...groupProps} ref={composedRefs} style={{ outline: 'none', ...props.style }} onMouseDown={composeEventHandlers(props.onMouseDown, () => { isClickFocusRef.current = true; })} onFocus={composeEventHandlers(props.onFocus, (event) => { // We normally wouldn't need this check, because we already check // that the focus is on the current target and not bubbling to it. // We do this because Safari doesn't focus buttons when clicked, and // instead, the wrapper will get focused and not through a bubbling event. const isKeyboardFocus = !isClickFocusRef.current; if (event.target === event.currentTarget && isKeyboardFocus && !isTabbingBackOut) { const entryFocusEvent = new Event(ENTRY_FOCUS, EVENT_OPTIONS); event.currentTarget.dispatchEvent(entryFocusEvent); if (!entryFocusEvent.defaultPrevented) { const items = getItems().filter((item) => item.focusable); const activeItem = items.find((item) => item.active); const currentItem = items.find((item) => item.id === currentTabStopId); const candidateItems = [activeItem, currentItem, ...items].filter( Boolean ) as typeof items; const candidateNodes = candidateItems.map((item) => item.ref.current!); focusFirst(candidateNodes); } } isClickFocusRef.current = false; })} onBlur={composeEventHandlers(props.onBlur, () => setIsTabbingBackOut(false))} /> </RovingFocusProvider> ); }); /* ------------------------------------------------------------------------------------------------- * RovingFocusGroupItem * -----------------------------------------------------------------------------------------------*/ const ITEM_NAME = 'RovingFocusGroupItem'; type RovingFocusItemElement = React.ElementRef<typeof Primitive.span>; type PrimitiveSpanProps = Radix.ComponentPropsWithoutRef<typeof Primitive.span>; interface RovingFocusItemProps extends PrimitiveSpanProps { focusable?: boolean; active?: boolean; } const RovingFocusGroupItem = React.forwardRef<RovingFocusItemElement, RovingFocusItemProps>( (props: ScopedProps<RovingFocusItemProps>, forwardedRef) => { const { __scopeRovingFocusGroup, focusable = true, active = false, ...itemProps } = props; const id = useId(); const context = useRovingFocusContext(ITEM_NAME, __scopeRovingFocusGroup); const isCurrentTabStop = context.currentTabStopId === id; const getItems = useCollection(__scopeRovingFocusGroup); return ( <Collection.ItemSlot scope={__scopeRovingFocusGroup} id={id} focusable={focusable} active={active} > <Primitive.span tabIndex={isCurrentTabStop ? 0 : -1} data-orientation={context.orientation} {...itemProps} ref={forwardedRef} onMouseDown={composeEventHandlers(props.onMouseDown, (event) => { // We prevent focusing non-focusable items on `mousedown`. // Even though the item has tabIndex={-1}, that only means take it out of the tab order. if (!focusable) event.preventDefault(); // Safari doesn't focus a button when clicked so we run our logic on mousedown also else context.onItemFocus(id); })} onFocus={composeEventHandlers(props.onFocus, () => context.onItemFocus(id))} onKeyDown={composeEventHandlers(props.onKeyDown, (event) => { if (event.key === 'Tab' && event.shiftKey) { context.onItemShiftTab(); return; } if (event.target !== event.currentTarget) return; const focusIntent = getFocusIntent(event, context.orientation, context.dir); if (focusIntent !== undefined) { event.preventDefault(); const items = getItems().filter((item) => item.focusable); let candidateNodes = items.map((item) => item.ref.current!); if (focusIntent === 'last') candidateNodes.reverse(); else if (focusIntent === 'prev' || focusIntent === 'next') { if (focusIntent === 'prev') candidateNodes.reverse(); const currentIndex = candidateNodes.indexOf(event.currentTarget); candidateNodes = context.loop ? wrapArray(candidateNodes, currentIndex + 1) : candidateNodes.slice(currentIndex + 1); } /** * Imperative focus during keydown is risky so we prevent React's batching updates * to avoid potential bugs. See: https://github.com/facebook/react/issues/20332 */ setTimeout(() => focusFirst(candidateNodes)); } })} /> </Collection.ItemSlot> ); } ); RovingFocusGroupItem.displayName = ITEM_NAME; /* -----------------------------------------------------------------------------------------------*/ // prettier-ignore const MAP_KEY_TO_FOCUS_INTENT: Record<string, FocusIntent> = { ArrowLeft: 'prev', ArrowUp: 'prev', ArrowRight: 'next', ArrowDown: 'next', PageUp: 'first', Home: 'first', PageDown: 'last', End: 'last', }; function getDirectionAwareKey(key: string, dir?: Direction) { if (dir !== 'rtl') return key; return key === 'ArrowLeft' ? 'ArrowRight' : key === 'ArrowRight' ? 'ArrowLeft' : key; } type FocusIntent = 'first' | 'last' | 'prev' | 'next'; function getFocusIntent(event: React.KeyboardEvent, orientation?: Orientation, dir?: Direction) { const key = getDirectionAwareKey(event.key, dir); if (orientation === 'vertical' && ['ArrowLeft', 'ArrowRight'].includes(key)) return undefined; if (orientation === 'horizontal' && ['ArrowUp', 'ArrowDown'].includes(key)) return undefined; return MAP_KEY_TO_FOCUS_INTENT[key]; } function focusFirst(candidates: HTMLElement[]) { const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement; for (const candidate of candidates) { // if focus is already where we want to go, we don't want to keep going through the candidates if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return; candidate.focus(); if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return; } } /** * Wraps an array around itself at a given start index * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']` */ function wrapArray<T>(array: T[], startIndex: number) { return array.map((_, index) => array[(startIndex + index) % array.length]); } const Root = RovingFocusGroup; const Item = RovingFocusGroupItem; export { createRovingFocusGroupScope, // RovingFocusGroup, RovingFocusGroupItem, // Root, Item, }; export type { RovingFocusGroupProps, RovingFocusItemProps };
the_stack
import { EvaluationReduxAction, ReduxAction, ReduxActionErrorTypes, ReduxActionTypes, } from "constants/ReduxActionConstants"; import { all, call, put, race, select, take, takeEvery, takeLatest, } from "redux-saga/effects"; import { Datasource } from "entities/Datasource"; import ActionAPI, { ActionCreateUpdateResponse } from "api/ActionAPI"; import { GenericApiResponse } from "api/ApiResponses"; import PageApi from "api/PageApi"; import { updateCanvasWithDSL } from "sagas/PageSagas"; import { copyActionError, copyActionSuccess, createActionRequest, createActionSuccess, deleteActionSuccess, fetchActionsForPage, fetchActionsForPageSuccess, FetchActionsPayload, moveActionError, moveActionSuccess, SetActionPropertyPayload, updateAction, updateActionProperty, updateActionSuccess, } from "actions/pluginActionActions"; import { DynamicPath, isChildPropertyPath, isDynamicValue, removeBindingsFromActionObject, } from "utils/DynamicBindingUtils"; import { validateResponse } from "./ErrorSagas"; import { transformRestAction } from "transformers/RestActionTransformer"; import { getActionById, getCurrentApplicationId, getCurrentPageId, } from "selectors/editorSelectors"; import AnalyticsUtil from "utils/AnalyticsUtil"; import { Action, ActionViewMode, PluginType, SlashCommand, SlashCommandPayload, } from "entities/Action"; import { ActionData, ActionDataState, } from "reducers/entityReducers/actionsReducer"; import { getAction, getCurrentPageNameByActionId, getEditorConfig, getPageNameByPageId, getPlugin, getSettingConfig, getDatasources, getActions, } from "selectors/entitiesSelector"; import history from "utils/history"; import { API_EDITOR_ID_URL, BUILDER_PAGE_URL, INTEGRATION_EDITOR_URL, INTEGRATION_TABS, QUERIES_EDITOR_ID_URL, } from "constants/routes"; import { Toaster } from "components/ads/Toast"; import { Variant } from "components/ads/common"; import PerformanceTracker, { PerformanceTransactionName, } from "utils/PerformanceTracker"; import { ACTION_COPY_SUCCESS, ACTION_MOVE_SUCCESS, createMessage, ERROR_ACTION_COPY_FAIL, ERROR_ACTION_MOVE_FAIL, ERROR_ACTION_RENAME_FAIL, } from "constants/messages"; import _, { merge, get } from "lodash"; import { getConfigInitialValues } from "components/formControls/utils"; import AppsmithConsole from "utils/AppsmithConsole"; import { ENTITY_TYPE } from "entities/AppsmithConsole"; import { SAAS_EDITOR_API_ID_URL } from "pages/Editor/SaaSEditor/constants"; import LOG_TYPE from "entities/AppsmithConsole/logtype"; import { createNewApiAction } from "actions/apiPaneActions"; import { createNewApiName, createNewQueryName, getQueryParams, } from "utils/AppsmithUtils"; import { DEFAULT_API_ACTION_CONFIG } from "constants/ApiEditorConstants"; import { toggleShowGlobalSearchModal, setGlobalSearchFilterContext, } from "actions/globalSearchActions"; import { filterCategories, SEARCH_CATEGORY_ID, } from "components/editorComponents/GlobalSearch/utils"; import { getSelectedWidget, getWidgetById } from "./selectors"; import { onApiEditor, onQueryEditor, } from "components/editorComponents/Debugger/helpers"; import { Plugin } from "api/PluginApi"; import { FlattenedWidgetProps } from "reducers/entityReducers/canvasWidgetsReducer"; import { SnippetAction } from "reducers/uiReducers/globalSearchReducer"; export function* createActionSaga( actionPayload: ReduxAction< Partial<Action> & { eventData: any; pluginId: string } >, ) { try { let payload = actionPayload.payload; if (actionPayload.payload.pluginId) { const editorConfig = yield select( getEditorConfig, actionPayload.payload.pluginId, ); const settingConfig = yield select( getSettingConfig, actionPayload.payload.pluginId, ); let initialValues = yield call(getConfigInitialValues, editorConfig); if (settingConfig) { const settingInitialValues = yield call( getConfigInitialValues, settingConfig, ); initialValues = merge(initialValues, settingInitialValues); } payload = merge(initialValues, actionPayload.payload); } const response: ActionCreateUpdateResponse = yield ActionAPI.createAction( payload, ); const isValidResponse = yield validateResponse(response); if (isValidResponse) { const pageName = yield select( getCurrentPageNameByActionId, response.data.id, ); AnalyticsUtil.logEvent("CREATE_ACTION", { id: response.data.id, actionName: response.data.name, pageName: pageName, ...actionPayload.payload.eventData, }); AppsmithConsole.info({ text: `Action created`, source: { type: ENTITY_TYPE.ACTION, id: response.data.id, name: response.data.name, }, }); const newAction = response.data; yield put(createActionSuccess(newAction)); } } catch (error) { yield put({ type: ReduxActionErrorTypes.CREATE_ACTION_ERROR, payload: actionPayload.payload, }); } } export function* fetchActionsSaga( action: EvaluationReduxAction<FetchActionsPayload>, ) { const { applicationId } = action.payload; PerformanceTracker.startAsyncTracking( PerformanceTransactionName.FETCH_ACTIONS_API, { mode: "EDITOR", appId: applicationId }, ); try { const response: GenericApiResponse<Action[]> = yield ActionAPI.fetchActions( applicationId, ); const isValidResponse = yield validateResponse(response); if (isValidResponse) { yield put({ type: ReduxActionTypes.FETCH_ACTIONS_SUCCESS, payload: response.data, postEvalActions: action.postEvalActions, }); PerformanceTracker.stopAsyncTracking( PerformanceTransactionName.FETCH_ACTIONS_API, ); } } catch (error) { yield put({ type: ReduxActionErrorTypes.FETCH_ACTIONS_ERROR, payload: { error }, }); PerformanceTracker.stopAsyncTracking( PerformanceTransactionName.FETCH_ACTIONS_API, { failed: true }, ); } } export function* fetchActionsForViewModeSaga( action: ReduxAction<FetchActionsPayload>, ) { const { applicationId } = action.payload; PerformanceTracker.startAsyncTracking( PerformanceTransactionName.FETCH_ACTIONS_API, { mode: "VIEWER", appId: applicationId }, ); try { const response: GenericApiResponse<ActionViewMode[]> = yield ActionAPI.fetchActionsForViewMode( applicationId, ); const correctFormatResponse = response.data.map((action) => { return { ...action, actionConfiguration: { timeoutInMillisecond: action.timeoutInMillisecond, }, }; }); const isValidResponse = yield validateResponse(response); if (isValidResponse) { yield put({ type: ReduxActionTypes.FETCH_ACTIONS_VIEW_MODE_SUCCESS, payload: correctFormatResponse, }); PerformanceTracker.stopAsyncTracking( PerformanceTransactionName.FETCH_ACTIONS_API, ); } } catch (error) { yield put({ type: ReduxActionErrorTypes.FETCH_ACTIONS_VIEW_MODE_ERROR, payload: { error }, }); PerformanceTracker.stopAsyncTracking( PerformanceTransactionName.FETCH_ACTIONS_API, { failed: true }, ); } } export function* fetchActionsForPageSaga( action: EvaluationReduxAction<{ pageId: string }>, ) { const { pageId } = action.payload; PerformanceTracker.startAsyncTracking( PerformanceTransactionName.FETCH_PAGE_ACTIONS_API, { pageId: pageId }, ); try { const response: GenericApiResponse<Action[]> = yield call( ActionAPI.fetchActionsByPageId, pageId, ); const isValidResponse = yield validateResponse(response); if (isValidResponse) { yield put( fetchActionsForPageSuccess(response.data, action.postEvalActions), ); PerformanceTracker.stopAsyncTracking( PerformanceTransactionName.FETCH_PAGE_ACTIONS_API, ); } } catch (error) { PerformanceTracker.stopAsyncTracking( PerformanceTransactionName.FETCH_PAGE_ACTIONS_API, { failed: true }, ); yield put({ type: ReduxActionErrorTypes.FETCH_ACTIONS_FOR_PAGE_ERROR, payload: { error }, }); } } export function* updateActionSaga(actionPayload: ReduxAction<{ id: string }>) { try { PerformanceTracker.startAsyncTracking( PerformanceTransactionName.UPDATE_ACTION_API, { actionid: actionPayload.payload.id }, ); let action = yield select(getAction, actionPayload.payload.id); if (!action) throw new Error("Could not find action to update"); const isApi = action.pluginType === PluginType.API; if (isApi) { action = transformRestAction(action); } const response: GenericApiResponse<Action> = yield ActionAPI.updateAction( action, ); const isValidResponse = yield validateResponse(response); if (isValidResponse) { const pageName = yield select( getCurrentPageNameByActionId, response.data.id, ); if (action.pluginType === PluginType.DB) { AnalyticsUtil.logEvent("SAVE_QUERY", { queryName: action.name, pageName, }); } else if (action.pluginType === PluginType.API) { AnalyticsUtil.logEvent("SAVE_API", { apiId: response.data.id, apiName: response.data.name, pageName: pageName, }); } else if (action.pluginType === PluginType.SAAS) { AnalyticsUtil.logEvent("SAVE_SAAS", { apiId: response.data.id, apiName: response.data.name, pageName: pageName, }); } PerformanceTracker.stopAsyncTracking( PerformanceTransactionName.UPDATE_ACTION_API, ); yield put(updateActionSuccess({ data: response.data })); } } catch (error) { PerformanceTracker.stopAsyncTracking( PerformanceTransactionName.UPDATE_ACTION_API, { failed: true }, ); yield put({ type: ReduxActionErrorTypes.UPDATE_ACTION_ERROR, payload: { error, id: actionPayload.payload.id }, }); } } export function* deleteActionSaga( actionPayload: ReduxAction<{ id: string; name: string; onSuccess?: () => void; }>, ) { try { const id = actionPayload.payload.id; const name = actionPayload.payload.name; const action: Action | undefined = yield select(getAction, id); if (!action) return; const isApi = action.pluginType === PluginType.API; const isQuery = action.pluginType === PluginType.DB; const isSaas = action.pluginType === PluginType.SAAS; const response: GenericApiResponse<Action> = yield ActionAPI.deleteAction( id, ); const isValidResponse = yield validateResponse(response); if (!isValidResponse) { return; } if (isApi) { const pageName = yield select(getCurrentPageNameByActionId, id); AnalyticsUtil.logEvent("DELETE_API", { apiName: name, pageName, apiID: id, }); } if (isSaas) { const pageName = yield select(getCurrentPageNameByActionId, id); AnalyticsUtil.logEvent("DELETE_SAAS", { apiName: name, pageName, apiID: id, }); } if (isQuery) { AnalyticsUtil.logEvent("DELETE_QUERY", { queryName: name, }); } if (!!actionPayload.payload.onSuccess) { actionPayload.payload.onSuccess(); } else { const pageId = yield select(getCurrentPageId); const applicationId = yield select(getCurrentApplicationId); history.push( INTEGRATION_EDITOR_URL(applicationId, pageId, INTEGRATION_TABS.NEW), ); } AppsmithConsole.info({ logType: LOG_TYPE.ENTITY_DELETED, text: "Action was deleted", source: { type: ENTITY_TYPE.ACTION, name: response.data.name, id: response.data.id, }, analytics: { pluginId: action.pluginId, }, }); yield put(deleteActionSuccess({ id })); } catch (error) { yield put({ type: ReduxActionErrorTypes.DELETE_ACTION_ERROR, payload: { error, id: actionPayload.payload.id }, }); } } function* moveActionSaga( action: ReduxAction<{ id: string; destinationPageId: string; originalPageId: string; name: string; }>, ) { const actionObject: Action = yield select(getAction, action.payload.id); const withoutBindings = removeBindingsFromActionObject(actionObject); try { const response = yield ActionAPI.moveAction({ action: { ...withoutBindings, pageId: action.payload.originalPageId, name: action.payload.name, }, destinationPageId: action.payload.destinationPageId, }); const isValidResponse = yield validateResponse(response); const pageName = yield select(getPageNameByPageId, response.data.pageId); if (isValidResponse) { Toaster.show({ text: createMessage(ACTION_MOVE_SUCCESS, response.data.name, pageName), variant: Variant.success, }); } AnalyticsUtil.logEvent("MOVE_API", { apiName: response.data.name, pageName: pageName, apiID: response.data.id, }); yield put(moveActionSuccess(response.data)); } catch (e) { Toaster.show({ text: createMessage(ERROR_ACTION_MOVE_FAIL, actionObject.name), variant: Variant.danger, }); yield put( moveActionError({ id: action.payload.id, originalPageId: action.payload.originalPageId, }), ); } } function* copyActionSaga( action: ReduxAction<{ id: string; destinationPageId: string; name: string }>, ) { let actionObject: Action = yield select(getAction, action.payload.id); try { if (!actionObject) throw new Error("Could not find action to copy"); if (action.payload.destinationPageId !== actionObject.pageId) { actionObject = removeBindingsFromActionObject(actionObject); } const copyAction = Object.assign({}, actionObject, { name: action.payload.name, pageId: action.payload.destinationPageId, }) as Partial<Action>; delete copyAction.id; const response = yield ActionAPI.createAction(copyAction); const datasources = yield select(getDatasources); const isValidResponse = yield validateResponse(response); const pageName = yield select(getPageNameByPageId, response.data.pageId); if (isValidResponse) { Toaster.show({ text: createMessage(ACTION_COPY_SUCCESS, actionObject.name, pageName), variant: Variant.success, }); } AnalyticsUtil.logEvent("DUPLICATE_API", { apiName: response.data.name, pageName: pageName, apiID: response.data.id, }); // checking if there is existing datasource to be added to the action payload const existingDatasource = datasources.find( (d: Datasource) => d.id === response.data.datasource.id, ); let payload = response.data; if (existingDatasource) { payload = { ...payload, datasource: existingDatasource }; } yield put(copyActionSuccess(payload)); } catch (e) { const actionName = actionObject ? actionObject.name : ""; Toaster.show({ text: createMessage(ERROR_ACTION_COPY_FAIL, actionName), variant: Variant.danger, }); yield put(copyActionError(action.payload)); } } export function* refactorActionName( id: string, pageId: string, oldName: string, newName: string, ) { // fetch page of the action PerformanceTracker.startAsyncTracking( PerformanceTransactionName.REFACTOR_ACTION_NAME, { actionId: id }, ); const pageResponse = yield call(PageApi.fetchPage, { id: pageId, }); // check if page request is successful const isPageRequestSuccessful = yield validateResponse(pageResponse); if (isPageRequestSuccessful) { // get the layoutId from the page response const layoutId = pageResponse.data.layouts[0].id; // call to refactor action const refactorResponse = yield ActionAPI.updateActionName({ layoutId, actionId: id, pageId: pageId, oldName: oldName, newName: newName, }); const isRefactorSuccessful = yield validateResponse(refactorResponse); const currentPageId = yield select(getCurrentPageId); PerformanceTracker.stopAsyncTracking( PerformanceTransactionName.REFACTOR_ACTION_NAME, { isSuccess: isRefactorSuccessful }, ); if (isRefactorSuccessful) { yield put({ type: ReduxActionTypes.SAVE_ACTION_NAME_SUCCESS, payload: { actionId: id, }, }); if (currentPageId === pageId) { yield updateCanvasWithDSL(refactorResponse.data, pageId, layoutId); } else { yield put(fetchActionsForPage(pageId)); } } } } function* bindDataOnCanvasSaga( action: ReduxAction<{ queryId: string; applicationId: string; pageId: string; }>, ) { const { pageId, queryId } = action.payload; const applicationId = yield select(getCurrentApplicationId); history.push( BUILDER_PAGE_URL({ applicationId, pageId, params: { isSnipingMode: "true", bindTo: queryId, }, }), ); } function* saveActionName(action: ReduxAction<{ id: string; name: string }>) { // Takes from state, checks if the name isValid, saves const apiId = action.payload.id; const api = yield select((state) => state.entities.actions.find( (action: ActionData) => action.config.id === apiId, ), ); try { yield refactorActionName( api.config.id, api.config.pageId, api.config.name, action.payload.name, ); } catch (e) { yield put({ type: ReduxActionErrorTypes.SAVE_ACTION_NAME_ERROR, payload: { actionId: action.payload.id, oldName: api.config.name, }, }); Toaster.show({ text: createMessage(ERROR_ACTION_RENAME_FAIL, action.payload.name), variant: Variant.danger, }); console.error(e); } } function getDynamicBindingsChangesSaga( action: Action, value: unknown, field: string, ) { const bindingField = field.replace("actionConfiguration.", ""); let dynamicBindings: DynamicPath[] = action.dynamicBindingPathList || []; if (typeof value === "object") { dynamicBindings = dynamicBindings.filter((dynamicPath) => { if (isChildPropertyPath(bindingField, dynamicPath.key)) { const childPropertyValue = _.get(value, dynamicPath.key); return isDynamicValue(childPropertyValue); } }); } else if (typeof value === "string") { const fieldExists = _.some(dynamicBindings, { key: bindingField }); const isDynamic = isDynamicValue(value); if (!isDynamic && fieldExists) { dynamicBindings = dynamicBindings.filter((d) => d.key !== bindingField); } if (isDynamic && !fieldExists) { dynamicBindings.push({ key: bindingField }); } } return dynamicBindings; } function* setActionPropertySaga(action: ReduxAction<SetActionPropertyPayload>) { const { actionId, propertyName, value } = action.payload; if (!actionId) return; if (propertyName === "name") return; const actionObj = yield select(getAction, actionId); const fieldToBeUpdated = propertyName.replace( "actionConfiguration", "config", ); AppsmithConsole.info({ logType: LOG_TYPE.ACTION_UPDATE, text: "Configuration updated", source: { type: ENTITY_TYPE.ACTION, name: actionObj.name, id: actionId, propertyPath: fieldToBeUpdated, }, state: { [fieldToBeUpdated]: value, }, }); const effects: Record<string, any> = {}; // Value change effect effects[propertyName] = value; // Bindings change effect effects.dynamicBindingPathList = getDynamicBindingsChangesSaga( actionObj, value, propertyName, ); yield all( Object.keys(effects).map((field) => put(updateActionProperty({ id: actionId, field, value: effects[field] })), ), ); if (propertyName === "executeOnLoad") { yield put({ type: ReduxActionTypes.TOGGLE_ACTION_EXECUTE_ON_LOAD_INIT, payload: { actionId, shouldExecute: value, }, }); return; } yield put(updateAction({ id: actionId })); } function* toggleActionExecuteOnLoadSaga( action: ReduxAction<{ actionId: string; shouldExecute: boolean }>, ) { try { const response = yield call( ActionAPI.toggleActionExecuteOnLoad, action.payload.actionId, action.payload.shouldExecute, ); const isValidResponse = yield validateResponse(response); if (isValidResponse) { yield put({ type: ReduxActionTypes.TOGGLE_ACTION_EXECUTE_ON_LOAD_SUCCESS, }); } } catch (error) { yield put({ type: ReduxActionErrorTypes.TOGGLE_ACTION_EXECUTE_ON_LOAD_ERROR, payload: error, }); } } function* handleMoveOrCopySaga(actionPayload: ReduxAction<{ id: string }>) { const { id } = actionPayload.payload; const action: Action = yield select(getAction, id); const isApi = action.pluginType === PluginType.API; const isQuery = action.pluginType === PluginType.DB; const isSaas = action.pluginType === PluginType.SAAS; const applicationId = yield select(getCurrentApplicationId); if (isApi) { history.push(API_EDITOR_ID_URL(applicationId, action.pageId, action.id)); } if (isQuery) { history.push( QUERIES_EDITOR_ID_URL(applicationId, action.pageId, action.id), ); } if (isSaas) { const plugin = yield select(getPlugin, action.pluginId); history.push( SAAS_EDITOR_API_ID_URL( applicationId, action.pageId, plugin.packageName, action.id, ), ); } } function* buildMetaForSnippets( entityId: any, entityType: string, expectedType: string, propertyPath: string, ) { /* Score is set to sort the snippets in the following order. 1. Field (10) 2. Entity + (All Queries / All Widgets) +Data Type (9) 3. Entity + Data Type (8) 4. Entity (5) 5. All Queries / All Widgets + Data Type (4) 6. All Queries / All Widgets 1 */ /* UNKNOWN is given priority over other non matching dataTypes. Eg. If there are no snippets matching a dataType criteria, we are promote snippets of type UNKNOWN */ const refinements: any = { entities: [entityType], }; const fieldMeta: { dataType: Array<string>; fields?: Array<string>; entities?: Array<string>; } = { dataType: [`${expectedType}<score=3>`, `UNKNOWN<score=1>`], }; if (propertyPath) { const relevantField = propertyPath .split(".") .slice(-1) .pop(); fieldMeta.fields = [`${relevantField}<score=10>`]; } if (entityType === ENTITY_TYPE.ACTION && entityId) { const currentEntity: Action = yield select(getActionById, { match: { params: { apiId: entityId } }, }); const plugin: Plugin = yield select(getPlugin, currentEntity.pluginId); const type: string = plugin.packageName || ""; refinements.entities = [type, entityType]; fieldMeta.entities = [`${type}<score=5>`, `${entityType}<score=1>`]; } if (entityType === ENTITY_TYPE.WIDGET && entityId) { const currentEntity: FlattenedWidgetProps = yield select( getWidgetById, entityId, ); const type: string = currentEntity.type || ""; refinements.entities = [type, entityType]; fieldMeta.entities = [`${type}<score=5>`, `${entityType}<score=1>`]; } return { refinements, fieldMeta }; } function* getCurrentEntity(pageId: string, params: Record<string, string>) { let entityId = "", entityType = ""; if (onApiEditor() || onQueryEditor()) { const id = params.apiId || params.queryId; const action: Action = yield select(getAction, id); entityId = action?.id; entityType = ENTITY_TYPE.ACTION; } else { const widget: FlattenedWidgetProps = yield select(getSelectedWidget); entityId = widget?.widgetId; entityType = ENTITY_TYPE.WIDGET; } return { entityId, entityType }; } function* executeCommandSaga(actionPayload: ReduxAction<SlashCommandPayload>) { const pageId: string = yield select(getCurrentPageId); const applicationId = yield select(getCurrentApplicationId); const callback = get(actionPayload, "payload.callback"); const params = getQueryParams(); switch (actionPayload.payload.actionType) { case SlashCommand.NEW_SNIPPET: let { entityId, entityType } = get(actionPayload, "payload.args", {}); const { expectedType, propertyPath } = get( actionPayload, "payload.args", {}, ); // Entity is derived using the dataTreePath property. // Fallback to find current entity when dataTreePath property value is empty (Eg. trigger fields) if (!entityId) { const currentEntity: { entityId: string; entityType: string; } = yield getCurrentEntity(pageId, params); entityId = currentEntity.entityId; entityType = currentEntity.entityType; } const { fieldMeta, refinements } = yield buildMetaForSnippets( entityId, entityType, expectedType, propertyPath, ); yield put( setGlobalSearchFilterContext({ refinements, fieldMeta, }), ); yield put( toggleShowGlobalSearchModal( filterCategories[SEARCH_CATEGORY_ID.SNIPPETS], ), ); yield put( setGlobalSearchFilterContext({ onEnter: typeof callback === "function" ? SnippetAction.INSERT : SnippetAction.COPY, //Set insertSnippet to true only if values }), ); AnalyticsUtil.logEvent("SNIPPET_LOOKUP"); const effectRaceResult: { failure: any; success: any } = yield race({ failure: take(ReduxActionTypes.CANCEL_SNIPPET), success: take(ReduxActionTypes.INSERT_SNIPPET), }); if (effectRaceResult.failure) return; if (callback) callback(effectRaceResult.success.payload); break; case SlashCommand.NEW_INTEGRATION: history.push( INTEGRATION_EDITOR_URL(applicationId, pageId, INTEGRATION_TABS.NEW), ); break; case SlashCommand.NEW_QUERY: const datasource = get(actionPayload, "payload.args.datasource"); const pluginId = get(datasource, "pluginId"); const plugin: Plugin = yield select(getPlugin, pluginId); const actions: ActionDataState = yield select(getActions); const pageActions = actions.filter( (a: ActionData) => a.config.pageId === pageId, ); const newQueryName = plugin.type === PluginType.DB ? createNewQueryName(actions, pageId) : createNewApiName(pageActions, pageId); const nextPayload: Partial<Action> = { name: newQueryName, pageId, eventData: { actionType: "Query", from: "Quick-Commands", dataSource: datasource.name, }, pluginId: datasource.pluginId, actionConfiguration: {}, }; if (plugin.type === "API") { nextPayload.datasource = datasource; nextPayload.actionConfiguration = DEFAULT_API_ACTION_CONFIG; } else { nextPayload.datasource = { id: datasource.id, }; } yield put(createActionRequest(nextPayload)); const QUERY = yield take(ReduxActionTypes.CREATE_ACTION_SUCCESS); if (callback) callback(`{{${QUERY.payload.name}.data}}`); break; case SlashCommand.NEW_API: yield put(createNewApiAction(pageId, "QUICK_COMMANDS")); const API = yield take(ReduxActionTypes.CREATE_ACTION_SUCCESS); if (callback) callback(`{{${API.payload.name}.data}}`); break; } } export function* watchActionSagas() { yield all([ takeEvery(ReduxActionTypes.SET_ACTION_PROPERTY, setActionPropertySaga), takeEvery(ReduxActionTypes.FETCH_ACTIONS_INIT, fetchActionsSaga), takeEvery( ReduxActionTypes.FETCH_ACTIONS_VIEW_MODE_INIT, fetchActionsForViewModeSaga, ), takeEvery(ReduxActionTypes.CREATE_ACTION_INIT, createActionSaga), takeLatest(ReduxActionTypes.UPDATE_ACTION_INIT, updateActionSaga), takeLatest(ReduxActionTypes.DELETE_ACTION_INIT, deleteActionSaga), takeLatest(ReduxActionTypes.BIND_DATA_ON_CANVAS, bindDataOnCanvasSaga), takeLatest(ReduxActionTypes.SAVE_ACTION_NAME_INIT, saveActionName), takeLatest(ReduxActionTypes.MOVE_ACTION_INIT, moveActionSaga), takeLatest(ReduxActionTypes.COPY_ACTION_INIT, copyActionSaga), takeLatest( ReduxActionTypes.FETCH_ACTIONS_FOR_PAGE_INIT, fetchActionsForPageSaga, ), takeEvery(ReduxActionTypes.MOVE_ACTION_SUCCESS, handleMoveOrCopySaga), takeEvery(ReduxActionTypes.COPY_ACTION_SUCCESS, handleMoveOrCopySaga), takeEvery(ReduxActionErrorTypes.MOVE_ACTION_ERROR, handleMoveOrCopySaga), takeEvery(ReduxActionErrorTypes.COPY_ACTION_ERROR, handleMoveOrCopySaga), takeLatest( ReduxActionTypes.TOGGLE_ACTION_EXECUTE_ON_LOAD_INIT, toggleActionExecuteOnLoadSaga, ), takeLatest(ReduxActionTypes.EXECUTE_COMMAND, executeCommandSaga), ]); }
the_stack
import {GifTypes} from 'action_types'; import {Client4} from 'client'; import gfycatSdk from 'utils/gfycat_sdk'; import {DispatchFunc, GetStateFunc} from 'types/actions'; import {GlobalState} from 'types/store'; // APP PROPS export function saveAppPropsRequest(props: any) { return { type: GifTypes.SAVE_APP_PROPS, props, }; } export function saveAppProps(appProps: any) { return (dispatch: DispatchFunc, getState: GetStateFunc) => { const {GfycatApiKey, GfycatApiSecret} = getState().entities.general.config; gfycatSdk(GfycatApiKey!, GfycatApiSecret!).authenticate(); dispatch(saveAppPropsRequest(appProps)); }; } // SEARCH export function selectSearchText(searchText: string) { return { type: GifTypes.SELECT_SEARCH_TEXT, searchText, }; } export function updateSearchText(searchText: string) { return { type: GifTypes.UPDATE_SEARCH_TEXT, searchText, }; } export function searchBarTextSave(searchBarText: string) { return { type: GifTypes.SAVE_SEARCH_BAR_TEXT, searchBarText, }; } export function invalidateSearchText(searchText: string) { return { type: GifTypes.INVALIDATE_SEARCH_TEXT, searchText, }; } export function requestSearch(searchText: string) { return { type: GifTypes.REQUEST_SEARCH, searchText, }; } export function receiveSearch({searchText, count, start, json}: {searchText: string; count: number; start: number; json: any}) { return { type: GifTypes.RECEIVE_SEARCH, searchText, ...json, count, start, currentPage: start / count, receivedAt: Date.now(), }; } export function receiveSearchEnd(searchText: string) { return { type: GifTypes.RECEIVE_SEARCH_END, searchText, }; } export function errorSearching(err: any, searchText: string) { return { type: GifTypes.SEARCH_FAILURE, searchText, err, }; } export function receiveCategorySearch({tagName, json}: {tagName: string; json: any}) { return { type: GifTypes.RECEIVE_CATEGORY_SEARCH, searchText: tagName, ...json, receiveAt: Date.now(), }; } export function clearSearchResults() { return { type: GifTypes.CLEAR_SEARCH_RESULTS, }; } export function requestSearchById(gfyId: string) { return { type: GifTypes.SEARCH_BY_ID_REQUEST, payload: { gfyId, }, }; } export function receiveSearchById(gfyId: string, gfyItem: any) { return { type: GifTypes.SEARCH_BY_ID_SUCCESS, payload: { gfyId, gfyItem, }, }; } export function errorSearchById(err: any, gfyId: string) { return { type: GifTypes.SEARCH_BY_ID_FAILURE, err, gfyId, }; } export function searchScrollPosition(scrollPosition: number) { return { type: GifTypes.SAVE_SEARCH_SCROLL_POSITION, scrollPosition, }; } export function searchPriorLocation(priorLocation: number) { return { type: GifTypes.SAVE_SEARCH_PRIOR_LOCATION, priorLocation, }; } export function searchGfycat({searchText, count = 30, startIndex = 0}: { searchText: string; count?: number; startIndex?: number}) { let start = startIndex; return (dispatch: DispatchFunc, getState: GetStateFunc) => { const {GfycatApiKey, GfycatApiSecret} = getState().entities.general.config; const {resultsByTerm} = getState().entities.gifs.search; if (resultsByTerm[searchText]) { start = resultsByTerm[searchText].start + count; } dispatch(requestSearch(searchText)); const sdk = gfycatSdk(GfycatApiKey!, GfycatApiSecret!); sdk.authenticate(); return sdk.search({search_text: searchText, count, start}).then((json: any) => { if (json.errorMessage) { // There was no results before if (resultsByTerm[searchText].items) { dispatch(receiveSearchEnd(searchText)); } else { dispatch(errorSearching(json, searchText)); } } else { dispatch(updateSearchText(searchText)); dispatch(cacheGifsRequest(json.gfycats)); dispatch(receiveSearch({searchText, count, start, json})); const context = getState().entities.gifs.categories.tagsDict[searchText] ? 'category' : 'search'; Client4.trackEvent( 'gfycat', 'views', {context, count: json.gfycats.length, keyword: searchText}, ); } }).catch( (err: any) => dispatch(errorSearching(err, searchText)), ); }; } export function searchCategory({tagName = '', gfyCount = 30, cursorPos = undefined}) { let cursor = cursorPos; return async (dispatch: DispatchFunc, getState: GetStateFunc) => { const {GfycatApiKey, GfycatApiSecret} = getState().entities.general.config; const {resultsByTerm} = getState().entities.gifs.search; if (resultsByTerm[tagName]) { cursor = resultsByTerm[tagName].cursor; } dispatch(requestSearch(tagName)); return gfycatSdk(GfycatApiKey!, GfycatApiSecret!).getTrendingCategories({tagName, gfyCount, cursor}).then( (json: any) => { if (json.errorMessage) { if (resultsByTerm[tagName].gfycats) { dispatch(receiveSearchEnd(tagName)); } else { dispatch(errorSearching(json, tagName)); } } else { dispatch(updateSearchText(tagName)); dispatch(cacheGifsRequest(json.gfycats)); dispatch(receiveCategorySearch({tagName, json})); Client4.trackEvent( 'gfycat', 'views', {context: 'category', count: json.gfycats.length, keyword: tagName}, ); // preload categories list if (tagName === 'trending') { dispatch(requestCategoriesListIfNeeded() as any); } } }, ).catch((err: any) => dispatch(errorSearching(err, tagName))); }; } export function shouldSearch(state: GlobalState, searchText: string) { const resultsByTerm = state.entities.gifs.search.resultsByTerm[searchText]; if (!resultsByTerm) { return true; } else if (resultsByTerm.isFetching) { return false; } else if (resultsByTerm.moreRemaining) { return true; } return resultsByTerm.didInvalidate; } export function searchIfNeeded(searchText: string) { return (dispatch: DispatchFunc, getState: GetStateFunc) => { if (shouldSearch(getState(), searchText)) { if (searchText.toLowerCase() === 'trending') { return dispatch(searchCategory({tagName: searchText})); } return dispatch(searchGfycat({searchText})); } return Promise.resolve(); }; } export function searchIfNeededInitial(searchText: string) { return (dispatch: DispatchFunc, getState: GetStateFunc) => { dispatch(updateSearchText(searchText)); if (shouldSearchInitial(getState(), searchText)) { if (searchText.toLowerCase() === 'trending') { return dispatch(searchCategory({tagName: searchText})); } return dispatch(searchGfycat({searchText})); } return Promise.resolve(); }; } export function shouldSearchInitial(state: GlobalState, searchText: string) { const resultsByTerm = state.entities.gifs.search.resultsByTerm[searchText]; if (!resultsByTerm) { return true; } else if (resultsByTerm.isFetching) { return false; } return false; } export function searchById(gfyId: string) { return (dispatch: DispatchFunc, getState: GetStateFunc) => { const {GfycatApiKey, GfycatApiSecret} = getState().entities.general.config; dispatch(requestSearchById(gfyId)); return gfycatSdk(GfycatApiKey!, GfycatApiSecret!).searchById({id: gfyId}).then( (response: any) => { dispatch(receiveSearchById(gfyId, response.gfyItem)); dispatch(cacheGifsRequest([response.gfyItem])); }, ).catch((err: any) => dispatch(errorSearchById(err, gfyId))); }; } export function shouldSearchById(state: GlobalState, gfyId: string) { return !state.entities.gifs.cache.gifs[gfyId]; //TODO investigate, used to be !state.cache.gifs[gfyId]; } export function searchByIdIfNeeded(gfyId: string) { return (dispatch: DispatchFunc, getState: GetStateFunc) => { if (shouldSearchById(getState(), gfyId)) { return dispatch(searchById(gfyId)); } return Promise.resolve(getState().entities.gifs.cache.gifs[gfyId]); //TODO: investigate, used to be getState().cache.gifs[gfyId] }; } export function saveSearchScrollPosition(scrollPosition: number) { return (dispatch: DispatchFunc) => { dispatch(searchScrollPosition(scrollPosition)); }; } export function saveSearchPriorLocation(priorLocation: number) { return (dispatch: DispatchFunc) => { dispatch(searchPriorLocation(priorLocation)); }; } export function searchTextUpdate(searchText: string) { return (dispatch: DispatchFunc) => { dispatch(updateSearchText(searchText)); }; } export function saveSearchBarText(searchBarText: string) { return (dispatch: DispatchFunc) => { dispatch(searchBarTextSave(searchBarText)); }; } // CATEGORIES export function categoriesListRequest() { return { type: GifTypes.REQUEST_CATEGORIES_LIST, }; } export function categoriesListReceived(json: any) { return { type: GifTypes.CATEGORIES_LIST_RECEIVED, ...json, }; } export function categoriesListFailure(err: any) { return { type: GifTypes.CATEGORIES_LIST_FAILURE, err, }; } export function requestCategoriesList({count = 60} = {}) { return (dispatch: DispatchFunc, getState: GetStateFunc) => { const {GfycatApiKey, GfycatApiSecret} = getState().entities.general.config; const state = getState().entities.gifs.categories; if (!shouldRequestCategoriesList(state)) { return Promise.resolve(); } dispatch(categoriesListRequest()); const {cursor} = state; const options = { ...(count && {count}), ...(cursor && {cursor}), }; return gfycatSdk(GfycatApiKey!, GfycatApiSecret!).getCategories(options).then((json: any) => { const newGfycats = json.tags.reduce((gfycats: any[], tag: any) => { if (tag.gfycats[0] && tag.gfycats[0].width) { return [...gfycats, ...tag.gfycats]; } return gfycats; }, []); dispatch(cacheGifsRequest(newGfycats)); dispatch(categoriesListReceived(json)); }).catch( (err: any) => { dispatch(categoriesListFailure(err)); }, ); }; } export function requestCategoriesListIfNeeded({ count, } = {count: undefined}) { return (dispatch: DispatchFunc, getState: GetStateFunc) => { const state = getState().entities.gifs.categories; if (state.tagsList && state.tagsList.length) { return Promise.resolve(); } return dispatch(requestCategoriesList({count})); }; } export function shouldRequestCategoriesList(state: {hasMore: boolean; isFetching: boolean; tagsList: any[]}) { const {hasMore, isFetching, tagsList} = state; if (!tagsList || !tagsList.length) { return true; } else if (isFetching) { return false; } else if (hasMore) { return true; } return false; } // CACHE export function cacheRequest() { return { type: GifTypes.CACHE_REQUEST, payload: { updating: true, }, }; } export function cacheGifs(gifs: any) { return { type: GifTypes.CACHE_GIFS, gifs, }; } export function cacheGifsRequest(gifs: any) { return async (dispatch: DispatchFunc) => { dispatch(cacheRequest()); dispatch(cacheGifs(gifs)); return {data: true}; }; }
the_stack
function test_version() { var version: string = JsHamcrest.version; } // // Descriptions // function test_append() { new JsHamcrest.Description().append("foo"); } function test_appendDescriptionOf_acceptsSelfDescribingType() { var obj: JsHamcrest.SelfDescribing; new JsHamcrest.Description().appendDescriptionOf(obj); } function test_appendDescriptionOf_acceptsObjectWithDescribeToMethod() { var obj: any = { describeTo(description: JsHamcrest.Description): void { description.append('obj'); } } new JsHamcrest.Description().appendDescriptionOf(obj); } function test_appendList() { new JsHamcrest.Description().appendList("[", ",", "]", [1, 2, 3]); } function test_appendLiteral() { new JsHamcrest.Description().appendLiteral(undefined); new JsHamcrest.Description().appendLiteral(null); new JsHamcrest.Description().appendLiteral(true); new JsHamcrest.Description().appendLiteral(42); new JsHamcrest.Description().appendLiteral(3.14159); new JsHamcrest.Description().appendLiteral("foo"); new JsHamcrest.Description().appendLiteral([1, 2, 3]); new JsHamcrest.Description().appendLiteral(JsHamcrest.Description); } function test_appendValueList() { var obj: JsHamcrest.SelfDescribing; new JsHamcrest.Description().appendValueList("[", ",", "]", [obj, obj, obj]); } function test_get() { var desc: string = new JsHamcrest.Description().get(); } // // Matcher // function test_SimpleMatcher(actual: any, matcher: JsHamcrest.SimpleMatcher): JsHamcrest.Description { var description = new JsHamcrest.Description(); description.append('Expected '); matcher.describeTo(description); if (!matcher.matches(actual)) { description.append(', but was '); matcher.describeValueTo(actual, description); description.append(': FAIL'); } else { description.append(': PASS'); } return description; } function test_CombinableMatcher(matcher: JsHamcrest.CombinableMatcher): JsHamcrest.CombinableMatcher { return matcher.and(not(string())).or(bool()); } // // Helpers // function test_isMatcher() { JsHamcrest.isMatcher(empty()); } function test_EqualTo() { var hasSecondCharacter = JsHamcrest.EqualTo(function (matcher: JsHamcrest.Matcher) { return new JsHamcrest.SimpleMatcher({ matches: function (actual: any) { return actual && actual.length >= 2 && matcher.matches(actual.charAt(2)); }, describeTo: function (description: JsHamcrest.Description) { description.append('string with second character ').appendDescriptionOf(matcher); } }); }); assertThat('foo', hasSecondCharacter('o')); assertThat('foo', hasSecondCharacter(greaterThan('n'))); } // // Operators // function test_assert() { // truthiness JsHamcrest.Operators.assert('foo'); // basic equality JsHamcrest.Operators.assert('foo', 'foo'); // matcher JsHamcrest.Operators.assert('foo', is('foo')); // options JsHamcrest.Operators.assert('foo', is('foo'), { message: 'Name', pass: function (result) { alert('[PASS] ' + result); }, fail: function (result) { alert('[FAIL] ' + result); } }); } function test_filter() { var evens = JsHamcrest.Operators.filter([1, 2, 3, 4, 5], even()); } function test_callTo() { var thrower = JsHamcrest.Operators.callTo(function (ok) { if (!ok) { throw new Error(); } }, false); } // // Collection Matchers // function test_empty() { assertThat([], empty()); assertThat('', empty()); } function test_everyItem() { assertThat([1,2,3], everyItem(greaterThan(0))); assertThat([1,'1'], everyItem(1)); } function test_hasItem() { assertThat([1,2,3], hasItem(equalTo(3))); assertThat([1,2,3], hasItem(3)); } function test_hasItems() { assertThat([1,2,3], hasItems(2,3)); assertThat([1,2,3], hasItems(greaterThan(2))); assertThat([1,2,3], hasItems(1, greaterThan(2))); } function test_hasSize() { assertThat([1,2,3], hasSize(3)); assertThat([1,2,3], hasSize(lessThan(5))); assertThat('string', hasSize(6)); assertThat('string', hasSize(greaterThan(3))); assertThat({a:1, b:2}, hasSize(equalTo(2))); } function test_isIn() { assertThat(1, isIn([1,2,3])); assertThat(1, isIn(1,2,3)); } function test_oneOf() { assertThat(1, oneOf([1,2,3])); assertThat(1, oneOf(1,2,3)); } // // Core Matchers // function test_allOf() { assertThat(5, allOf([greaterThan(0), lessThan(10)])); assertThat(5, allOf([5, lessThan(10)])); assertThat(5, allOf(greaterThan(0), lessThan(10))); assertThat(5, allOf(5, lessThan(10))); } function test_anyOf() { assertThat(5, anyOf([even(), greaterThan(2)])); assertThat(5, anyOf(even(), greaterThan(2))); } function test_both() { assertThat(10, both(greaterThan(5)).and(even())); } function test_either() { assertThat(10, either(greaterThan(50)).or(even())); } function test_equalTo() { assertThat('10', equalTo(10)); } function test_is() { assertThat('10', is(10)); assertThat('10', is(equalTo(10))); } function test_nil() { assertThat(undefined, nil()); assertThat(null, nil()); } function test_not() { assertThat(10, not(20)); assertThat(10, not(is(20))); } function test_raises() { var myFunction = function() { // Do something dangerous... throw new Error(); }; assertThat(myFunction, raises('Error')); } function test_raisesAnything() { var myFunction = function() { // Do something dangerous... throw 'Some unexpected error'; }; assertThat(myFunction, raisesAnything()); } function test_sameAs() { var number = 10, anotherNumber = number; assertThat(number, sameAs(anotherNumber)); } function test_truth() { assertThat(10, truth()); assertThat({}, truth()); assertThat(0, not(truth())); assertThat('', not(truth())); assertThat(null, not(truth())); assertThat(undefined, not(truth())); } // // Number Matchers // function test_between() { assertThat(5, between(4).and(7)); } function test_closeTo() { assertThat(0.5, closeTo(1.0, 0.5)); assertThat(1.0, closeTo(1.0, 0.5)); assertThat(1.5, closeTo(1.0, 0.5)); assertThat(2.0, not(closeTo(1.0, 0.5))); } function test_divisibleBy() { assertThat(21, divisibleBy(3)); } function test_even() { assertThat(4, even()); } function test_greaterThan() { assertThat(10, greaterThan(5)); } function test_greaterThanOrEqualTo() { assertThat(10, greaterThanOrEqualTo(5)); } function test_lessThan() { assertThat(5, lessThan(10)); } function test_lessThanOrEqualTo() { assertThat(5, lessThanOrEqualTo(10)); } function test_notANumber() { assertThat(Math.sqrt(-1), notANumber()); } function test_zero() { assertThat(0, zero()); assertThat('0', not(zero())); } // // Object Matchers // function test_bool() { assertThat(true, bool()); assertThat(false, bool()); assertThat("text", not(bool())); } function test_func() { assertThat(function() {}, func()); assertThat("text", not(func())); } function test_hasFunction() { var greeter = { sayHello: function(name: string) { alert('Hello, ' + name); } }; assertThat(greeter, hasFunction('sayHello')); } function test_hasMember() { var greeter = { marco: 'polo', sayHello: function(name: string) { alert('Hello, ' + name); } }; assertThat(greeter, hasMember('marco')); assertThat(greeter, hasMember('sayHello')); assertThat(greeter, hasMember('marco', equalTo('polo'))); } function test_instanceOf() { assertThat([], instanceOf(Array)); } function test_number() { assertThat(10, number()); assertThat('10', not(number())); } function test_object() { assertThat({}, object()); assertThat(10, not(object())); } function test_string() { assertThat('10', string()); assertThat(10, not(string())); } function test_typeOf() { assertThat(10, typeOf('number')); assertThat({}, typeOf('object')); assertThat('10', typeOf('string')); assertThat(function(){}, typeOf('function')); } // // Text Matchers // function test_containsString() { assertThat('string', containsString('tri')); } function test_emailAddress() { assertThat('user@domain.com', emailAddress()); } function test_endsWith() { assertThat('string', endsWith('ring')); } function test_equalIgnoringCase() { assertThat('str', equalIgnoringCase('Str')); } function test_matches() { assertThat('0xa4f2c', matches(/\b0[xX][0-9a-fA-F]+\b/)); } function test_startsWith() { assertThat('string', startsWith('str')); } // // Integration // JsHamcrest.Integration.copyMembers(window); JsHamcrest.Integration.copyMembers(JsHamcrest.Matchers, window); JsHamcrest.Integration.installMatchers({ truthy: JsHamcrest.Matchers.truth }); JsHamcrest.Integration.installOperators({ assertNotThat: function (actual: any, matcher: JsHamcrest.Matcher, message?: string): JsHamcrest.Description { return JsHamcrest.Operators.assert(actual, JsHamcrest.Matchers.not(matcher), { message: message }); } }); // // Testing Frameworks // JsHamcrest.Integration.WebBrowser(); JsHamcrest.Integration.Rhino(); JsHamcrest.Integration.JsTestDriver(); JsHamcrest.Integration.JsTestDriver({ scope: window }); JsHamcrest.Integration.Nodeunit(); JsHamcrest.Integration.Nodeunit({ scope: window }); JsHamcrest.Integration.JsUnitTest(); JsHamcrest.Integration.JsUnitTest({ scope: window }); JsHamcrest.Integration.YUITest(); JsHamcrest.Integration.YUITest({ scope: window }); JsHamcrest.Integration.QUnit(); JsHamcrest.Integration.QUnit({ scope: window }); JsHamcrest.Integration.jsUnity(); JsHamcrest.Integration.jsUnity({ scope: window }); JsHamcrest.Integration.jsUnity({ attachAssertions: true }); JsHamcrest.Integration.jsUnity({ scope: window, attachAssertions: true }); JsHamcrest.Integration.screwunit(); JsHamcrest.Integration.screwunit({ scope: window }); JsHamcrest.Integration.jasmine(); JsHamcrest.Integration.jasmine({ scope: window });
the_stack
import { assert } from "chai"; import { getBSU, getSASConnectionStringFromEnvironment, recorderEnvSetup, getSoftDeleteBSU, getGenericBSU } from "./utils"; import { record, delay, Recorder, isLiveMode } from "@azure-tools/test-recorder"; import * as dotenv from "dotenv"; import { ShareServiceClient, ShareItem, ShareRootSquash } from "../src"; import { Context } from "mocha"; dotenv.config(); describe("FileServiceClient", () => { let recorder: Recorder; beforeEach(function(this: Context) { recorder = record(this, recorderEnvSetup); }); afterEach(async function() { await recorder.stop(); }); it("ListShares with default parameters", async () => { const serviceClient = getBSU(); const result = ( await serviceClient .listShares() .byPage() .next() ).value; assert.ok(typeof result.requestId); assert.ok(result.requestId!.length > 0); assert.ok(typeof result.version); assert.ok(result.version!.length > 0); assert.ok(result.serviceEndpoint.length > 0); assert.ok(result.shareItems!.length >= 0); if (result.shareItems!.length > 0) { const share = result.shareItems![0]; assert.ok(share.name.length > 0); assert.ok(share.properties.etag.length > 0); assert.ok(share.properties.lastModified); } }); it("listShares with default parameters - empty prefix should not cause an error", async () => { const serviceClient = getBSU(); const result = ( await serviceClient .listShares({ prefix: "" }) .byPage() .next() ).value; assert.ok(typeof result.requestId); assert.ok(result.requestId!.length > 0); assert.ok(typeof result.version); assert.ok(result.version!.length > 0); assert.ok(result.serviceEndpoint.length > 0); assert.ok(result.shareItems!.length >= 0); if (result.shareItems!.length > 0) { const share = result.shareItems![0]; assert.ok(share.name.length > 0); assert.ok(share.properties.etag.length > 0); assert.ok(share.properties.lastModified); } }); it("ListShares with all parameters configured", async () => { const serviceClient = getBSU(); const shareNamePrefix = recorder.getUniqueName("share"); const shareName1 = `${shareNamePrefix}x1`; const shareName2 = `${shareNamePrefix}x2`; const shareClient1 = serviceClient.getShareClient(shareName1); const shareClient2 = serviceClient.getShareClient(shareName2); await shareClient1.create({ metadata: { key: "val" } }); await shareClient2.create({ metadata: { key: "val" } }); const iter = serviceClient .listShares({ includeMetadata: true, includeSnapshots: true, prefix: shareNamePrefix }) .byPage({ maxPageSize: 1 }); let res = await iter.next(); let result1 = res.value; while (!result1.shareItems && !res.done) { res = await iter.next(); result1 = res.value; } assert.ok(result1.shareItems); assert.ok(result1.continuationToken); assert.equal(result1.shareItems!.length, 1); assert.ok(result1.shareItems![0].name.startsWith(shareNamePrefix)); assert.ok(result1.shareItems![0].properties.etag.length > 0); assert.ok(result1.shareItems![0].properties.lastModified); assert.deepEqual(result1.shareItems![0].metadata!.key, "val"); const result2 = ( await serviceClient .listShares({ includeMetadata: true, includeSnapshots: true, prefix: shareNamePrefix }) .byPage({ continuationToken: result1.continuationToken, maxPageSize: 1 }) .next() ).value; assert.ok(!result2.continuationToken); assert.equal(result2.shareItems!.length, 1); assert.ok(result2.shareItems![0].name.startsWith(shareNamePrefix)); assert.ok(result2.shareItems![0].properties.etag.length > 0); assert.ok(result2.shareItems![0].properties.lastModified); assert.deepEqual(result2.shareItems![0].metadata!.key, "val"); await shareClient1.delete(); await shareClient2.delete(); }); it("Verify PagedAsyncIterableIterator for listShares", async () => { const serviceClient = getBSU(); const shareNamePrefix = recorder.getUniqueName("share"); const shareName1 = `${shareNamePrefix}x1`; const shareName2 = `${shareNamePrefix}x2`; const shareClient1 = serviceClient.getShareClient(shareName1); const shareClient2 = serviceClient.getShareClient(shareName2); await shareClient1.create({ metadata: { key: "val" } }); await shareClient2.create({ metadata: { key: "val" } }); for await (const item of serviceClient.listShares({ includeMetadata: true, includeSnapshots: true, prefix: shareNamePrefix })) { assert.ok(item.name.startsWith(shareNamePrefix)); assert.ok(item.properties.etag.length > 0); assert.ok(item.properties.lastModified); assert.deepEqual(item.metadata!.key, "val"); } await shareClient1.delete(); await shareClient2.delete(); }); it("Verify PagedAsyncIterableIterator(generator .next() syntax) for listShares", async () => { const serviceClient = getBSU(); const shareNamePrefix = recorder.getUniqueName("share"); const shareName1 = `${shareNamePrefix}x1`; const shareName2 = `${shareNamePrefix}x2`; const shareClient1 = serviceClient.getShareClient(shareName1); const shareClient2 = serviceClient.getShareClient(shareName2); await shareClient1.create({ metadata: { key: "val" } }); await shareClient2.create({ metadata: { key: "val" } }); const iter = serviceClient.listShares({ includeMetadata: true, includeSnapshots: true, prefix: shareNamePrefix }); let shareItem = await iter.next(); assert.ok(shareItem.value.name.startsWith(shareNamePrefix)); assert.ok(shareItem.value.properties.etag.length > 0); assert.ok(shareItem.value.properties.lastModified); assert.deepEqual(shareItem.value.metadata!.key, "val"); shareItem = await iter.next(); assert.ok(shareItem.value.name.startsWith(shareNamePrefix)); assert.ok(shareItem.value.properties.etag.length > 0); assert.ok(shareItem.value.properties.lastModified); assert.deepEqual(shareItem.value.metadata!.key, "val"); await shareClient1.delete(); await shareClient2.delete(); }); it("Verify PagedAsyncIterableIterator(byPage()) for listShares", async () => { const shareClients = []; const serviceClient = getBSU(); const shareNamePrefix = recorder.getUniqueName("share"); for (let i = 0; i < 4; i++) { const shareClient = serviceClient.getShareClient(`${shareNamePrefix}x${i}`); await shareClient.create({ metadata: { key: "val" } }); shareClients.push(shareClient); } for await (const response of serviceClient .listShares({ includeMetadata: true, includeSnapshots: true, prefix: shareNamePrefix }) .byPage({ maxPageSize: 2 })) { for (const item of response.shareItems!) { assert.ok(item.name.startsWith(shareNamePrefix)); assert.ok(item.properties.etag.length > 0); assert.ok(item.properties.lastModified); assert.deepEqual(item.metadata!.key, "val"); } } for (const shareClient of shareClients) { await shareClient.delete(); } }); it("Verify PagedAsyncIterableIterator(byPage() - continuationToken) for listShares", async () => { const shareClients = []; const serviceClient = getBSU(); const shareNamePrefix = recorder.getUniqueName("share"); for (let i = 0; i < 4; i++) { const shareClient = serviceClient.getShareClient(`${shareNamePrefix}x${i}`); await shareClient.create({ metadata: { key: "val" } }); shareClients.push(shareClient); } let iter = serviceClient .listShares({ includeMetadata: true, includeSnapshots: true, prefix: shareNamePrefix }) .byPage({ maxPageSize: 2 }); let res = await iter.next(); let response = res.value; while (!response.shareItems && !res.done) { res = await iter.next(); response = res.value; } assert.ok(response.shareItems); // Gets 2 shares for (const item of response.shareItems!) { assert.ok(item.name.startsWith(shareNamePrefix)); assert.ok(item.properties.etag.length > 0); assert.ok(item.properties.lastModified); assert.deepEqual(item.metadata!.key, "val"); } // Gets next marker const marker = response.continuationToken; iter = serviceClient .listShares({ includeMetadata: true, includeSnapshots: true, prefix: shareNamePrefix }) .byPage({ continuationToken: marker, maxPageSize: 2 }); response = (await iter.next()).value; // Gets 2 shares for (const item of response.shareItems!) { assert.ok(item.name.startsWith(shareNamePrefix)); assert.ok(item.properties.etag.length > 0); assert.ok(item.properties.lastModified); assert.deepEqual(item.metadata!.key, "val"); } for (const shareClient of shareClients) { await shareClient.delete(); } }); it("GetProperties", async () => { const serviceClient = getBSU(); const result = await serviceClient.getProperties(); assert.ok(typeof result.requestId); assert.ok(result.requestId!.length > 0); assert.ok(typeof result.version); assert.ok(result.version!.length > 0); if (result.cors && result.cors!.length > 0) { assert.ok(result.cors![0].allowedHeaders.length > 0); assert.ok(result.cors![0].allowedMethods.length > 0); assert.ok(result.cors![0].allowedOrigins.length > 0); assert.ok(result.cors![0].exposedHeaders.length > 0); assert.ok(result.cors![0].maxAgeInSeconds >= 0); } }); it("SetProperties", async () => { const serviceClient = getBSU(); const serviceProperties = await serviceClient.getProperties(); serviceProperties.minuteMetrics = { enabled: true, includeAPIs: true, retentionPolicy: { days: 4, enabled: true }, version: "1.0" }; serviceProperties.hourMetrics = { enabled: true, includeAPIs: true, retentionPolicy: { days: 3, enabled: true }, version: "1.0" }; const newCORS = { allowedHeaders: "*", allowedMethods: "GET", allowedOrigins: "example.com", exposedHeaders: "*", maxAgeInSeconds: 8888 }; if (!serviceProperties.cors) { serviceProperties.cors = [newCORS]; } else if (serviceProperties.cors!.length < 5) { serviceProperties.cors.push(newCORS); } // SMB multi-channel is returned by getProperties() even when the feature is not supproted on the account. const newServiceProperties = { cors: serviceProperties.cors, minuteMetrics: serviceProperties.minuteMetrics, hourMetrics: serviceProperties.hourMetrics }; await serviceClient.setProperties(newServiceProperties); await delay(5 * 1000); const result = await serviceClient.getProperties(); assert.ok(typeof result.requestId); assert.ok(result.requestId!.length > 0); assert.ok(typeof result.version); assert.ok(result.version!.length > 0); assert.deepEqual(result.hourMetrics, serviceProperties.hourMetrics); }); it("createShare and deleteShare", async () => { const serviceClient = getBSU(); const shareName = recorder.getUniqueName("share"); const metadata = { key: "value" }; const { shareClient } = await serviceClient.createShare(shareName, { metadata }); const result = await shareClient.getProperties(); assert.deepEqual(result.metadata, metadata); await serviceClient.deleteShare(shareName); try { await shareClient.getProperties(); assert.fail( "Expecting an error in getting properties from a deleted block blob but didn't get one." ); } catch (error) { assert.ok((error.statusCode as number) === 404); } }); it("can be created from a sas connection string", async () => { const newClient = ShareServiceClient.fromConnectionString( getSASConnectionStringFromEnvironment() ); const result = await newClient.getProperties(); assert.ok(typeof result.requestId); assert.ok(result.requestId!.length > 0); }); it("can be created from a sas connection string and an option bag", async () => { const newClient = ShareServiceClient.fromConnectionString( getSASConnectionStringFromEnvironment(), { retryOptions: { maxTries: 5 } } ); const result = await newClient.getProperties(); assert.ok(typeof result.requestId); assert.ok(result.requestId!.length > 0); }); }); describe("FileServiceClient", () => { let recorder: Recorder; let serviceClient: ShareServiceClient; beforeEach(function(this: Context) { recorder = record(this, recorderEnvSetup); try { serviceClient = getSoftDeleteBSU(); } catch (error) { this.skip(); } }); afterEach(async function() { await recorder.stop(); }); it("ListShares with deleted share", async function() { const shareClient = serviceClient.getShareClient(recorder.getUniqueName("share")); await shareClient.create(); await shareClient.delete(); let found = false; for await (const share of serviceClient.listShares({ includeDeleted: true })) { if (share.name === shareClient.name) { found = true; assert.ok(share.version); assert.ok(share.deleted); } } assert.ok(found); }); it("Undelete share positive", async function() { const shareClient = serviceClient.getShareClient(recorder.getUniqueName("share")); await shareClient.create(); await shareClient.delete(); let found = false; let shareDeleted: ShareItem | undefined; for await (const share of serviceClient.listShares({ includeDeleted: true })) { if (share.name === shareClient.name) { found = true; assert.ok(share.version); assert.ok(share.deleted); assert.ok(share.properties.deletedTime); assert.ok(share.properties.remainingRetentionDays); shareDeleted = share; } } assert.ok(found); assert.ok(shareDeleted); // Await share to be deleted. await delay(30 * 1000); const restoredShareClient = await serviceClient.undeleteShare( shareDeleted!.name, shareDeleted!.version! ); await restoredShareClient.getProperties(); await restoredShareClient.delete(); }); it("Undelete share negative", async function() { const shareClient = serviceClient.getShareClient(recorder.getUniqueName("share")); const invalidVersion = "01D60F8BB59A4652"; try { await serviceClient.undeleteShare(shareClient.name, invalidVersion); assert.fail("Expecting an error in undelete share with invalid version."); } catch (error) { assert.ok((error.statusCode as number) === 404); } }); }); describe("FileServiceClient Premium", () => { let recorder: Recorder; let serviceClient: ShareServiceClient; beforeEach(function(this: Context) { recorder = record(this, recorderEnvSetup); try { serviceClient = getGenericBSU("PREMIUM_FILE_"); } catch (error) { console.log(error); this.skip(); } }); afterEach(async function() { await recorder.stop(); }); it("SMB Multichannel", async function(this: Context) { if (isLiveMode()) { // Skipped for now as it needs be enabled on the account. this.skip(); } await serviceClient.setProperties({ protocol: { smb: { multichannel: { enabled: true } } } }); const propertiesSet = await serviceClient.getProperties(); assert.ok(propertiesSet.protocol?.smb?.multichannel); }); it("Share Enable Protocol & Share Squash Root", async function(this: Context) { if (isLiveMode()) { // Skipped for now as this feature is not available in our test account's region yet. this.skip(); } const shareName = recorder.getUniqueName("share"); const shareClient = serviceClient.getShareClient(shareName); // create share let rootSquash: ShareRootSquash = "RootSquash"; await shareClient.create({ protocols: { smbEnabled: true, nfsEnabled: true }, rootSquash }); // get properties const expectedProtocols = { nfsEnabled: true }; const getRes = await shareClient.getProperties(); assert.deepStrictEqual(getRes.protocols, expectedProtocols); assert.deepStrictEqual(getRes.rootSquash, rootSquash); // set properties rootSquash = "AllSquash"; await shareClient.setProperties({ rootSquash }); // list share const shareName1 = recorder.getUniqueName("share1"); const protocols = { smbEnabled: true }; await serviceClient.createShare(shareName1, { protocols }); for await (const share of serviceClient.listShares()) { if (share.name === shareName) { assert.deepStrictEqual(share.properties.protocols, expectedProtocols); assert.deepStrictEqual(share.properties.rootSquash, rootSquash); } else if (share.name === shareName1) { assert.deepStrictEqual(share.properties.protocols, protocols); } } }); it("Premium Share getProperties", async function(this: Context) { if (isLiveMode()) { // Skip this case until the feature is enabled in production. this.skip(); } const shareName = recorder.getUniqueName("share"); const shareClient = serviceClient.getShareClient(shareName); // create share await shareClient.create(); const getRes = await shareClient.getProperties(); assert.ok(getRes.provisionedBandwidthMibps); assert.ok(getRes.quota); }); });
the_stack
import { Event, Emitter, DisposableCollection, path, CancellationToken, CancellationTokenSource, Throttler, } from '@opensumi/ide-utils'; import { IWatcherCallback, IWatchTerminator, IWatcherInfo, ITreeNodeOrCompositeTreeNode, ITreeNode, ICompositeTreeNode, TreeNodeEvent, IWatcherEvent, MetadataChangeType, ITreeWatcher, IMetadataChange, ITree, WatchEvent, TreeNodeType, IAccessibilityInformation, } from '../types'; const { Path } = path; /** * 裁剪数组 * * @param arr 裁剪数组 * @param start 起始位置 * @param deleteCount 删除或替换位置 * @param items 插入的数组 */ export function spliceArray(arr: number[], start: number, deleteCount = 0, items?: number[] | null) { const a = arr.slice(0); a.splice(start, deleteCount, ...(items || [])); return a; } export enum BranchOperatorStatus { EXPANDED = 1, SHRINKED, } export type TreeNodeOrCompositeTreeNode = TreeNode | CompositeTreeNode; export interface IGlobalTreeState { isExpanding: boolean; isLoadingPath: boolean; isRefreshing: boolean; refreshCancelToken: CancellationTokenSource; loadPathCancelToken: CancellationTokenSource; } export interface IOptionalGlobalTreeState { isExpanding?: boolean; isLoadingPath?: boolean; isRefreshing?: boolean; refreshCancelToken?: CancellationTokenSource; loadPathCancelToken?: CancellationTokenSource; } export class TreeNode implements ITreeNode { public static nextId = (() => { let id = 0; return () => id++; })(); public static is(node: any): node is ITreeNode { return !!node && 'depth' in node && 'name' in node && 'path' in node && 'id' in node; } public static getTreeNodeById(id: number) { return TreeNode.idToTreeNode.get(id); } public static getTreeNodeByPath(path: string) { return TreeNode.pathToTreeNode.get(path); } public static setTreeNode(id: number, path: string, node: TreeNode) { TreeNode.idToTreeNode.set(id, node); TreeNode.pathToTreeNode.set(path, node); } public static removeTreeNode(id: number, path: string) { TreeNode.idToTreeNode.delete(id); TreeNode.pathToTreeNode.delete(path); } public static getIdByPath(path: string) { return TreeNode.pathToId.get(path); } public static setIdByPath(path: string, id: number) { return TreeNode.pathToId.set(path, id); } public static getGlobalTreeState(path: string) { const root = path.split(Path.separator).slice(0, 2).join(Path.separator); let state = TreeNode.pathToGlobalTreeState.get(root); if (!state) { state = { isExpanding: false, isLoadingPath: false, isRefreshing: false, refreshCancelToken: new CancellationTokenSource(), loadPathCancelToken: new CancellationTokenSource(), }; } return state; } public static setGlobalTreeState(path: string, updateState: IOptionalGlobalTreeState) { const root = path.split(Path.separator).slice(0, 2).join(Path.separator); let state = TreeNode.pathToGlobalTreeState.get(root); if (!state) { state = { isExpanding: false, isLoadingPath: false, isRefreshing: false, refreshCancelToken: new CancellationTokenSource(), loadPathCancelToken: new CancellationTokenSource(), }; } state = { ...state, ...updateState, }; TreeNode.pathToGlobalTreeState.set(root, state); return state; } public static idToTreeNode: Map<number, ITreeNodeOrCompositeTreeNode> = new Map(); public static pathToTreeNode: Map<string, ITreeNodeOrCompositeTreeNode> = new Map(); public static pathToId: Map<string, number> = new Map(); // 每颗树都只会在根节点上绑定一个可取消的对象,即同个时间点只能存在一个改变树数据结构的事情 public static pathToGlobalTreeState: Map<string, IGlobalTreeState> = new Map(); private _parent: ICompositeTreeNode | undefined; private _metadata: { [key: string]: any; }; private _uid: number; private _disposed: boolean; protected _depth: number; protected _watcher: ITreeWatcher; protected _tree: ITree; protected _visible: boolean; protected constructor( tree: ITree, parent?: ICompositeTreeNode, watcher?: ITreeWatcher, optionalMetadata?: { [key: string]: any }, ) { this._uid = TreeNode.nextId(); this._parent = parent; this._tree = tree; this._disposed = false; this._visible = true; this._metadata = { ...(optionalMetadata || {}) }; this._depth = parent ? parent.depth + 1 : 0; if (watcher) { this._watcher = watcher; } else if (parent) { this._watcher = (parent as any).watcher; } } get disposed() { return this._disposed; } /** * 获取基础信息 */ get depth() { return this._depth; } get parent() { return this._parent; } set parent(node: ICompositeTreeNode | undefined) { this._parent = node; } get type() { return TreeNodeType.TreeNode; } get id() { return this._uid; } set id(id: number) { this._uid = id; } get displayName() { return this.name; } /** * 由于 Tree 对于唯一路径的 path 的依赖 * 在传入 name 值时必须保证其在路径上的唯一性 */ get name() { // 根节点保证路径不重复 if (!this.parent) { return `root_${this.id}`; } return this.getMetadata('name'); } set name(name: string) { this.addMetadata('name', name); } // 节点绝对路径 get path(): string { if (!this.parent) { return new Path(`${Path.separator}${this.name}`).toString(); } return new Path(this.parent.path).join(this.name).toString(); } get accessibilityInformation(): IAccessibilityInformation { return { label: this.name, role: 'treeitem', }; } public getMetadata(withKey: string): any { if (withKey === 'name' && !this._metadata[withKey]) { this._metadata[withKey] = String(TreeNode.nextId()); } return this._metadata[withKey]; } public addMetadata(withKey: string, value: any) { if (!(withKey in this._metadata)) { this._metadata[withKey] = value; this._watcher.notifyDidChangeMetadata(this, { type: MetadataChangeType.Added, key: withKey, prevValue: void 0, value, }); } else { const prevValue = this._metadata[withKey]; this._metadata[withKey] = value; this._watcher.notifyDidChangeMetadata(this, { type: MetadataChangeType.Updated, key: withKey, prevValue, value }); } } public removeMetadata(withKey: string) { if (withKey in this._metadata) { const prevValue = this._metadata[withKey]; delete this._metadata[withKey]; this._watcher.notifyDidChangeMetadata(this, { type: MetadataChangeType.Removed, key: withKey, prevValue, value: void 0, }); } } /** * 这里的move操作可能为移动,也可能为重命名 * * @param {ICompositeTreeNode} to * @param {string} [name=this.name] * @returns * @memberof TreeNode */ public mv(to: ICompositeTreeNode | null, name: string = this.name) { // 一个普通节点必含有父节点,根节点不允许任何操作 const prevParent = this._parent as CompositeTreeNode; if (to === null || !CompositeTreeNode.is(to)) { this._parent = undefined; this.dispose(); return; } const didChangeParent = prevParent !== to; const prevPath = this.path; this._depth = to.depth + 1; if (didChangeParent || name !== this.name) { this.addMetadata('name', name); if (didChangeParent) { this._watcher.notifyWillChangeParent(this, prevParent, to); } if (this.parent) { (this.parent as CompositeTreeNode).unlinkItem(this, true); this._parent = to; (this.parent as CompositeTreeNode).insertItem(this); } if (didChangeParent) { this._watcher.notifyDidChangeParent(this, prevParent, to); } } if (this.path !== prevPath) { this._watcher.notifyDidChangePath(this); } } public get visible(): boolean { return this._visible; } public setVisible(b: boolean): this { this._visible = b; return this; } public dispose() { if (this._disposed) { return; } this._watcher.notifyDidDispose(this); this._disposed = true; } } export class CompositeTreeNode extends TreeNode implements ICompositeTreeNode { private static defaultSortComparator(a: ITreeNodeOrCompositeTreeNode, b: ITreeNodeOrCompositeTreeNode): number { if (a.constructor === b.constructor) { return a.name > b.name ? 1 : a.name < b.name ? -1 : 0; } return CompositeTreeNode.is(a) ? -1 : CompositeTreeNode.is(b) ? 1 : 0; } public static is(node: any): node is ICompositeTreeNode { return !!node && 'children' in node; } public static isRoot(node: any): boolean { return CompositeTreeNode.is(node) && !node.parent; } protected _children: ITreeNodeOrCompositeTreeNode[] | null = null; // 节点的分支数量 private _branchSize: number; private _flattenedBranch: number[] | null; private refreshThrottler: Throttler = new Throttler(); private _lock = false; private watchTerminator: (path: string) => void; public watchEvents: Map<string, IWatcherInfo>; public isExpanded: boolean; protected generatorWatcher() { const emitter = new Emitter<any>(); const onEventChanges: Event<any> = emitter.event; const disposeCollection = new DisposableCollection(); const terminateWatch = (path: string) => { this.watchEvents.delete(path); }; const watcher: ITreeWatcher = { notifyWillProcessWatchEvent: (target: ICompositeTreeNode, event: IWatcherEvent) => { emitter.fire({ type: TreeNodeEvent.WillProcessWatchEvent, args: [target, event] }); }, notifyWillChangeParent: ( target: ITreeNodeOrCompositeTreeNode, prevParent: ICompositeTreeNode, newParent: ICompositeTreeNode, ) => { emitter.fire({ type: TreeNodeEvent.WillChangeParent, args: [target, prevParent, newParent] }); }, notifyDidChangeParent: ( target: ITreeNodeOrCompositeTreeNode, prevParent: ICompositeTreeNode, newParent: ICompositeTreeNode, ) => { emitter.fire({ type: TreeNodeEvent.DidChangeParent, args: [target, prevParent, newParent] }); }, notifyDidDispose: (target: ITreeNodeOrCompositeTreeNode) => { emitter.fire({ type: TreeNodeEvent.DidDispose, args: [target] }); }, notifyDidProcessWatchEvent: (target: ICompositeTreeNode, event: IWatcherEvent) => { emitter.fire({ type: TreeNodeEvent.DidProcessWatchEvent, args: [target, event] }); }, notifyDidChangePath: (target: ITreeNodeOrCompositeTreeNode) => { emitter.fire({ type: TreeNodeEvent.DidChangePath, args: [target] }); }, notifyWillChangeExpansionState: (target: ICompositeTreeNode, nowExpanded: boolean) => { const isVisible = this.isItemVisibleAtSurface(target); emitter.fire({ type: TreeNodeEvent.WillChangeExpansionState, args: [target, nowExpanded, isVisible] }); }, notifyDidChangeExpansionState: (target: ICompositeTreeNode, nowExpanded: boolean) => { const isVisible = this.isItemVisibleAtSurface(target); emitter.fire({ type: TreeNodeEvent.DidChangeExpansionState, args: [target, nowExpanded, isVisible] }); }, notifyDidChangeMetadata: (target: ITreeNode | ICompositeTreeNode, change: IMetadataChange) => { emitter.fire({ type: TreeNodeEvent.DidChangeMetadata, args: [target, change] }); }, notifyDidUpdateBranch: () => { emitter.fire({ type: TreeNodeEvent.BranchDidUpdate, args: [] }); }, notifyWillResolveChildren: (target: ICompositeTreeNode, nowExpanded: boolean) => { emitter.fire({ type: TreeNodeEvent.WillResolveChildren, args: [target, nowExpanded] }); }, notifyDidResolveChildren: (target: ICompositeTreeNode, nowExpanded: boolean) => { emitter.fire({ type: TreeNodeEvent.DidResolveChildren, args: [target, nowExpanded] }); }, // 监听所有事件 on: (event: TreeNodeEvent, callback: any) => { const dispose = onEventChanges((data) => { if (data.type === event) { callback(...data.args); } }); disposeCollection.push(dispose); return dispose; }, // 监听Watch事件变化 onWatchEvent: (path: string, callback: IWatcherCallback): IWatchTerminator => { const terminator: IWatchTerminator = terminateWatch; this.watchEvents.set(path, { terminator, callback }); return terminator; }, dispose: disposeCollection, }; return watcher; } // parent 为undefined即表示该节点为根节点 constructor( tree: ITree, parent: ICompositeTreeNode | undefined, watcher?: ITreeWatcher, optionalMetadata?: { [key: string]: any }, ) { super(tree, parent, watcher, optionalMetadata); this.isExpanded = parent ? false : true; this._branchSize = 0; if (!parent) { this.watchEvents = new Map(); // 为根节点创建监听器 this._watcher = this.generatorWatcher(); TreeNode.setTreeNode(this.id, this.path, this); } else { this._watcher = (parent as any).watcher; } } // 重载 name 的 getter/setter,路径改变时需要重新监听文件节点变化 set name(name: string) { const prevPath = this.path; if (!CompositeTreeNode.isRoot(this) && typeof this.watchTerminator === 'function') { this.watchTerminator(prevPath); this.addMetadata('name', name); this.watchTerminator = this.watcher.onWatchEvent(this.path, this.handleWatchEvent); } else { this.addMetadata('name', name); } } get name() { // 根节点保证路径不重复 if (!this.parent) { return `root_${this.id}`; } return this.getMetadata('name'); } // 作为根节点唯一的watcher需要在生成新节点的时候传入 get watcher() { return this._watcher; } get type() { return TreeNodeType.CompositeTreeNode; } get children() { return this._children; } get expanded() { return this.isExpanded; } /** * 当前可见的分支数量 * * 当节点为展开状态时,其整个分支(递归展平)由上一级的分支(根(位于数据层可见)或处于折叠状态的分支)拥有 * 当节点为折叠状态时,其整个分支(递归展平)由其上一级父目录展开该节点 * * @readonly * @memberof CompositeTreeNode */ get branchSize() { return this._branchSize; } /** * 获取当前节点的分支数,一般为顶层节点,如Root上获取 * * @readonly * @memberof CompositeTreeNode */ get flattenedBranch() { return this._flattenedBranch; } get lock() { return this._lock; } /** * 确保此“目录”的子级已加载(不影响“展开”状态) * 如果子级已经加载,则返回的Promise将立即解决 * 否则,将发出重新加载请求并返回Promise * 一旦返回的Promise.resolve,“CompositeTreeNode#children” 便可以访问到对于节点 */ public async ensureLoaded(token?: CancellationToken) { if (this._children) { return; } return await this.hardReloadChildren(token); } // 展开节点 public async setExpanded(ensureVisible = true, quiet = false, isOwner = true, token?: CancellationToken) { if (this.disposed) { return; } // 根节点不可折叠 if (CompositeTreeNode.isRoot(this)) { return; } if (this.isExpanded) { return; } if (isOwner) { const state = TreeNode.getGlobalTreeState(this.path); state.loadPathCancelToken.cancel(); state.refreshCancelToken.cancel(); TreeNode.setGlobalTreeState(this.path, { isExpanding: true, }); } this.isExpanded = true; if (this._children === null) { this._watcher.notifyWillResolveChildren(this, this.isExpanded); await this.hardReloadChildren(token); this._watcher.notifyDidResolveChildren(this, this.isExpanded); // 检查其是否展开;可能同时执行了 setCollapsed 方法 if (!this.isExpanded || token?.isCancellationRequested) { if (isOwner) { TreeNode.setGlobalTreeState(this.path, { isExpanding: false, }); } return; } } if (ensureVisible && this.parent && CompositeTreeNode.is(this.parent)) { /** * 在传入 ensureVisible = true 时,这里传入的 token 不能取消所有副作用 * 故在使用 ensureVisible = true 时必须保证 `setExpanded` 与 `setCollapsed` 的独立性 * 如需要 `await node.setExpanded(true)` 后再执行 `node.setCollapsed()` */ await (this.parent as CompositeTreeNode).setExpanded(true, !quiet, false, token); } if (token?.isCancellationRequested) { if (isOwner) { TreeNode.setGlobalTreeState(this.path, { isExpanding: false, }); } return; } if (this.isExpanded) { this._watcher.notifyWillChangeExpansionState(this, true); // 与根节点合并分支 this.expandBranch(this, quiet); this._watcher.notifyDidChangeExpansionState(this, true); } if (isOwner) { TreeNode.setGlobalTreeState(this.path, { isExpanding: false, }); } } // 获取当前节点下所有展开的节点路径 private getAllExpandedNodePath() { let paths: string[] = []; if (this.children) { for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; if (CompositeTreeNode.is(child) && (child as CompositeTreeNode).expanded) { paths.push(child.path); paths = paths.concat((child as CompositeTreeNode).getAllExpandedNodePath()); } } return paths; } else { return paths; } } // 获取当前节点下所有折叠的节点路径 private getAllCollapsedNodePath() { let paths: string[] = []; if (this.children) { for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; if (!CompositeTreeNode.is(child)) { continue; } if ((child as CompositeTreeNode).isExpanded) { paths = paths.concat((child as CompositeTreeNode).getAllCollapsedNodePath()); } else { paths.push(child.path); } } return paths; } else { return paths; } } /** * 处理节点数据,让节点重新加载子节点及初始化 flattenedBranch * @param token CancellationToken */ private async resolveChildrens(token?: CancellationToken) { let childrens; try { childrens = (await this._tree.resolveChildren(this)) || []; } catch (e) { childrens = []; } if (token?.isCancellationRequested) { return false; } const flatTree = new Array(childrens.length); this._children = Array(childrens.length); for (let i = 0; i < childrens.length; i++) { const child = childrens[i]; // 如果存在上一次缓存的节点,则使用缓存节点的 ID (child as TreeNode).id = TreeNode.getIdByPath(child.path) || (child as TreeNode).id; this._children[i] = child; TreeNode.setIdByPath(child.path, child.id); } this._children?.sort(this._tree.sortComparator || CompositeTreeNode.defaultSortComparator); for (let i = 0; i < childrens.length; i++) { flatTree[i] = this._children[i].id; } const expandedChilds: CompositeTreeNode[] = []; for (let i = 0; i < (this.children || []).length; i++) { const subChild = this.children![i]; if (CompositeTreeNode.is(subChild) && subChild.expanded) { await (subChild as CompositeTreeNode).resolveChildrens(token); if (token?.isCancellationRequested) { return; } expandedChilds.push(subChild as CompositeTreeNode); } } this._branchSize = flatTree.length; this.setFlattenedBranch(flatTree); for (let i = 0; i < expandedChilds.length; i++) { const child = expandedChilds[i]; child.expandBranch(child, true); } } private updateTreeNodeCache(child: CompositeTreeNode | TreeNode) { TreeNode.setTreeNode(child.id, child.path, child); if (CompositeTreeNode.is(child) && child.expanded && child.children?.length) { for (let i = 0; i < child.children.length; i++) { const subChild = child.children[i]; this.updateTreeNodeCache(subChild as TreeNode | CompositeTreeNode); } } } // 静默刷新子节点, 即不触发分支更新事件 private async refreshTreeNodeByPaths( expandedPaths: string[] = this.getAllExpandedNodePath(), needReload = true, token?: CancellationToken, ) { if (!CompositeTreeNode.is(this)) { return; } // 如果某次刷新操作被取消,则下次刷新依旧使用上一次刷新的展开目录进行刷新 let forceLoadPath; let childrens = this.children || []; if (this.expanded) { if (needReload) { try { childrens = (await this._tree.resolveChildren(this)) || []; } catch (e) { childrens = []; } if (token?.isCancellationRequested) { return; } if (!this.expanded) { // 当请求刷新节点时,如果该节点已经不应该被处理,则清理 Children // 下次再被展开时便会自动更新 Children 最新内容 if (this.children) { // 清理子节点,等待下次展开时更新 if (!!this.children && this.parent) { for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; (child as CompositeTreeNode).dispose(); } this._children = null; } } return; } } while ((forceLoadPath = expandedPaths.shift())) { const isRelative = forceLoadPath.indexOf(`${this.path}${Path.separator}`) > -1; if (!isRelative) { break; } const child = childrens?.find((child) => child.path === forceLoadPath); // 对于压缩情况的路径需要额外处理一下 // 如果这里加载的路径是 a/b/c, 有可能目前只加载到 a/b if (!child) { if (!childrens || childrens.length === 0) { break; } for (let i = 0; i < childrens.length; i++) { const child = childrens[i]; if (forceLoadPath.indexOf(`${child.path}${Path.separator}`) === 0 && CompositeTreeNode.is(child)) { // 包含压缩节点的情况 if (!CompositeTreeNode.is(child) || (child as CompositeTreeNode).expanded) { // 说明此时节点初始化时已默认展开或被裁切,不需要进一步处理 continue; } (child as CompositeTreeNode).isExpanded = true; // 加载路径包含当前判断路径,尝试加载该节点再匹配 await (child as CompositeTreeNode).resolveChildrens(token); if (token?.isCancellationRequested) { return; } if (expandedPaths.length > 0) { // 不需要重新reload压缩节点的子节点内容 await (child as CompositeTreeNode).refreshTreeNodeByPaths(expandedPaths, false, token); if (token?.isCancellationRequested) { return; } } else { (child as CompositeTreeNode).expandBranch(child as CompositeTreeNode, true); } break; } } } else if (CompositeTreeNode.is(child)) { if ((child as CompositeTreeNode).expanded) { // 说明此时节点初始化时已默认展开,需要进一步加载一下节点内容 await (child as CompositeTreeNode).resolveChildrens(token); if (token?.isCancellationRequested) { return; } } else { (child as CompositeTreeNode).isExpanded = true; if (expandedPaths.length > 0) { await (child as CompositeTreeNode).resolveChildrens(token); if (token?.isCancellationRequested) { return; } await (child as CompositeTreeNode).refreshTreeNodeByPaths(expandedPaths, false, token); if (token?.isCancellationRequested) { return; } } else { await (child as CompositeTreeNode).resolveChildrens(token); if (token?.isCancellationRequested) { return; } } } } } if (forceLoadPath) { expandedPaths.unshift(forceLoadPath); if (needReload) { if (this.children) { for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; (child as any).dispose(); } } const expandedChilds: CompositeTreeNode[] = []; const flatTree = new Array(childrens.length); this._children = Array(childrens.length); for (let i = 0; i < childrens.length; i++) { const child = childrens[i]; // 如果存在上一次缓存的节点,则使用缓存节点的 ID (child as TreeNode).id = TreeNode.getIdByPath(child.path) || (child as TreeNode).id; this._children[i] = child; if (CompositeTreeNode.is(child) && child.expanded) { expandedChilds.push(child as CompositeTreeNode); } } this._children.sort(this._tree.sortComparator || CompositeTreeNode.defaultSortComparator); for (let i = 0; i < childrens.length; i++) { flatTree[i] = this._children[i].id; } this._branchSize = flatTree.length; this.setFlattenedBranch(flatTree, true); } this.expandBranch(this, true); } else if (CompositeTreeNode.isRoot(this)) { if (token?.isCancellationRequested) { return; } // 通知节点更新 if (this.children) { // 重置旧的节点分支 this.shrinkBranch(this, true); } if (this.children) { for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; (child as any).dispose(); } } const expandedChilds: CompositeTreeNode[] = []; const otherChilds: CompositeTreeNode[] = []; const flatTree = new Array(childrens.length); this._children = Array(childrens.length); for (let i = 0; i < childrens.length; i++) { const child = childrens[i]; // 如果存在上一次缓存的节点,则使用缓存节点的 ID (child as TreeNode).id = TreeNode.getIdByPath(child.path) || (child as TreeNode).id; this._children[i] = child; TreeNode.setIdByPath(child.path, child.id); if (CompositeTreeNode.is(child) && child.expanded) { if (!child.children) { await (child as CompositeTreeNode).resolveChildrens(token); if (token?.isCancellationRequested) { return; } } expandedChilds.push(child as CompositeTreeNode); } else { otherChilds.push(child as CompositeTreeNode); } } this._children.sort(this._tree.sortComparator || CompositeTreeNode.defaultSortComparator); for (let i = 0; i < childrens.length; i++) { flatTree[i] = this._children[i].id; } this._branchSize = flatTree.length; this.setFlattenedBranch(flatTree, true); for (let i = 0; i < expandedChilds.length; i++) { const child = expandedChilds[i]; child.expandBranch(child, true); this.updateTreeNodeCache(child); } for (let i = 0; i < otherChilds.length; i++) { const child = otherChilds[i]; this.updateTreeNodeCache(child); } // 清理上一次监听函数 if (typeof this.watchTerminator === 'function') { this.watchTerminator(this.path); } this.watchTerminator = this.watcher.onWatchEvent(this.path, this.handleWatchEvent); this.watcher.notifyDidUpdateBranch(); } else { if (token?.isCancellationRequested) { return; } const expandedChilds: CompositeTreeNode[] = []; if (needReload) { // 非根节点刷新的情况 // 通知节点更新 if (this.children) { // 重置旧的节点分支 this.shrinkBranch(this, true); } if (this.children) { for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; (child as TreeNode).dispose(); } } const flatTree = new Array(childrens.length); this._children = Array(childrens.length); for (let i = 0; i < childrens.length; i++) { const child = childrens[i]; (child as TreeNode).id = TreeNode.getIdByPath(child.path) || (child as TreeNode).id; this._children[i] = child; TreeNode.setIdByPath(child.path, child.id); if ((child as CompositeTreeNode).expanded) { expandedChilds.push(child as CompositeTreeNode); } this.updateTreeNodeCache(child as TreeNode | CompositeTreeNode); } this._children.sort(this._tree.sortComparator || CompositeTreeNode.defaultSortComparator); for (let i = 0; i < childrens.length; i++) { flatTree[i] = this._children[i].id; } this._branchSize = flatTree.length; this.setFlattenedBranch(flatTree); } else { for (let i = 0; i < childrens.length; i++) { const child = childrens[i]; if ((child as CompositeTreeNode).expanded) { expandedChilds.push(child as CompositeTreeNode); } } } for (let i = 0; i < expandedChilds.length; i++) { const child = expandedChilds[i]; child.expandBranch(child, true); } // 清理上一次监听函数 if (typeof this.watchTerminator === 'function') { this.watchTerminator(this.path); } this.watchTerminator = this.watcher.onWatchEvent(this.path, this.handleWatchEvent); if (needReload) { this.expandBranch(this); } } } else { // 仅需处理存在子节点的情况,否则将会影响刷新后的节点长度 if (this.children) { // 清理子节点,等待下次展开时更新 if (!!this.children && this.parent) { // eslint-disable-next-line @typescript-eslint/prefer-for-of for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; (child as CompositeTreeNode).dispose(); } this._children = null; } } return; } } public async expandedAll(collapsedPaths: string[] = this.getAllCollapsedNodePath()) { // 仅根节点使用 if (!CompositeTreeNode.isRoot(this)) { return; } collapsedPaths = collapsedPaths.sort((a, b) => Path.pathDepth(a) - Path.pathDepth(b)); let path; while (collapsedPaths.length > 0) { path = collapsedPaths.pop(); const item = TreeNode.getTreeNodeByPath(path); if (CompositeTreeNode.is(item)) { await (item as CompositeTreeNode).setExpanded(false, true); } } // 通知分支树已更新 this.watcher.notifyDidUpdateBranch(); } public async collapsedAll(expandedPaths: string[] = this.getAllExpandedNodePath()) { // 仅根节点使用 if (!CompositeTreeNode.isRoot(this)) { return; } expandedPaths = expandedPaths.sort((a, b) => Path.pathDepth(a) - Path.pathDepth(b)); let path; while (expandedPaths.length > 0) { path = expandedPaths.pop(); const item = TreeNode.getTreeNodeByPath(path); if (CompositeTreeNode.is(item)) { (item as CompositeTreeNode).setCollapsed(true); } } // 通知分支树已更新 this.watcher.notifyDidUpdateBranch(); } // 折叠节点 public setCollapsed(quiet = false) { // 根节点不可折叠 if (CompositeTreeNode.isRoot(this) || this.disposed) { return; } if (!this.isExpanded) { return; } const state = TreeNode.getGlobalTreeState(this.path); state.loadPathCancelToken.cancel(); state.refreshCancelToken.cancel(); this._watcher.notifyWillChangeExpansionState(this, false); if (this._children && this.parent) { // 从根节点裁剪分支 this.shrinkBranch(this, quiet); } this.isExpanded = false; this._watcher.notifyDidChangeExpansionState(this, false); } public mv(to: ICompositeTreeNode, name: string = this.name) { const prevPath = this.path; super.mv(to, name); if (typeof this.watchTerminator === 'function') { this.watchTerminator(prevPath); this.watchTerminator = this.watcher.onWatchEvent(this.path, this.handleWatchEvent); } // 同时移动过子节点 if (this.children) { for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; child.mv(child.parent as ICompositeTreeNode, child.name); } } } /** * 在节点中插入新的节点 * * 直接调用此方法将不会触发onWillHandleWatchEvent和onDidHandleWatchEvent事件 */ public insertItem(item: ITreeNodeOrCompositeTreeNode) { if (item.parent !== this) { item.mv(this, item.name); return; } if (this.children) { for (let i = 0; i < this.children.length; i++) { // path / id 是节点唯一标识 if (this.children[i].path === item.path) { this.children[i] = item; return; } } } const branchSizeIncrease = 1 + (item instanceof CompositeTreeNode && item.expanded ? item._branchSize : 0); if (this._children) { this._children.push(item); this._children.sort(this._tree.sortComparator || CompositeTreeNode.defaultSortComparator); } this._branchSize += branchSizeIncrease; let master: CompositeTreeNode = this; // 如果该节点无叶子节点,则继续往上查找合适的插入位置 while (!master._flattenedBranch) { if (master.parent) { master = master.parent as CompositeTreeNode; master._branchSize += branchSizeIncrease; } } if (!this._children) { return; } let relativeInsertionIndex = this._children!.indexOf(item); let absInsertionIndex; const leadingSibling = this._children![relativeInsertionIndex - 1]; if (leadingSibling) { const siblingIdx = master._flattenedBranch.indexOf(leadingSibling.id); relativeInsertionIndex = siblingIdx + (leadingSibling instanceof CompositeTreeNode && leadingSibling.expanded ? leadingSibling._branchSize : 0); } else { relativeInsertionIndex = master._flattenedBranch.indexOf(this.id); } if (relativeInsertionIndex === -1) { if (this._branchSize === 1) { // 在空Tree中插入节点时,相对插入位置为0 relativeInsertionIndex = 0; } } // 非空Tree情况下需要+1,为了容纳自身节点位置,在插入节点下方插入新增节点 absInsertionIndex = relativeInsertionIndex + 1; // 空 Tree 情况下需要重置为 0,避免设置 Uint32Array 时超出范围 if (master._flattenedBranch.length === 0) { absInsertionIndex = 0; } let branch: number[] = [item.id]; if (item instanceof CompositeTreeNode && item.expanded && item._flattenedBranch) { branch = branch.concat(item._flattenedBranch); (item as CompositeTreeNode).setFlattenedBranch(null); } master.setFlattenedBranch(spliceArray(master._flattenedBranch, absInsertionIndex, 0, branch)); TreeNode.setTreeNode(item.id, item.path, item as TreeNode); return item; } /** * 从父节点中移除节点 * * 直接调用此方法将不会触发onWillHandleWatchEvent和onDidHandleWatchEvent事件 */ public unlinkItem(item: ITreeNodeOrCompositeTreeNode, reparenting?: boolean): void { if (!this._children) { return; } const idx = this._children!.indexOf(item); if (idx === -1) { return; } // 当删除时父节点已不存在界面上时,跳过插入操作 if (!this.isItemVisibleAtRootSurface(this)) { return; } this._children!.splice(idx, 1); const branchSizeDecrease = 1 + (item instanceof CompositeTreeNode && item.expanded ? item._branchSize : 0); this._branchSize -= branchSizeDecrease; // 逐级往上查找节点的父节点,并沿途裁剪分支数 let master: CompositeTreeNode = this; while (!master._flattenedBranch) { if (master.parent) { master = master.parent as CompositeTreeNode; master._branchSize -= branchSizeDecrease; } } const removalBeginIdx = master._flattenedBranch.indexOf(item.id); if (removalBeginIdx === -1) { return; } if (item instanceof CompositeTreeNode && item.expanded) { (item as CompositeTreeNode).setFlattenedBranch( master._flattenedBranch.slice(removalBeginIdx + 1, removalBeginIdx + branchSizeDecrease), ); } master.setFlattenedBranch(spliceArray(master._flattenedBranch, removalBeginIdx, branchSizeDecrease)); if (!reparenting && item.parent === this) { item.mv(null); } } /** * 转换节点路径 */ private transferItem(oldPath: string, newPath: string) { const oldP = new Path(oldPath); const from = oldP.dir.toString(); if (from !== this.path) { return; } const name = oldP.base.toString(); const item = this._children!.find((c) => c.name === name); if (!item) { return; } const newP = new Path(newPath); const to = newP.dir.toString(); const destDir = to === from ? this : TreeNode.getTreeNodeByPath(to); if (!CompositeTreeNode.is(destDir)) { this.unlinkItem(item); return; } item.mv(destDir, newP.base.toString()); return item; } public dispose() { // 如果存在对应文件路径下的监听,同样需要清理掉 if (this.watchEvents) { const watcher = this.watchEvents.get(this.path); if (watcher) { watcher.terminator(); } this.watchEvents.clear(); } if (this._children) { // 移除后应该折叠,因为下次初始化默认值为折叠,否则将会导致下次插入异常 this.isExpanded = false; this._children.forEach((child) => { (child as CompositeTreeNode).dispose(); }); this._children = null; this._flattenedBranch = null; } super.dispose(); } /** * 设置扁平化的分支信息 */ protected setFlattenedBranch(leaves: number[] | null, withoutNotify?: boolean) { this._flattenedBranch = leaves; // Root节点才通知更新 if (CompositeTreeNode.isRoot(this) && !withoutNotify) { this.watcher.notifyDidUpdateBranch(); } } /** * 展开分支节点 * @param branch 分支节点 */ protected expandBranch(branch: CompositeTreeNode, withoutNotify?: boolean) { if (this !== branch) { // 但节点为展开状态时进行裁剪 if (branch._flattenedBranch) { this._branchSize += branch._branchSize; } } // 当前节点为折叠状态,更新分支信息 if (this !== branch && this._flattenedBranch) { const injectionStartIdx = this._flattenedBranch.indexOf(branch.id) + 1; if (injectionStartIdx === 0) { // 中途发生了branch更新事件,此时的_flattenedBranch可能已被更新,即查找不到branch.id // 这种情况在父节点发生了多路径目录的创建定位动作下更易复现 // 例:文件树在执行a/b/c定位操作时需要请求三次数据,而更新操作可能只需要一次 // 导致就算更新操作后置执行,也可能比定位操作先执行完,同时将_flattenedBranch更新 // 最终导致此处查询不到对应节点,下面的shrinkBranch同样可能有相同问题,如点击折叠全部功能时 return; } this.setFlattenedBranch( spliceArray(this._flattenedBranch, injectionStartIdx, 0, branch._flattenedBranch), withoutNotify, ); // 取消展开分支对于分支的所有权,即最终只会有顶部Root拥有所有分支信息 branch.setFlattenedBranch(null, withoutNotify); } else if (this.parent) { (this.parent as CompositeTreeNode).expandBranch(branch, withoutNotify); } } /** * 清理分支节点 * @param branch 分支节点 */ protected shrinkBranch(branch: CompositeTreeNode, withoutNotify?: boolean) { if (this !== branch) { // 这里的`this`实际上为父节点 // `this`的分支大小没有改变,仍然具有相同数量的叶子,但是从父级参照系(即根节点)来看,其分支缩小了 this._branchSize -= branch._branchSize; } if (this !== branch && this._flattenedBranch) { const removalStartIdx = this._flattenedBranch.indexOf(branch.id) + 1; if (removalStartIdx === 0) { // 中途发生了branch更新事件,此时的_flattenedBranch可能已被更新,即查找不到branch.id return; } // 返回分支对于分支信息所有权,即将折叠的节点信息再次存储于折叠了的节点中 branch.setFlattenedBranch( this._flattenedBranch.slice(removalStartIdx, removalStartIdx + branch._branchSize), withoutNotify, ); this.setFlattenedBranch( spliceArray( this._flattenedBranch, removalStartIdx, branch._flattenedBranch ? branch._flattenedBranch.length : 0, ), withoutNotify, ); } else if (this.parent) { (this.parent as CompositeTreeNode).shrinkBranch(branch, withoutNotify); } } /** * 加载子节点信息 * 当返回值为 true 时,正常加载完子节点并同步到数据结构中 * 返回值为 false 时,加载节点的过程被中断 * * @memberof CompositeTreeNode */ public async hardReloadChildren(token?: CancellationToken) { let rawItems; try { rawItems = (await this._tree.resolveChildren(this)) || []; } catch (e) { rawItems = []; } // 当获取到新的子节点时,如果当前节点正处于非展开状态时,忽略后续裁切逻辑 // 后续的 expandBranch 也不应该被响应 if (!this.expanded || token?.isCancellationRequested) { return false; } const expandedChilds: CompositeTreeNode[] = []; const flatTree = new Array(rawItems.length); const tempChildren = new Array(rawItems.length); for (let i = 0; i < rawItems.length; i++) { const child = rawItems[i]; // 如果存在上一次缓存的节点,则使用缓存节点的 ID (child as TreeNode).id = TreeNode.getIdByPath(child.path) || (child as TreeNode).id; tempChildren[i] = child; TreeNode.setIdByPath(child.path, child.id); if (CompositeTreeNode.is(child) && child.expanded) { if (!(child as CompositeTreeNode).children) { await (child as CompositeTreeNode).resolveChildrens(token); } if (token?.isCancellationRequested) { return false; } expandedChilds.push(child as CompositeTreeNode); } } tempChildren.sort(this._tree.sortComparator || CompositeTreeNode.defaultSortComparator); for (let i = 0; i < rawItems.length; i++) { flatTree[i] = tempChildren[i].id; } if (this.children) { // 重置节点分支 this.shrinkBranch(this); } if (this.children) { for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; (child as any).dispose(); } } for (let i = 0; i < tempChildren.length; i++) { this.updateTreeNodeCache(tempChildren[i]); } this._children = tempChildren; this._branchSize = flatTree.length; this.setFlattenedBranch(flatTree); for (let i = 0; i < expandedChilds.length; i++) { const child = expandedChilds[i]; (child as CompositeTreeNode).expandBranch(child, true); } // 清理上一次监听函数 if (typeof this.watchTerminator === 'function') { this.watchTerminator(this.path); } this.watchTerminator = this.watcher.onWatchEvent(this.path, this.handleWatchEvent); return true; } public moveNode(oldPath: string, newPath: string) { if (typeof oldPath !== 'string') { throw new TypeError('Expected oldPath to be a string'); } if (typeof newPath !== 'string') { throw new TypeError('Expected newPath to be a string'); } if (Path.isRelative(oldPath)) { throw new TypeError('oldPath must be absolute'); } if (Path.isRelative(newPath)) { throw new TypeError('newPath must be absolute'); } return this.transferItem(oldPath, newPath); } public addNode(node: TreeNode) { if (!TreeNode.is(node)) { throw new TypeError('Expected node to be a TreeNode'); } return this.insertItem(node); } public removeNode(path: string) { const pathObject = new Path(path); const dirName = pathObject.dir.toString(); const name = pathObject.base.toString(); if (dirName === this.path && !!this.children) { const item = this.children.find((c) => c.name === name); if (item) { this.unlinkItem(item); } } } /** * 处理Watch事件,同时可通过外部手动调 g用节点更新函数进行节点替换,这里为通用的事件管理 * 如: transferItem,insertItem, unlinkItem等 * @private * @memberof CompositeTreeNode */ private handleWatchEvent = async (event: IWatcherEvent) => { this.watcher.notifyWillProcessWatchEvent(this, event); if (event.type === WatchEvent.Moved) { const { oldPath, newPath } = event; if (typeof oldPath !== 'string') { throw new TypeError('Expected oldPath to be a string'); } if (typeof newPath !== 'string') { throw new TypeError('Expected newPath to be a string'); } if (Path.isRelative(oldPath)) { throw new TypeError('oldPath must be absolute'); } if (Path.isRelative(newPath)) { throw new TypeError('newPath must be absolute'); } this.transferItem(oldPath, newPath); } else if (event.type === WatchEvent.Added) { const { node } = event; if (!TreeNode.is(node)) { throw new TypeError('Expected node to be a TreeNode'); } this.insertItem(node); } else if (event.type === WatchEvent.Removed) { const { path } = event; const pathObject = new Path(path); const dirName = pathObject.dir.toString(); const name = pathObject.base.toString(); if (dirName === this.path && !!this.children) { const item = this.children.find((c) => c.name === name); if (item) { this.unlinkItem(item); } } } else { // 如果当前变化的节点已在数据视图(并非滚动到不可见区域)中不可见,则将该节点折叠,待下次更新即可, if (!this.isItemVisibleAtRootSurface(this)) { this.isExpanded = false; this._children = null; } else { // needReload --- 判断根目录是否需要进行一次刷新,部分情况,如压缩目录下的文件创建后不应该刷新 await this.refresh(); } } this.watcher.notifyDidProcessWatchEvent(this, event); }; // 当没有传入具体路径时,使用当前展开目录作为刷新路径 public async refresh() { const state = TreeNode.getGlobalTreeState(this.path); if (state.isLoadingPath || state.isExpanding) { return; } let token; if (state.refreshCancelToken.token.isCancellationRequested) { const refreshCancelToken = new CancellationTokenSource(); TreeNode.setGlobalTreeState(this.path, { isRefreshing: true, refreshCancelToken, }); token = refreshCancelToken.token; } else { token = state.refreshCancelToken.token; } await this.refreshThrottler.queue(async () => this.doRefresh(token)); TreeNode.setGlobalTreeState(this.path, { isRefreshing: false, }); } private async doRefresh(token?: CancellationToken) { const paths = this.getAllExpandedNodePath(); await this.refreshTreeNodeByPaths(paths, true, token); } private isItemVisibleAtRootSurface(node: TreeNode) { let parent: ITreeNodeOrCompositeTreeNode = node; while (parent.parent) { parent = parent.parent; } return (parent as CompositeTreeNode).isItemVisibleAtSurface(node); } /** * 检查节点是否可见,而不是被隐藏在节点中 * * 这里的可见并不表示节点在当前视图中可见,而是在用户滚动到特定位置便可看见 * * 隐藏在节点中可能的原因为其父节点中有一个以上处于折叠状态 */ public isItemVisibleAtSurface(item: ITreeNodeOrCompositeTreeNode): boolean { if (item === this) { return true; } return !!this._flattenedBranch && this._flattenedBranch.indexOf(item.id) > -1; } private transformToRelativePath(path: string): string[] { const { splitPath } = Path; const pathFlag = splitPath(path); pathFlag.shift(); return pathFlag; } /** * 根据路径展开节点树 * @memberof CompositeTreeNode */ public async loadTreeNodeByPath(path: string): Promise<ITreeNodeOrCompositeTreeNode | undefined> { if (!CompositeTreeNode.isRoot(this)) { return; } const state = TreeNode.getGlobalTreeState(this.path); if (state.isExpanding) { return; } state.refreshCancelToken.cancel(); let token; if (state.loadPathCancelToken.token.isCancellationRequested) { const loadPathCancelToken = new CancellationTokenSource(); TreeNode.setGlobalTreeState(this.path, { isLoadingPath: true, loadPathCancelToken, }); token = loadPathCancelToken.token; } else { token = state.loadPathCancelToken.token; } const flattenedBranchChilds: CompositeTreeNode[] = []; const { splitPath, isRelative } = Path; const pathFlag = isRelative(path) ? splitPath(path) : this.transformToRelativePath(path); if (pathFlag.length === 0) { TreeNode.setGlobalTreeState(this.path, { isLoadingPath: false, }); return this; } if (!this.children) { await this.ensureLoaded(token); } if (token.isCancellationRequested) { TreeNode.setGlobalTreeState(this.path, { isLoadingPath: false, }); return; } let next = this._children; let preItem: CompositeTreeNode; let preItemPath = ''; let name; while (next && (name = pathFlag.shift())) { let item = next.find((c) => c.name.indexOf(name) === 0); if (item) { if (CompositeTreeNode.is(item)) { (item as CompositeTreeNode)._watcher.notifyWillChangeExpansionState(item, true); (item as CompositeTreeNode).isExpanded = true; if (!(item as CompositeTreeNode).children) { await (item as CompositeTreeNode).resolveChildrens(token); if (token.isCancellationRequested) { TreeNode.setGlobalTreeState(this.path, { isLoadingPath: false, }); return; } } flattenedBranchChilds.push(item as CompositeTreeNode); (item as CompositeTreeNode)._watcher.notifyDidChangeExpansionState(item, true); } if (pathFlag.length === 0) { let child; while ((child = flattenedBranchChilds.pop())) { (child as CompositeTreeNode).expandBranch(child, true); if (flattenedBranchChilds.length === 0) { this.updateTreeNodeCache(child as CompositeTreeNode); } } this.watcher.notifyDidUpdateBranch(); TreeNode.setGlobalTreeState(this.path, { isLoadingPath: false, }); return item; } } // 可能展开后路径发生了变化, 需要重新处理一下当前加载路径 if (!item && preItem!) { const compactPath = splitPath(preItem!.name).slice(1); if (compactPath[0] === name) { compactPath.shift(); while (compactPath.length > 0) { if (compactPath[0] === pathFlag[0]) { compactPath.shift(); pathFlag.shift(); } else { break; } } name = pathFlag.shift(); item = next!.find((c) => c.name.indexOf(name) === 0); } } // 最终加载到的路径节点 if (!item || (!CompositeTreeNode.is(item) && pathFlag.length > 0)) { let child; while ((child = flattenedBranchChilds.pop())) { (child as CompositeTreeNode).expandBranch(child, true); if (flattenedBranchChilds.length === 0) { this.updateTreeNodeCache(child as CompositeTreeNode); } } this.watcher.notifyDidUpdateBranch(); TreeNode.setGlobalTreeState(this.path, { isLoadingPath: false, }); return preItem!; } if (CompositeTreeNode.is(item)) { const isCompactName = item.name.indexOf(Path.separator) > 0; if (isCompactName) { const compactPath = splitPath(item.name).slice(1); while (compactPath.length > 0) { if (compactPath[0] === pathFlag[0]) { compactPath.shift(); pathFlag.shift(); } else { break; } } } if (!(item as CompositeTreeNode)._children) { preItemPath = item.path; if (CompositeTreeNode.is(item)) { (item as CompositeTreeNode).isExpanded = true; if (!item.children) { await (item as CompositeTreeNode).resolveChildrens(token); if (token.isCancellationRequested) { TreeNode.setGlobalTreeState(this.path, { isLoadingPath: false, }); return; } } flattenedBranchChilds.push(item as CompositeTreeNode); } } if (item && pathFlag.length === 0) { let child; while ((child = flattenedBranchChilds.pop())) { (child as CompositeTreeNode).expandBranch(child, true); if (flattenedBranchChilds.length === 0) { this.updateTreeNodeCache(child as CompositeTreeNode); } } this.watcher.notifyDidUpdateBranch(); TreeNode.setGlobalTreeState(this.path, { isLoadingPath: false, }); return item; } else { if (!!preItemPath && preItemPath !== item.path) { // 说明此时已发生了路径压缩,如从 a -> a/b/c // 需要根据路径变化移除对应的展开路径, 这里只需考虑短变长场景 const prePaths = Path.splitPath(preItemPath); const nextPaths = Path.splitPath(item.path); if (nextPaths.length > prePaths.length) { pathFlag.splice(0, nextPaths.length - prePaths.length); } } next = (item as CompositeTreeNode)._children; preItem = item as CompositeTreeNode; } } } if (preItem!) { let child; while ((child = flattenedBranchChilds.pop())) { (child as CompositeTreeNode).expandBranch(child, true); if (flattenedBranchChilds.length === 0) { this.updateTreeNodeCache(child as CompositeTreeNode); } } this.watcher.notifyDidUpdateBranch(); TreeNode.setGlobalTreeState(this.path, { isLoadingPath: false, }); return preItem; } TreeNode.setGlobalTreeState(this.path, { isLoadingPath: false, }); } /** * 根据节点获取节点ID下标位置 * @param {number} id * @returns * @memberof CompositeTreeNode */ public getIndexAtTreeNodeId(id: number) { if (this._flattenedBranch) { return this._flattenedBranch.indexOf(id); } return -1; } /** * 根据节点获取节点下标位置 * @param {ITreeNodeOrCompositeTreeNode} node * @returns * @memberof CompositeTreeNode */ public getIndexAtTreeNode(node: ITreeNodeOrCompositeTreeNode) { if (this._flattenedBranch) { return this._flattenedBranch.indexOf(node.id); } return -1; } /** * 根据下标位置获取节点 * @param {number} index * @returns * @memberof CompositeTreeNode */ public getTreeNodeAtIndex(index: number) { const id = this._flattenedBranch![index]; return TreeNode.getTreeNodeById(id); } /** * 根据节点ID获取节点 * @param {number} id * @returns * @memberof CompositeTreeNode */ public getTreeNodeById(id: number) { return TreeNode.getTreeNodeById(id); } /** * 根据节点路径获取节点 * @param {string} path * @returns * @memberof CompositeTreeNode */ public getTreeNodeByPath(path: string) { return TreeNode.getTreeNodeByPath(path); } }
the_stack
import { decodePickingColor, DOM, encodePickingColor } from '@antv/l7-utils'; import { inject, injectable } from 'inversify'; import 'reflect-metadata'; import { TYPES } from '../../types'; import { isEventCrash } from '../../utils/dom'; import { IGlobalConfigService, ISceneConfig } from '../config/IConfigService'; import { IInteractionService, IInteractionTarget, InteractionEvent, } from '../interaction/IInteractionService'; import { ILayer, ILayerService } from '../layer/ILayerService'; import { ILngLat } from '../map/IMapService'; import { gl } from '../renderer/gl'; import { IFramebuffer } from '../renderer/IFramebuffer'; import { IRendererService } from '../renderer/IRendererService'; import { IPickingService } from './IPickingService'; @injectable() export default class PickingService implements IPickingService { @inject(TYPES.IRendererService) private rendererService: IRendererService; @inject(TYPES.IGlobalConfigService) private readonly configService: IGlobalConfigService; @inject(TYPES.IInteractionService) private interactionService: IInteractionService; @inject(TYPES.ILayerService) private layerService: ILayerService; private pickingFBO: IFramebuffer; private width: number = 0; private height: number = 0; private alreadyInPicking: boolean = false; private pickBufferScale: number = 1.0; public init(id: string) { const { createTexture2D, createFramebuffer, getViewportSize, getContainer, } = this.rendererService; let { width, height, } = (getContainer() as HTMLElement).getBoundingClientRect(); width *= DOM.DPR; height *= DOM.DPR; this.pickBufferScale = this.configService.getSceneConfig(id).pickBufferScale || 1; // 创建 picking framebuffer,后续实时 resize this.pickingFBO = createFramebuffer({ color: createTexture2D({ width: Math.round(width / this.pickBufferScale), height: Math.round(height / this.pickBufferScale), wrapS: gl.CLAMP_TO_EDGE, wrapT: gl.CLAMP_TO_EDGE, }), }); // 监听 hover 事件 this.interactionService.on( InteractionEvent.Hover, this.pickingAllLayer.bind(this), ); } public async boxPickLayer( layer: ILayer, box: [number, number, number, number], cb: (...args: any[]) => void, ): Promise<any> { const { useFramebuffer, clear, getContainer } = this.rendererService; this.resizePickingFBO(); useFramebuffer(this.pickingFBO, () => { clear({ framebuffer: this.pickingFBO, color: [0, 0, 0, 0], stencil: 0, depth: 1, }); layer.hooks.beforePickingEncode.call(); layer.renderModels(); layer.hooks.afterPickingEncode.call(); const features = this.pickBox(layer, box); cb(features); }); } public pickBox(layer: ILayer, box: [number, number, number, number]): any[] { const [xMin, yMin, xMax, yMax] = box.map((v) => { const tmpV = v < 0 ? 0 : v; return Math.floor((tmpV * DOM.DPR) / this.pickBufferScale); }); const { getViewportSize, readPixels, getContainer } = this.rendererService; let { width, height, } = (getContainer() as HTMLElement).getBoundingClientRect(); width *= DOM.DPR; height *= DOM.DPR; if ( xMin > ((width - 1) * DOM.DPR) / this.pickBufferScale || xMax < 0 || yMin > ((height - 1) * DOM.DPR) / this.pickBufferScale || yMax < 0 ) { return []; } let pickedColors: Uint8Array | undefined; const w = Math.min(width / this.pickBufferScale, xMax) - xMin; const h = Math.min(height / this.pickBufferScale, yMax) - yMin; pickedColors = readPixels({ x: xMin, // 视口坐标系原点在左上,而 WebGL 在左下,需要翻转 Y 轴 y: Math.floor(height / this.pickBufferScale - (yMax + 1)), width: w, height: h, data: new Uint8Array(w * h * 4), framebuffer: this.pickingFBO, }); const features = []; const featuresIdMap: { [key: string]: boolean } = {}; for (let i = 0; i < pickedColors.length / 4; i = i + 1) { const color = pickedColors.slice(i * 4, i * 4 + 4); const pickedFeatureIdx = decodePickingColor(color); if (pickedFeatureIdx !== -1 && !featuresIdMap[pickedFeatureIdx]) { const rawFeature = layer.getSource().getFeatureById(pickedFeatureIdx); features.push(rawFeature); featuresIdMap[pickedFeatureIdx] = true; } } return features; } private async pickingAllLayer(target: IInteractionTarget) { if (this.alreadyInPicking || this.layerService.alreadyInRendering) { return; } this.alreadyInPicking = true; await this.pickingLayers(target); // TODO: 触发图层更新渲染,同时传递更新类型 this.layerService.renderLayers('picking'); this.alreadyInPicking = false; } private resizePickingFBO() { const { getContainer } = this.rendererService; let { width, height, } = (getContainer() as HTMLElement).getBoundingClientRect(); width *= DOM.DPR; height *= DOM.DPR; if (this.width !== width || this.height !== height) { this.pickingFBO.resize({ width: Math.round(width / this.pickBufferScale), height: Math.round(height / this.pickBufferScale), }); this.width = width; this.height = height; } } private async pickingLayers(target: IInteractionTarget) { const { getViewportSize, useFramebuffer, clear, getContainer, } = this.rendererService; this.resizePickingFBO(); useFramebuffer(this.pickingFBO, () => { const layers = this.layerService.getLayers(); layers .filter((layer) => layer.needPick(target.type)) .reverse() .some((layer) => { clear({ framebuffer: this.pickingFBO, color: [0, 0, 0, 0], stencil: 0, depth: 1, }); layer.hooks.beforePickingEncode.call(); layer.renderModels(); layer.hooks.afterPickingEncode.call(); const isPicked = this.pickFromPickingFBO(layer, target); return isPicked && !layer.getLayerConfig().enablePropagation; }); }); } private pickFromPickingFBO = ( layer: ILayer, { x, y, lngLat, type, target }: IInteractionTarget, ) => { let isPicked = false; const { getViewportSize, readPixels, getContainer } = this.rendererService; let { width, height, } = (getContainer() as HTMLElement).getBoundingClientRect(); width *= DOM.DPR; height *= DOM.DPR; const { enableHighlight, enableSelect } = layer.getLayerConfig(); const xInDevicePixel = x * DOM.DPR; const yInDevicePixel = y * DOM.DPR; if ( xInDevicePixel > width - 1 * DOM.DPR || xInDevicePixel < 0 || yInDevicePixel > height - 1 * DOM.DPR || yInDevicePixel < 0 ) { return false; } let pickedColors: Uint8Array | undefined; pickedColors = readPixels({ x: Math.floor(xInDevicePixel / this.pickBufferScale), // 视口坐标系原点在左上,而 WebGL 在左下,需要翻转 Y 轴 y: Math.floor((height - (y + 1) * DOM.DPR) / this.pickBufferScale), width: 1, height: 1, data: new Uint8Array(1 * 1 * 4), framebuffer: this.pickingFBO, }); if ( pickedColors[0] !== 0 || pickedColors[1] !== 0 || pickedColors[2] !== 0 ) { const pickedFeatureIdx = decodePickingColor(pickedColors); const rawFeature = layer.getSource().getFeatureById(pickedFeatureIdx); if ( pickedFeatureIdx !== layer.getCurrentPickId() && type === 'mousemove' ) { type = 'mouseenter'; } const layerTarget = { x, y, type, lngLat, featureId: pickedFeatureIdx, feature: rawFeature, target, }; if (!rawFeature) { // this.logger.error( // '未找到颜色编码解码后的原始 feature,请检查 fragment shader 中末尾是否添加了 `gl_FragColor = filterColor(gl_FragColor);`', // ); } else { // trigger onHover/Click callback on layer isPicked = true; layer.setCurrentPickId(pickedFeatureIdx); this.triggerHoverOnLayer(layer, layerTarget); // 触发拾取事件 } } else { // 未选中 const layerTarget = { x, y, lngLat, type: layer.getCurrentPickId() !== null && type === 'mousemove' ? 'mouseout' : 'un' + type, featureId: null, target, feature: null, }; this.triggerHoverOnLayer(layer, { ...layerTarget, type: 'unpick', }); this.triggerHoverOnLayer(layer, layerTarget); layer.setCurrentPickId(null); } if (enableHighlight) { this.highlightPickedFeature(layer, pickedColors); } if ( enableSelect && type === 'click' && pickedColors?.toString() !== [0, 0, 0, 0].toString() ) { const selectedId = decodePickingColor(pickedColors); if ( layer.getCurrentSelectedId() === null || selectedId !== layer.getCurrentSelectedId() ) { this.selectFeature(layer, pickedColors); layer.setCurrentSelectedId(selectedId); } else { this.selectFeature(layer, new Uint8Array([0, 0, 0, 0])); // toggle select layer.setCurrentSelectedId(null); } } return isPicked; }; private triggerHoverOnLayer( layer: ILayer, target: { x: number; y: number; type: string; lngLat: ILngLat; feature: unknown; featureId: number | null; }, ) { // layer.emit(target.type, target); // 判断是否发生事件冲突 if (isEventCrash(target)) { layer.emit(target.type, target); } } /** * highlight 如果直接修改选中 feature 的 buffer,存在两个问题: * 1. 鼠标移走时无法恢复 * 2. 无法实现高亮颜色与原始原色的 alpha 混合 * 因此高亮还是放在 shader 中做比较好 * @example * this.layer.color('name', ['#000000'], { * featureRange: { * startIndex: pickedFeatureIdx, * endIndex: pickedFeatureIdx + 1, * }, * }); */ private highlightPickedFeature( layer: ILayer, pickedColors: Uint8Array | undefined, ) { // @ts-ignore const [r, g, b] = pickedColors; layer.hooks.beforeHighlight.call([r, g, b]); } private selectFeature(layer: ILayer, pickedColors: Uint8Array | undefined) { // @ts-ignore const [r, g, b] = pickedColors; layer.hooks.beforeSelect.call([r, g, b]); } }
the_stack
declare namespace zingchart { function render(config: object): null; function bind(id: string, eventName: string, cb?: any): void; function exec(id: string, call: string, params?: any): any; function unbind(id: string, event: string, fn?: any): void; let BUILDCODE: string[]; let LICENSE: string[]; let LICENSEKEY: string[]; let ASYNC: boolean; let FONTFAMILY: string[]; let FONTSIZE: string[]; let MODULESDIR: string[]; let ZCOUTPUT: boolean; let SYNTAX: string; let EXPORTURL: string; let AJAXEXPORT: boolean; let DEV: { CANVASVERSION?: number; CACHECANVASTEXT?: boolean; CACHESELECTION?: boolean; CHECKDECIMALS?: boolean; COPYDATA?: boolean; KEEPSOURCE?: boolean; MEDIARULES?: boolean; PLOTSTATS?: boolean; SKIPTRACKERS?: boolean; SKIPPROGRESS?: boolean; SORTTOKENS?: boolean; RESOURCES?: boolean; }; interface data { globals?: globals; graphset?: [graphset]; gui?: gui; history?: history; refresh?: refresh; } interface backgroundMarker { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; /** * Sets the type of the object/shape. "pie" | "circle" | "star5" | ... */ type?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; } interface backgroundState { /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; } interface calloutTip { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the line color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line width of the object. 1 | 3 | | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the size of the object. 4 | "6px" | ... */ size?: number; /** * Sets the shape type of the object. "circle" | "diamond" | "cross" | "arrow" */ type?: string; } interface contextMenu { button?: { /** * To style the closing context menu button. Use the lineColor attribute to specify the button color. {...} */ close?: any; /** * To style the opening context menu button. Use the lineColor attribute to specify the button color. {...} */ open?: any; }; items?: [ { /** * To specify the font color of the context menu items. 'gray' | '##666699' */ 'font-color'?: any; fontColor?: any; /** * To display or remove the Save Image context menu item. true | false */ image?: boolean; /** * To display or remove the Lock/Unlock Scrolling context menu item. true | false */ lock?: boolean; /** * Use the object to display or remove individual Share Image context menu items: email, facebook, twitter, and linkedin. {...} */ share?: any; } ]; /** * To set the visibility of the object. true | false */ visible?: boolean; } interface contextMenuGui { /** * To fix the position of the context menu to one side of the chart. true | false */ docked?: boolean; /** * Empties all default context-menu items, leaving just the "About ZingChart" button. true | false | 1 | 0 */ empty?: boolean; /** * To position the context menu button on the left or right side of the chart. left | right */ position?: string; button?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. A single color will create a solid background, while two colors will create a gradient. " * none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the width of the object's border. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the object's font color. Similar to color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" * | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the object's font family. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the object's font size. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the object's font style. Similar to italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the object's font weight. Similar to bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the padding around the object's text. Up to four values can be used to set the padding around the text, with the first value * being the top padding, the second value being the right padding, the third value being the bottom padding, and the fourth value be * ing the left padding. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the bottom padding for the object's text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the left padding for the object's text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the right padding for the object's text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the top padding for the object's text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the horizontal alignment for the object's text. Horizontal alignment can be left, center, or right. "left" | "center" | "righ * t" */ 'text-align'?: string; textAlign?: string; /** * Sets the transparency of the object's text. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 bei * ng completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration to use underlined characters. Similar to underline. May not display properly in Mozilla Firefox when ch * arts are rendered using SVG. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the context-menu button is visible or not. true | false | 1 | 0 */ visible?: boolean; /** * Sets the width of the object. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; /** * Sets the X position of the object. The context-menu gear object must be positioned separately. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. The context-menu gear object must be positioned separately. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; }; 'custom-items'?: [ { /** * Sets a JavaScript function/portion of code that will be executed when the respective menu item is selected. "doSomething()" | "ale * rt(1)" | ... */ function?: string; /** * Sets the ID of the menu item. "myid" | "f1" | ... */ id?: string; /** * Sets the text for the menu item. "New Menu Item" | ... */ text?: string; } ]; gear?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; /** * Sets the type of icon displayed on mobile devices to tap to bring up the drop-down menu. gear4 can be specified, this means that t * he gear icon shown will have four sprockets protruding from it. Gears can range from 3-9. star4 has 4 points, while star9 has 9 po * ints. Stars can range from 3-9 also. "gear4" | "gear9" | "star4" | "star9" | ... */ type?: string; /** * Sets the X position of the object. The context-menu button object must be positioned separately. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. The context-menu button object must be positioned separately. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; }; item?: { /** * Sets the background color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the font color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets how the context menu item appears when a user hovers over it. Use the backgroundColor and fontColor attributes. {...} */ 'hover-state'?: any; hoverState?: any; }; } interface crosshairX { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * X-Axis Crosshairs Only: When true, plot nodes will be highlighted only when the guide is directly next to the node. When false (th * e default setting), the plot nodes closest to the guide will be highlighted. true | false | 1 | 0 */ exact?: boolean; /** * Sets the line color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Reverses the order of items in plotLabel. Generally used with positive stacked charts. */ 'reverse-series'?: boolean; reverseSeries?: boolean; /** * X-Axis Crosshairs Only: For graphsets with multiple chart objects, setting the attribute to true in "crosshair-x" will allow you t * o use crosshairs across all charts simultaneously. true | false | 1 | 0 */ shared?: boolean; /** * X-Axis Crosshairs Only: Sets the mode used to display crosshair plot-labels. When set to "move" (the default setting), plot-labels * for all nodes will be displayed. The "hover" setting will allow only one plot-label to be displayed at a time, with the visibilit * y of each label being triggered when the user hovers over a node. "move" | "hover" */ trigger?: string; /** * Y-Axis Crosshairs Only: Sets the type of the "crosshair-y", either in single mode (one line for all scales) or multiple (a line fo * r every plot). "single" | "multiple" */ type?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; marker?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object, applicable on closed shapes. See the square points between the lines. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See the square points between the lines. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: number; /** * The type of the marker object to render. square | circle | diamond | triangle | star5 | star6 | star7 | star8 | rpoly5 | gear5 | g * ear6 | gear7 | gear8 */ type?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; }; 'plot-label'?: plotLabel; plotLabel?: plotLabel; 'scale-label'?: scaleLabel; scaleLabel?: scaleLabel; } interface crosshairY { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * X-Axis Crosshairs Only: When true, plot nodes will be highlighted only when the guide is directly next to the node. When false (th * e default setting), the plot nodes closest to the guide will be highlighted. true | false | 1 | 0 */ exact?: boolean; /** * Sets the line color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Reverses the order of items in plotLabel. Generally used with positive stacked charts. */ 'reverse-series'?: boolean; reverseSeries?: boolean; /** * X-Axis Crosshairs Only: For graphsets with multiple chart objects, setting the attribute to true in "crosshair-x" will allow you t * o use crosshairs across all charts simultaneously. true | false | 1 | 0 */ shared?: boolean; /** * X-Axis Crosshairs Only: Sets the mode used to display crosshair plot-labels. When set to "move" (the default setting), plot-labels * for all nodes will be displayed. The "hover" setting will allow only one plot-label to be displayed at a time, with the visibilit * y of each label being triggered when the user hovers over a node. "move" | "hover" */ trigger?: string; /** * Y-Axis Crosshairs Only: Sets the type of the "crosshair-y", either in single mode (one line for all scales) or multiple (a line fo * r every plot). "single" | "multiple" */ type?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; marker?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object, applicable on closed shapes. See the square points between the lines. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See the square points between the lines. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: number; /** * The type of the marker object to render. square | circle | diamond | triangle | star5 | star6 | star7 | star8 | rpoly5 | gear5 | g * ear6 | gear7 | gear8 */ type?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; }; 'plot-label'?: plotLabel; plotLabel?: plotLabel; 'scale-label'?: scaleLabel; scaleLabel?: scaleLabel; } interface guideLabel { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Note that values require the leading 0 before the decimal point. Use with "background-color" attribute. 0.3 | 0.4 | * 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#FF0 * 000", "#0000FF"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "#f00" | "#f00 #00f" | "red yel * low" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the font color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the font style of the object. "none" | "italic" */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object. "none" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the padding around the text of the object. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the crosshair plot label text to be displayed for that series. You can provide any combination of alphanumeric characters and * /or ZingChart tokens. "%v widgets" | "Top Sales: %v" | "$%v" | "%v %t" | "..." */ text?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; } interface highlightMarker { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the line color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line style of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 1 | 3 | | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * The type of the marker object to render. square | circle | diamond | triangle | star5 | star6 | star7 | star8 | rpoly5 | gear5 | g * ear6 | gear7 | gear8 */ type?: string; } interface highlightState { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the line color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line style of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 1 | 3 | | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * The type of the marker object to render. square | circle | diamond | triangle | star5 | star6 | star7 | star8 | rpoly5 | gear5 | g * ear6 | gear7 | gear8 */ type?: string; } interface hoverMarker { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the line color of the object, applicable on non-closed shapes. See also border-color for closed shapes. "none" | "transparent * " | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. See also border-width for closed shapes. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets an Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; /** * The type of the marker object to render. square | circle | diamond | triangle | star5 | star6 | star7 | star8 | rpoly5 | gear5 | g * ear6 | gear7 | gear8 */ type?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; } interface hoverState { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Area Charts Only: Sets the transparency level of the area below a line. Values must range between 0.0 and 1.0, with 0.0 being comp * letely transparent and 1.0 being completely opaque. Note that values require the leading zero before the decimal point. 0.3 | 0.9 * | ... */ 'alpha-area'?: number; alphaArea?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699' * , '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15 * , 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object. 2 | 3 | '5px' | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the font color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'font-color'?: any; fontColor?: any; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the line color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 1 | 3 | | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the padding of the object. 3 | '5px' | '10px' | ... */ padding?: number; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the text transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 bei * ng completely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; } interface itemOff { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | .../p> */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. Similar to angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the object's font color. Similar to color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" * | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style. Similar to italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight. Similar to bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; } interface legendItem { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. Requires Legend. Used only inside individual * series rather than Plot. See red text in upper right box. Works with output flash. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. Requires Legend. Used only inside individual series rather than Plot. See red text in * upper right box. Works with output canvas and svg. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). Requires Legend. * Used only inside individual series rather than Plot. See red text in upper right box. "none" | "transparent" | "#f00" | "#f00 #00f * " | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. Requires Legend. Used onl * y inside individual series rather than Plot. See red text in upper right box. "none" | "transparent" | "#f00" | "#f00 #00f" | "red * yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. Requires Legend. Used on * ly inside individual series rather than Plot. See red text in upper right box. "none" | "transparent" | "#f00" | "#f00 #00f" | "re * d yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". Requires Legend. Used only inside individual series rathe * r than Plot. See red text in upper right box. "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. Requires Legend. Used only inside ind * ividual series rather than Plot. See red text in upper right box. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. Requires Legend. Used only inside individual se * ries rather than Plot. See red text in upper right box. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. Requires Legend. Used only inside individual series rather than Plot. See red te * xt in upper right box. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not. Requires Legend. Used only inside individual series rather than Pl * ot. See red text in upper right box. true | false | 1 | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. Requires Legend. Used only inside individual seri * es rather than Plot. See red text in upper right box. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object. Requires Legend. Used only inside individual series rather than Plot. See red text in upper r * ight box. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. Requires Legend. Used only inside individual series * rather than Plot. See red text in upper right box. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. Requires * Legend. Used only inside individual series rather than Plot. See red text in upper right box. 4 | "6px" | "6px 10px 3px 5px" | "- * 10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. Requires Legend. Used only inside individual series ra * ther than Plot. See red text in upper right box. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. Requires Legend. Used only inside individual series r * ather than Plot. See red text in upper right box. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. Requires Legend. Used only inside individual series rathe * r than Plot. See red text in upper right box. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. Requires Legend. Used only inside individual series rath * er than Plot. See red text in upper right box. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. Requires Legend. Used only inside individual serie * s rather than Plot. See red text in upper right box. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. Requires Legend. Used only inside individual series rather than Plot. See red text in upper right box. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object. Requires Legend. Used only inside individual series rather than Plot. See red text in upper r * ight box. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets whether an object will have a callout arrow or not. Requires Legend. Used only inside individual series rather than Plot. See * red text in upper right box. Works with output canvas and svg. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. Requires Legend. Used only inside individual se * ries rather than Plot. See red text in upper right box. Works with output canvas and svg. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. Requires Legend. Used only insid * e individual series rather than Plot. See red text in upper right box. Works with output canvas and svg. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart.. Requires Legend. Used only inside individual series rather than Plot. See red text in upper right b * ox. Works with output canvas and svg. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. Requires Legend. Used only inside individual series rather than Pl * ot. See red text in upper right box. Works with output canvas and svg. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. Requires Legend. Used only inside individua * l series rather than Plot. See red text in upper right box. Works with output canvas and svg. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. Requires Legend. Used only inside * individual series rather than Plot. See red text in upper right box. Works with output canvas and svg. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Sets the color of the text in the legend box. Requires Legend. Used only inside individual series rather than Plot. See red text i * n upper right box. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ color?: string; /** * Sets the style of the cursor when hovering over a node. "hand" | "normal" */ cursor?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. Requires Legend. Used only inside individual series rather th * an Plot. See red text in upper right box. Works with output canvas and svg. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. Requires Legend. Used only inside individual series rather than Plot. See red text in upper * right box. Works with output canvas and svg. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. Requires Legend. Used only inside individual series rather than Plot. See red text in upper * right box. Works with output canvas and svg. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. Requires Legend. Used only inside individual series rather than * Plot. See red text in upper right box. Works with output canvas and svg. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. For the text in the legend box. Requires Legend. Used only ins * ide individual series rather than Plot. See red text in upper right box. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the font color of the text in the legend box. Works like color. Requires Legend. Used only inside individual series rather th * an Plot. See red text in upper right box. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family in the legend box. Requires Legend. Used only inside individual series rather than Plot. See red text * in upper right box. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size in the legend box. Requires Legend. Used only inside individual series rather than Plot. See red text in * upper right box. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style in the legend box. Requires Legend. Used only inside individual series rather than Plot. See red text i * n upper right box. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight in the legend box. Similar to bold. Requires Legend. Used only inside individual series rather than Pl * ot. See red text in upper right box. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. Requires Le * gend. Used only inside individual series rather than Plot. See red text in upper right box. Works with output canvas and svg. "#f0 * 0 #0f0 #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. Require * s Legend. Used only inside individual series rather than Plot. See red text in upper right box. Works with output canvas and svg. * "0.1 0.5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. Requires Legend. Used only inside individual series rather than Plot. See red text in upper right box. W * orks with output canvas and svg. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the text is displayed with italic characters or not. For the legend box. Similar to font-style. Requires Legend. Used * only inside individual series rather than Plot. See red text in upper right box. true | false | 1 | 0 */ italic?: boolean; /** * Sets the object's margins. Requires Legend. Used only inside individual series rather than Plot. See red text in upper right box. * Works with output canvas and svg. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ margin?: any; /** * Sets the object's bottom margin. Requires Legend. Used only inside individual series rather than Plot. See red text in upper right * box. Works with output canvas and svg. 4 | "6px" | ... */ 'margin-bottom'?: any; marginBottom?: any; /** * Sets the object's left margin. Requires Legend. Used only inside individual series rather than Plot. See red text in upper right b * ox. Works with output canvas and svg. 4 | "6px" | ... */ 'margin-left'?: any; marginLeft?: any; /** * Sets the object's right margin. Requires Legend. Used only inside individual series rather than Plot. See red text in upper right * box. Works with output canvas and svg. 4 | "6px" | ... */ 'margin-right'?: any; marginRight?: any; /** * Sets the object's top margin. Requires Legend. Used only inside individual series rather than Plot. See red text in upper right bo * x. Works with output canvas and svg. 4 | "6px" | ... */ 'margin-top'?: any; marginTop?: any; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." Requires Legend. Used only inside individual series rather than Plot. See red text in uppe * r right box. 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. Requires Legend. Used only inside individual series rather than Plot. See red text in upper right box. Works w * ith output canvas and svg. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. Requires Legend. Used only inside individual series rather than Plot. * See red text in upper right box. Works with output canvas and svg. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets an Y offset to apply when positioning the object/shape. Requires Legend. Used only inside individual series rather than Plot. * See red text in upper right box. Works with output canvas and svg. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * To specify the order of the legend items in the legend. 1 | 2 | 3 | 4 | ... */ order?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, starting with t * he top and going clockwise. Requires Legend. Used only inside individual series rather than Plot. See red text in upper right box. * 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. For single item in Legend. Requires Legend. Used only inside individual series r * ather than Plot. See red text in upper right box. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. For single item in Legend. Requires Legend. Used only inside individual series rat * her than Plot. See red text in upper right box. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. For single item in Legend. Requires Legend. Used only inside individual series ra * ther than Plot. See red text in upper right box. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. For single item in Legend. Requires Legend. Used only inside individual series rath * er than Plot. See red text in upper right box. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. For single item in Legend. Requires Legend. Used only inside individual series * rather than Plot. See red text in upper right box. Works with output flash. Has limited effect on HTML5 implementation. true | fa * lse | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. For single item in Legend. Req * uires Legend. Used only inside individual series rather than Plot. See red text in upper right box. Works with output flash. Has l * imited effect on HTML5 implementation. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. For single item in Legend. Requires Legend. Used only inside individual series * rather than Plot. See red text in upper right box. Works with output flash. Has limited effect on HTML5 implementation. -45 | 115 * | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. For single item in Legend. Requires Legend. Used only inside individual se * ries rather than Plot. See red text in upper right box. Works with output flash. Has limited effect on HTML5 implementation. 4 | " * 6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. For single item in Legend. Requires Legend. Used only inside individual series rather * than Plot. See red text in upper right box. Works with output flash. Has limited effect on HTML5 implementation. "none" | "transpa * rent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. For single item in Legend. Requires Legend. Used only inside individual serie * s rather than Plot. See red text in upper right box. Works with output flash. Has limited effect on HTML5 implementation. 4 | "6px * " | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; /** * Sets the text content of the object. For single item in Legend. Requires Legend. Used only inside individual series rather than Pl * ot. See red text in upper right box. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. For single item in Legend. Requires Legend. Used only inside in * dividual series rather than Plot. See red text in upper right box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. For single item in Legend. Requires Legend. Used * only inside individual series rather than Plot. See red text in upper right box. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration. Similar to underline. For single item in Legend. Requires Legend. Used only inside individual series r * ather than Plot. See red text in upper right box. Use output canvas or flash. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text is displayed with underlined characters or not. For single item in Legend. Requires Legend. Used only inside * individual series rather than Plot. See red text in upper right box. Use output canvas or flash. true | false | 1 | 0 */ underline?: boolean; /** * Sets whether the text will wrap, depending on the width of the object. For single item in Legend. Requires Legend. Used only insid * e individual series rather than Plot. See red text in upper right box. Use output canvas or flash. "top" | "middle" | "bottom" */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the visibility of the object. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. See red text in upper right box. Use output canvas or flash * . true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; } interface legendMarker { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. Requires Legend. Used only inside individual * series rather than Plot. See the shape to the left of the text in the upper right box. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. Requires Legend. Used only inside individual series rather than Plot. See the shape t * o the left of the text in the upper right box. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. For the shape to the left of the Legend text. Colors can be entered by name (e.g. "red", * "blue", "yellow"), in hexadecimal notation (e.g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0 * ,0,255)", "rgb(255,255,0)"). Requires Legend. Used only inside individual series rather than Plot. See the orange shape to the lef * t of the text in the upper right box. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. Requires Legend. Used onl * y inside individual series rather than Plot. See the shape to the left of the text in the upper right box. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. Requires Legend. Used on * ly inside individual series rather than Plot. See the shape to the left of the text in the upper right box. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". Requires Legend. Used only inside individual series rathe * r than Plot. See the shape to the left of the text in the upper right box. "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. Requires Legend. Used only inside ind * ividual series rather than Plot. See the shape to the left of the text in the upper right box. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. Requires Legend. Used only inside individual se * ries rather than Plot. See the shape to the left of the text in the upper right box. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. Requires Legend. Used only inside individual series rather than Plot. See the sh * ape to the left of the text in the upper right box. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. Requires Legend. Used onl * y inside individual series rather than Plot. See the shape to the left of the text in the upper right box. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. See also line-color for c * losed shapes. Requires Legend. Used only inside individual series rather than Plot. See the shape to the left of the text in the u * pper right box. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the style of the cursor when hovering over a node. "hand" | "normal" */ cursor?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. Requires Legend. Used only inside individual series rather th * an Plot. See the shape to the left of the text in the upper right box. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. Requires Legend. Used only inside individual series rather than Plot. See the shape to the * left of the text in the upper right box. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. Requires Legend. Used only inside individual series rather than Plot. See the shape to the * left of the text in the upper right box. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. Requires Legend. Used only inside individual series rather than * Plot. See the shape to the left of the text in the upper right box. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. Requires Le * gend. Used only inside individual series rather than Plot. See the shape to the left of the text in the upper right box. "#f00 #0f * 0 #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. Require * s Legend. Used only inside individual series rather than Plot. See the shape to the left of the text in the upper right box. "0.1 * 0.5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets an X offset to apply when positioning the object/shape. Requires Legend. Used only inside individual series rather than Plot. * See the shape to the left of the text in the upper right box. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets an Y offset to apply when positioning the object/shape. Requires Legend. Used only inside individual series rather than Plot. * See the shape to the left of the text in the upper right box. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the size of the object/shape. Requires Legend. Used only inside individual series rather than Plot. See the shape to the left * of the text in the upper right box. 4 | "6px" | ... */ size?: any; /** * Sets the type of the object/shape. Requires Legend. Used only inside individual series rather than Plot. See the shape to the left * of the text in the upper right box. "pie" | "circle" | "star5" | ... */ type?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. Requires Legend. Used only in * side individual series rather than Plot. See the shapes to the left of the text in the upper right box. true | false | 1 | 0 */ visible?: boolean; /** * Sets the X position of the object. Requires Legend. Used only inside individual series rather than Plot. See the shapes to the lef * t of the text in the upper right box. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. Requires Legend. Used only inside individual series rather than Plot. See the shapes to the lef * t of the text in the upper right box. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; } interface minorGuide { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the line color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699', * '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, * 15)' | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 1 | 3 | '6px' | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; } interface minorTick { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the line color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699', * '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, * 15)' | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. See the red lines across the bottom between the ticks. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. See the red lines across the bottom between the ticks. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 1 | 3 | '6px' | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the placement of the object. 'outer' | 'inner' | 'cross' */ placement?: string; /** * Sets the size of the object. 10 | '16px' | ... */ size?: number; /** * Sets the visibility of the object. true | false */ visible?: boolean; } interface noData { /** * Sets the text's horizontal alignment to one of the three applicable values, relative to the object's box. "left" | "center" | "rig * ht" */ align?: string; /** * Sets the text's vertical alignment to one of the three applicable values, relative to the object's box. "top" | "middle" | "bottom * " */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not. true | false | 1 | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the object's font color. Similar to font-color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, * 15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. Similar to angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the object's font color. Similar to color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" * | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style. Similar to italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight. Similar to bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the text is displayed with italic characters or not. true | false | 1 | 0 */ italic?: boolean; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, with the first * value affecting the top padding, the second value affecting the right padding, and so on, in a clockwise direction. 10 | "5px" | " * 10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration to use underlined characters. Similar to underline. May not display properly in Mozilla Firefox when ch * arts are rendered using SVG. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text is displayed with underlined characters or not. Similar to text-decoration. May not display properly in Mozi * lla Firefox when charts are rendered using SVG. true | false | 1 | 0 */ underline?: boolean; /** * Sets the URL for the link associated with the object. "http://www.domain.com/link.php" | "link.asp" | ... */ url?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; } interface pageOff { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets an Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; } interface pageOn { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets an Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; } interface pageStatus { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not. true | false | 1 | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Cuts off extra text in the legend box if width is set. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets whether the text is displayed with bold characters or not. "#f00" | "rgb(100,15,15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. Similar to angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the object's font color. Similar to color. "#f00" | "blue" | "rgb(100,15,15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. ""Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style. Similar to italic. "none" | "italic" | "oblique" | ... */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight. Similar to bold. "normal" | "bold" | ... */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the text is displayed with italic characters or not. true | false | | 1 | 0 */ italic?: boolean; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: number; maxWidth?: number; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, starting with t * he top and going clockwise. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" | ... */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration. Similar to underline. "none" | "underline" | ... */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text is displayed with underlined characters or not. true | false | 1 | 0 */ underline?: string; /** * Sets the text's vertical alignment to one of the three applicable values, relative to the object's box. "top" | "Middle" | "Bottom * " */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; } interface plotLabel { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not. true | false | 1 | 0 */ bold?: boolean; /** * Sets the transparency of the border. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'border-alpha'?: number; borderAlpha?: number; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Clips text that runs longer than the width of the parent object. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the text's color of the crosshair xy label when you hover over the graph items. "none" | "transparent" | "#f00" | "#f00 #00f" * | "red yellow" | "rgb(100, 15, 15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the rotation angle of the crosshair xy label when you hover over the graph items. Similar with angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the text's color of the crosshair xy label when you hover over the graph items. Similar with color. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family of the crosshair xy label when you hover over the graph items. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size of the crosshair xy label when you hover over the graph items. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style of the crosshair xy label when you hover over the graph items. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight of the crosshair xy label when you hover over the graph items. Similar with bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the text of the crosshair xy label when you hover over the graph items is displayed with italic characters or not . t * rue | false | 1 | 0 */ italic?: boolean; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * To separate the plot labels so that a label appears for each series. You can assign unique text and styling to each label by going * to the "series" array. In each series object, create a "guide-label"object, where you can place your series-specific text and sty * ling attributes. true | false | 1 | 0 */ multiple?: boolean; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, with the first * value affecting the top padding, the second value affecting the right padding, and so on, in a clockwise direction. 10 | "5px" | " * 10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration to use underlined characters. Similar to underline. May not display properly in Mozilla Firefox when ch * arts are rendered using SVG. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Allows the underlying data to be 'transformed' to a new format if it was in that format originally. For example, if data is coded * as a date and time, and 'type':'date' is specified as an attribute of this object, '1311261385209' will display 'Wed, 19 of May 05 * :00 PM' if '%D, %d %M %h:%i %A' is specified under the transform attribute of scale-x. {...} */ transform?: any; /** * Sets whether the text is displayed with underlined characters or not. Similar to text-decoration. May not display properly in Mozi * lla Firefox when charts are rendered using SVG. true | false | 1 | 0 */ underline?: boolean; /** * Sets the text's vertical alignment to one of the three applicable values, relative to the object's box. "top" | "middle" | "bottom * " */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; } interface refLine { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the line color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. See the space between orange bar. Works for output canvas and svg. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. See the length of the pieces of the orange bar. Works for output canvas and svg. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 1 | 3 | '6px' | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the visibility of the object. true | false */ visible?: boolean; } interface scaleK { /** * On a radar chart, the “aspect” attribute allows you to change the chart’s shape from star/spider (default) to circular. 'star' (de * fault) | 'circle' */ aspect?: string; /** * Allows you to set the format for your scale-k values. You can use a combination of text and tokens (%v represents the scale values * ), e.g., “%v°” or “Variable %v”. 'Value: %v' */ format?: string; /** * Allows you to set custom labels for each step along scale-k. [...] */ labels?: any; /** * Used to set the minimum, maximum, and step scale values on scale-k. E.g., for “values”: “0:330:30”, 0 is the minimum, 330 is the m * aximum, and 30 is the step. "0:100:10" | [1,3,5,7] | ... */ values?: any; /** * Used to hide the k-axis. true | false */ visible?: boolean; guide?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that values require the leading zero before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the line color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 1 | 3 | '6px' | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the visibility of the object. true | false */ visible?: boolean; items?: [ { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that values require the leading zero before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string; borderWidth?: number | string; } ]; }; item?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the angle of the object. -45 | 30 | 120 | ... */ angle?: number /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699' * , '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15 * , 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object. 2 | 3 | '5px' | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the font color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object. 'Arial' | 'Tahoma,Verdana' | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object. 10 | 12 | '20px' | ... */ 'font-size'?: number; fontSize?: number; /** * Sets the font style of the object. 'italic' | 'normal' */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object. 'bold' | 'normal' */ 'font-weight'?: string; fontWeight?: string; /** * Sets the padding of the object 3 | '5px' | '10px' | ... */ padding?: number; /** * Sets the text transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 bei * ng completely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; }; tick?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that values require the leading zero before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the line color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 4 | '6px' | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the placement of the object. 'outer' | 'inner' | 'cross' */ placement?: string; /** * Sets the size of the object. 4 | '6px' | ... */ size?: number; /** * Sets the visibility of the object. true | false */ visible?: boolean; }; tooltip?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the transparency of the border. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'border-alpha'?: number; borderAlpha?: number; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius (rounded corners) of the object. "3px" | "10px" */ 'border-radius'?: any; borderRadius?: any; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the font color of the object text. "none" | "transparent" | "purple" | "#33ccff" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object text. "Courier" | "Georgia" | "Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object text. 12 | "20px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the font style of the object text. "normal" | "italic" */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object text. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets the height of the object. 10 | "20px" | 0.3 | "30%" | ... */ height?: number; /** * Sets the padding around the object text. "10%" | "25px" ... */ padding?: number; /** * To create sticky tooltips. Use this with the "timeout" attribute, which allows you to specify how long you want the tooltips to "s * tick" to the chart. true | false | 1 |0 */ sticky?: boolean; /** * Specifies what text to display in the tooltips. Use with the %scale-value (%v) token. "Scale Tooltips" | "%v Days" | "..." */ text?: string; /** * Sets the transparency of the text. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comple * tely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * To create sticky tooltips. Provide a value in milliseconds. Use this with the "sticky" attribute, which specifies whether or not t * ooltips will "stick" to the chart. "30000 | 10000 | ... */ timeout?: number; /** * Sets the visibility of the object. true | false | 1 | 0 */ visible?: boolean; /** * Sets the width of the object. 10 | "20px" | 0.3 | "30%" | ... */ width?: number; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; } interface scaleLabel { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text of the scale label is displayed with bold characters or not. To see this, hover over the axis to the bottom. * true | false | 1 | 0 */ bold?: boolean; /** * Sets the transparency of the border. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'border-alpha'?: number; borderAlpha?: number; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Sets the text's color of the crosshair xy label when you hover over the graph items. "none" | "transparent" | "#f00" | "#f00 #00f" * | "red yellow" | "rgb(100, 15, 15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the rotation angle of the crosshair xy label when you hover over the graph items. Similar with angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the text's color of the crosshair xy label when you hover over the graph items. Similar with color. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family of the crosshair xy label when you hover over the graph items. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size of the crosshair xy label when you hover over the graph items. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style of the crosshair xy label when you hover over the graph items. Similar with italic. "none" | "italic" | * "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight of the crosshair xy label when you hover over the graph items. Similar with bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the text of the crosshair xy label when you hover over the graph items is displayed with italic characters or not . t * rue | false | 1 | 0 */ italic?: boolean; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, with the first * value affecting the top padding, the second value affecting the right padding, and so on, in a clockwise direction. 10 | "5px" | " * 10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * X-Axis Crosshair Scale Labels Only: Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration to use underlined characters. Similar to underline. May not display properly in Mozilla Firefox when ch * arts are rendered using SVG. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Allows the underlying data to be 'transformed' to a new format if it was in that format originally. For example, if data is coded * as a date and time, and 'type':'date' is specified as an attribute of this object, '1311261385209' will display 'Wed, 19 of May 05 * :00 PM' if '%D, %d %M %h:%i %A' is specified under the transform attribute of scale-x. {...} */ transform?: any; /** * Sets whether the text is displayed with underlined characters or not. Similar to text-decoration. May not display properly in Mozi * lla Firefox when charts are rendered using SVG. true | false | 1 | 0 */ underline?: boolean; /** * Sets the text's vertical alignment to one of the three applicable values, relative to the object's box. "top" | "middle" | "bottom * " */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; } interface scaleR { /** * Gauge Charts Only: To set custom labels that correspond to each tick mark on the scale. If there are more tick marks than labels, * the default scale values will be used for the remaining labels. ['A', 'B', 'C', 'D', 'E'] | ... */ labels?: any; /** * Gauge Charts Only: To set the number of minor tick marks displayed between the major tick marks. 9 | 5 | 2 | ... */ 'minor-ticks'?: number; minorTicks?: number; /** * Gauge Charts Only: To set the minimum, maximum, and step scale values. '0:10' | '0:25:5' | ... */ values?: any; center?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699' * , '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15 * , 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the size of the pivot point. 4 | "6px" | ... */ size?: number; /** * Sets the shape of the pivot point. 'circle' | 'diamond' | 'star5' | 'gear9' | ... */ type?: string; /** * Sets the x-coordinate position of the pivot point. 10 | "20px" | 0.3 | "30%" | ... */ x?: number; /** * Sets the visibility of the object. true | false */ visible?: boolean; /** * Sets the y-coordinate position of the pivot point. 10 | "20px" | 0.3 | "30%" | ... */ y?: number; }; guide?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the line color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699', * '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, * 15)' | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 1 | 3 | '6px' | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the visibility of the object. true | false */ visible?: boolean; }; item?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the angle of the object. 'auto' | 30 | 90 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699' * , '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15 * , 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object. 2 | 3 | '5px' | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the font color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object. 'Arial' | 'Tahoma,Verdana' | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object. 10 | 12 | '20px' | ... */ 'font-size'?: number; fontSize?: number; /** * Sets the font style of the object. 'italic' | 'normal' */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object. 'bold' | 'normal' */ 'font-weight'?: string; fontWeight?: string; /** * Sets the placement of the object. Negative values move the scale items inward. Positive values move the scale items outward. 0 | - * 20 | 30 | ... */ offsetR?: number; /** * Sets the padding of the object. 3 | '5px' | '10px' | ... */ padding?: number; /** * Sets the text transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 bei * ng completely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the visibility of the object. */ visible?: boolean; }; markers?: [ { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699' * , '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15 * , 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object. 2 | 3 | '5px' | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the line color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699', * '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, * 15)' | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 1 | 3 | '6px' | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets an ending offset for the scale marker. 0.1 | ... */ 'offset-end'?: number; offsetEnd?: number; /** * Sets a starting offset for the scale marker. 0.5 | ... */ 'offset-start'?: number; offsetStart?: number; /** * Sets the range of the scale marker. Provide one value for line scale markers and two values (starting and ending) for area scale m * arkers. [60] | [20,40] | ... */ range?: any; /** * Sets the scale marker type: area or line. 'area' | 'line' */ type?: string; label?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the angle of the object. 'auto' | 30 | 90 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699' * , '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15 * , 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object. 2 | 3 | '5px' | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the font color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object. 'Arial' | 'Tahoma,Verdana' | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object. 10 | 12 | '20px' | ... */ 'font-size'?: number; fontSize?: number; /** * Sets the font style of the object. 'italic' | 'normal' */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object. 'bold' | 'normal' */ 'font-weight'?: string; fontWeight?: string; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the placement of the object. Negative values move the scale items inward. Positive values move the scale items outward. 0 | - * 20 | 30 | ... */ offsetR?: number; /** * Sets the padding of the object. 3 | '5px' | '10px' | ... */ padding?: number; /** * Sets the text alignment of the object. 'left' | 'center' | 'right' */ 'text-align'?: string; textAlign?: string; /** * Sets the text transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 bei * ng completely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the width of the object. 50 | '200px' | ... */ width?: number; }; } ]; 'minor-guide'?: minorGuide; minorGuide?: minorGuide; 'minor-tick'?: minorTick; minorTick?: minorTick; ring?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699' * , '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15 * , 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the size of the object. 30 | '40px' | ... */ size?: number; items?: [ { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699' * , '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15 * , 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the size of the object. 30 | '40px' | ... */ size?: number; } ]; }; tick?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the line color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699', * '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, * 15)' | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 1 | 3 | '6px' | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the placement of the object. 'outer' | 'inner' | 'cross' */ placement?: string; /** * Sets the size of the object. 30 | '40px' | ... */ size?: number; /** * Sets the visibility of the object. true | false */ visible?: boolean; }; } interface scaleV { /** * Allows you to set the format for your scale-v values. You can use a combination of text and tokens (%v represents the scale values * ), e.g., “%v°” or “Variable %v”. 'Value: %v' */ format?: string; /** * Allows you to set custom labels for each step along scale-v. Note that if there are more steps than provided labels, the default v * alues will be used for the remaining labels. [...] */ labels?: any; /** * Used to set the minimum, maximum, and step scale values on scale-v. E.g., for “values”: “0:100:25”, 0 is the minimum, 100 is the m * aximum, and 25 is the step. "0:100:10" | [1,3,5,7] | ... */ values?: any; /** * Used to hide the v-axis. true | false */ visible?: boolean; guide?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the line color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 1 | 3 | '6px' | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the visibility of the object. true | false */ visible?: boolean; items?: [ { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that values require the leading zero before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'background-color'?: string; } ]; }; item?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the angle of the object. -45 | 30 | 120 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699' * , '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15 * , 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object. 2 | 3 | '5px' | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the font color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object. 'Arial' | 'Tahoma,Verdana' | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object. 10 | 12 | '20px' | ... */ 'font-size'?: number; fontSize?: number; /** * Sets the font style of the object. 'italic' | 'normal' */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object. 'bold' | 'normal' */ 'font-weight'?: string; fontWeight?: string; /** * Sets the padding of the object 3 | '5px' | '10px' | ... */ padding?: number; /** * Sets the text transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 bei * ng completely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; }; 'ref-line'?: refLine; refLine?: refLine; tick?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that values require the leading zero before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the line color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 4 | '6px' | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the placement of the object. 'outer' | 'inner' | 'cross' */ placement?: string; /** * Sets the size of the object. 4 | '6px' | ... */ size?: number; /** * Sets the visibility of the object. true | false */ visible?: boolean; }; tooltip?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the transparency of the border. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'border-alpha'?: number; borderAlpha?: number; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius (rounded corners) of the object. "3px" | "10px" */ 'border-radius'?: any; borderRadius?: any; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the font color of the object text. "none" | "transparent" | "purple" | "#33ccff" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object text. "Courier" | "Georgia" | "Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object text. 12 | "20px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the font style of the object text. "normal" | "italic" */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object text. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets the height of the object. 10 | "20px" | 0.3 | "30%" | ... */ height?: number; /** * Sets the padding around the object text. "10%" | "25px" ... */ padding?: number; /** * To create sticky tooltips. Use this with the "timeout" attribute, which allows you to specify how long you want the tooltips to "s * tick" to the chart. true | false | 1 |0 */ sticky?: boolean; /** * Specifies what text to display in the tooltips. Use with the %scale-value (%v) token. "Scale Tooltips" | "%v Days" | "..." */ text?: string; /** * Sets the transparency of the text. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comple * tely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * To create sticky tooltips. Provide a value in milliseconds. Use this with the "sticky" attribute, which specifies whether or not t * ooltips will "stick" to the chart. "30000 | 10000 | ... */ timeout?: number; /** * Sets the visibility of the object. true | false | 1 | 0 */ visible?: boolean; /** * Sets the width of the object. 10 | "20px" | 0.3 | "30%" | ... */ width?: number; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; } interface scaleX { /** * true | false | 1 | 0 */ 'auto-fit'?: boolean; autoFit?: boolean; /** * Sets whether the scale values will be displayed in scientific notation. Particularly useful when dealing with large numbers. true * | false | 1 | 0 */ exponent?: boolean; /** * Sets the number of decimals that will be displayed when using scientific notation. Use with the 'exponent' attribute. 5 | 10 | ... */ 'exponent-decimals'?: number; exponentDecimals?: number; /** * ''horizontal' | 'h' | 'vertical' | 'v' | 'row x col' | 'x col' | 'row x' | 'float'' */ layout?: string; /** * Sets the color of the axis line. 'none' | 'transparent' | '#f00' | '#f00 #00f' | 'red yellow' | 'rgb(100, 15, 15)' | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the gap size in case of a non-contiguous line style. 4 | '6px' | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Sets the segment size in case of a non-contiguous line style. 4 | '6px' | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Logarithmic Scales only: To set the base value, which defaults to Math.E (Euler's number, the base of natural logarithms). Math.E * | 10 | 2 | ... */ 'log-base'?: any; logBase?: any; /** * Sets the object's margin/s. 10 | '5px' | '10 20' | '5px 10px 15px 20px' | ... */ margin?: any; /** * Sets the object's bottom margin. 4 | '6px' | ... */ 'margin-bottom'?: any; marginBottom?: any; /** * Sets the object's left margin. 4 | '6px' | ... */ 'margin-left'?: any; marginLeft?: any; /** * Sets the object's right margin. 4 | '6px' | ... */ 'margin-right'?: any; marginRight?: any; /** * Sets the object's top margin. 4 | '6px' | ... */ 'margin-top'?: any; marginTop?: any; /** * Sets the max number of values displaying along the bottom horizontal line. 5 | 10 | ... */ 'max-items'?: number; maxItems?: number; /** * Sets the maximum number of labels that will display along the axis. 5 | 10 | ... */ 'max-labels'?: number; maxLabels?: number; /** * Sets the maximum number of ticks to display on the x axis. 5 | 10 | ... */ 'max-ticks'?: number; maxTicks?: number; /** * Sets the maximum value for the x axis. 'max-value': is one of the multiple ways you can set x axis values. Commonly used with time * series data. Also see 'mix-value': and 'step': 4 | '6px' | ... */ 'max-value'?: number; maxValue?: number; /** * Sets the number of minor tick marks displayed between the major tick marks. Note that this attribute is required to style the mino * r tick marks and/or guides. 5 | 10 | ... */ 'minor-ticks'?: number; minorTicks?: number; /** * Setting 'mirrored': true will reverse/mirror the x axis values. 'scale-x': {} values will read right to left. true | false | 1 | 0 */ mirrored?: boolean; /** * Sets the negative symbol just outside of the formatted value. 'standard' | 'currency' */ negation?: string; /** * Sets an offset from the end of the plotted data. This will cause the data to appear as if it were 'squeezed' from the right side. * 4 | '6px' | '5%' | 35%' | ... */ 'offset-end'?: number; offsetEnd?: number; /** * Sets an offset at the start of the plotted data. This will cause the data to appear as if it were 'squeezed' from the left side. 4 * | '6px' | '5%' | '35%' | ... */ 'offset-start'?: number; offsetStart?: number; /** * Sets an x offset that will be applied to the scale-x object. 4 | '6px' | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets the placement of the scale object. 'default' | 'opposite' */ placement?: string; /** * To change the scale type from linear (default) to logarithmic. 'lin' | 'log' */ progression?: string; /** * Used on radial charts (pie, radar, gauge) to specify the starting angle of the nodes. -45 | 115 | ... */ 'ref-angle'?: number; refAngle?: number; /** * To set the value the reference line is drawn at. 1 | 5 | 10 | ... */ 'ref-value'?: number; refValue?: number; /** * 5 | 10 | ... */ 'scale-factor'?: number; scaleFactor?: number; /** * Setting to true will cause the values on the x axis to use an abbreviated notation with a short unit such as K,M,B, etc. true | fa * lse | 1 | 0 */ short?: boolean; /** * Specifies which unit of measure to use when short is set to true. K | M | B | KB | MB | GB | TB | PB */ 'short-unit'?: string; shortUnit?: string; /** * ['A', 'B'] | ... */ 'show-labels'?: any; showLabels?: any; /** * When you set the 'thousands-separator': attribute, the punctuation which is used will be placed to separate digits which go into 1,000s, 10,000s, etc. When placed in the 'plot': { } object, * this will only effect values which are pulled directly from the series data. Objects such as 'scale-y': { }, 'scale-x': { }, etc..., will need to be set separately. * Default Value: null */ 'thousands-separator'?: string; thousandsSeparator?: string; /** * Sets the size of the object/shape. 4 | '6px' | ... */ size?: any; /** * An alternative way to create category scale labels. Similar to a 'labels' array, the 'values' array also acts as a maximum scale v * alue. [1, 7, 9] | ['Jan', 'Feb', 'Mar', 'Apr'] | ['Q1', 'Q2', 'Q3', 'Q4'] */ values?: any; /** * You can set the 'scale-x': { } to 'visible': false to hide the x axis. The x-axis will still calculate plots correctly, however yo * u will not be able to see the x axis line or any of the attributes such as scale values. If you simply want to hide the x axis lin * e you can utilize 'line-color':'none'. This will remove the visibility of the x axis line and still allow you to style ticks, item * s, etc separately, true | false | 1 | 0 */ visible?: boolean; /** * To turn on chart zooming on scale. Default is false. */ zooming?: boolean; /** * When zooming is enabled, setting zoom-snap to true snaps the zoom area to the nearest data node as a zoom area is selected. By def * ault, zoom-snap is set to false. true | false | 1 | 0 */ 'zoom-snap'?: boolean; zoomSnap?: boolean; guide?: { /** * Sets the transparency of the scale-x / scale-y guide. See the red lines. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the scale-x / scale-y guide. See the blue background in between the red lines. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the line color of the scale-x / scale-y guide. See the red lines. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow * " | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * When using a dashed or dotted line-type, this will set the size of each gap between line segments. Can be used with line-segment-s * ize to create unique dashed or dotted lines. For the scale-x / scale-y guide. See the space between red lines. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * When using a dashed or dotted line-type, this will set the size of each visible segment of line. Can be used with line-gap-size to * create unique dashed or dotted lines. For the scale-x / scale-y guide. See the red lines. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the scale-x / scale-y guide. See the red lines. "solid" | "dotted" | "dashed" | "da * shdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. For the scale-x / scale-y guide. See the red lines. 4 | "6px" * | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; items?: [ { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that values require the leading zero before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string } ]; }; item?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. 0....1 */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a two-color background gradient of the object. To be used with background-color-2. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a two-color background gradient of the object. To be used with background-color-1. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not. true | false | 1 | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the object's font color. Similar to font-color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, * 15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. Similar to angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the object's font color. Similar to color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" * | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style. Similar to italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight. Similar to bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the text is displayed with italic characters or not. true | false | 1 | 0 */ italic?: boolean; /** * If set to 'true', scale labels will lock in place and not rotate based upon the viewing angle in 3D charts. true | false | 1 | 0 */ 'lock-rotation'?: boolean; lockRotation?: boolean; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, with the first * value affecting the top padding, the second value affecting the right padding, and so on, in a clockwise direction. 10 | "5px" | " * 10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration to use underlined characters. Similar to underline. May not display properly in Mozilla Firefox when ch * arts are rendered using SVG. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text is displayed with underlined characters or not. Similar to text-decoration. May not display properly in Mozi * lla Firefox when charts are rendered using SVG. true | false | 1 | 0 */ underline?: boolean; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; label?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. In the scale-x / scale-y label. See the red * text. Works for output flash. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. In the scale-x / scale-y label. See the red text. Works for output canvas and svg. -4 * 5 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). In the scale-x / * scale-y label. See the red text. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. See the red text. Works f * or output canvas and svg. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not in the scale-x / scale-y label. See the red text. true | false | 1 * | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Cuts off extra text. Use with width. For the scale-x / scale-y label. See the red text. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the object's font color. Similar to font-color. For the scale-x / scale-y label. See the red text. "none" | "transparent" | " * #f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. For the scale-x / scale-y label. See the red text. -45 | 115 * | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. For the scale-x / scale-y label. See the red text. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. For the scale-x / scale-y label. See the red text. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. For the scale-x / scale-y label. See the red text. "linear" | " * radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. Similar to angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the object's font color. Similar to color. For the scale-x / scale-y label. See the red text. "none" | "transparent" | "#f00" * | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. For the scale-x / scale-y label. See the red text. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size. For the scale-x / scale-y label. See the red text. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style. Similar to italic. For the scale-x / scale-y label. See the red text. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight. Similar to bold. For the scale-x / scale-y label. See the red text. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. For the scale-x / scale-y label. See the red text. Works with output canvas and svg. 10 | "20px" | 0.3 | * "30%" | ... */ height?: any; /** * Sets whether the text is displayed with italic characters or not. For the scale-x / scale-y label. See the red text. true | false * | 1 | 0 */ italic?: boolean; /** * If set to 'true', scale labels will lock in place and not rotate based upon the viewing angle in 3D charts. */ 'lock-rotation'?: boolean; lockRotation?: boolean; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "...". For the scale-x / scale-y label. See the red text. 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, with the first * value affecting the top padding, the second value affecting the right padding, and so on, in a clockwise direction. 10 | "5px" | " * 10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration. Similar to underline. For output canvas and flash. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text is displayed with underlined characters or not. For output canvas and flash. true | false | 1 | 0 */ underline?: boolean; /** * Sets the visibility of the object. For the label. Used with output canvas and svg. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; labels?: any; markers?: [ { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Allows you to set how the label is aligned with the chart. "normal" | "opposite" | "auto" */ 'label-alignment'?: string; labelAlignment?: string; /** * Allows you to set how the label is placed on a graph. "normal" | "opposite" | "auto" */ 'label-placement'?: string; labelPlacement?: string; /** * Sets the line color of the object, applicable on non-closed shapes. See also border-color for closed shapes. "none" | "transparent * " | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. See also border-width for closed shapes. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Setting 'placement' to 'top' will overlay the marker on top of your charted data. By default, markers are set to 'placement':'bott * om', which will place the marker behind your charted data. top | bottom */ placement?: string; /** * To indicate the range you want the scale marker to span. Without specification, that range is based on the scale indexes. Add a "v * alue-range" attribute and set the value to true to set the range based on the scale values. Line scale markers accept one or two r * ange values. One value specifies the point that the scale marker is drawn at, similar to a reference line. Two values specify the * starting and ending points, appearing as an angled line. Area scale markers accept two or four range values. Two values specify th * e starting and ending points, always appearing as a rectangle shape. Four values specify the connecting points of the scale marker * , allowing you to create various trapezoid shapes. [1] | [3,4] | [3,4,5,6] | ... */ range?: any; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the marker type to either a single line or a marker that will cover an area. "line" | "area" */ type?: string; /** * To use with the "range" array. When set to true, the scale marker (area or line) accommodates values, including Unix timestamps, a * s your starting and ending values. E.g., "range": [30,34] or "range": [1420491600000,1422651600000]. true | false (default) | 1 | * 0 */ 'value-range'?: boolean; valueRange?: boolean; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; label?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the angle of the object. 'auto' | 30 | 90 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699' * , '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15 * , 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object. 2 | 3 | '5px' | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the font color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object. 'Arial' | 'Tahoma,Verdana' | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object. 10 | 12 | '20px' | ... */ 'font-size'?: number; fontSize?: number; /** * Sets the font style of the object. 'italic' | 'normal' */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object. 'bold' | 'normal' */ 'font-weight'?: string; fontWeight?: string; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the padding of the object. 3 | '5px' | '10px' | ... */ padding?: number; /** * Sets the text alignment of the object. 'left' | 'center' | 'right' */ 'text-align'?: string; textAlign?: string; /** * Sets the text transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 bei * ng completely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the width of the object. 50 | '200px' | ... */ width?: number; }; } ]; 'minor-guide'?: minorGuide; minorGuide?: minorGuide; 'minor-tick'?: minorTick; minorTick?: refLine; refLine?: refLine; rules?: [ { /** * Allows you to specify what portions of a chart to apply selected attributes to. '%v > 0' | '%v >= 5' | ... */ rule?: string; } ]; tick?: { /** * Sets the transparency of the tick. In the example, the scale-x ticks are vertical lines | in red in between the months. 0.3 | 0.9 * | ... */ alpha?: number; /** * Sets the line color of the object, applicable on non-closed shapes. See also border-color for closed shapes. "none" | "transparent * " | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. See also border-width for closed shapes. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Determines the placement of tick marks along an axis line. inner | cross | outer */ placement?: string; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. Has limited effect on HTML5 im * plementation. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. Has limited effect on HTML5 implementation. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. Has limited effect on HTML5 implementation. "none" | "transparent" | "#f00" | "#f00 #0 * 0f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; }; tooltip?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the transparency of the border. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'border-alpha'?: number; borderAlpha?: number; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius (rounded corners) of the object. "3px" | "10px" */ 'border-radius'?: any; borderRadius?: any; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the font color of the object text. "none" | "transparent" | "purple" | "#33ccff" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object text. "Courier" | "Georgia" | "Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object text. 12 | "20px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the font style of the object text. "normal" | "italic" */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object text. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets the height of the object. 10 | "20px" | 0.3 | "30%" | ... */ height?: number; /** * Sets the padding around the object text. "10%" | "25px" ... */ padding?: number; /** * To create sticky tooltips. Use this with the "timeout" attribute, which allows you to specify how long you want the tooltips to "s * tick" to the chart. true | false | 1 |0 */ sticky?: boolean; /** * Specifies what text to display in the tooltips. Use with the %scale-value (%v) token. "Scale Tooltips" | "%v Days" | "..." */ text?: string; /** * Sets the transparency of the text. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comple * tely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * To create sticky tooltips. Provide a value in milliseconds. Use this with the "sticky" attribute, which specifies whether or not t * ooltips will "stick" to the chart. "30000 | 10000 | ... */ timeout?: number; /** * Sets the visibility of the object. true | false | 1 | 0 */ visible?: boolean; /** * Sets the width of the object. 10 | "20px" | 0.3 | "30%" | ... */ width?: number; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; transform?: { /** * To format your date values. Use this attribute with the `type` value (set to `true`). Token Description `%A` Displays the ante or * post meridiem time in upper case letters: AM or PM. `%a` Displays the ante or post meridiem time in lower case letters: am or pm. * `%D` Displays the day of the week in abbreviated form: Sun, Mon, Tue, Wed, Thu, Fri. `%d` Displays the day's date without a leadin * g 0 if the date is single digit. `%dd` Displays the day's date with a leading 0 if the date is single digit. `%G` Displays the hou * r in 24-hour format without a leading 0. `%g` Displays the hour in 12-hour format without a leading 0. `%H` Displays the hour in 2 * 4-hour format with a leading 0 if the hour is single digit. `%h` Displays the hour in 12-hour format with a leading 0 if the hour * is single digit. `%i` Displays the minutes. `%M` Displays the month in abbreviated form: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, S * ep, Oct, Nov and Dec. `%m` Displays the month numerically without a leading 0 if the date is single digit. `%mm` Display the month * numerically with a leading 0 if the month is single digit. `%q` Displays the milliseconds. `%s` Displays the seconds. `%Y` Displa * ys the year in 4-digit format. `%y` Displays the year in 2-digit format. */ all?: string; '`%A`'?: any; '`%a`'?: any; '`%D`'?: any; '`%d`'?: any; '`%dd`'?: any; '`%G`'?: any; '`%g`'?: any; '`%H`'?: any; '`%h`'?: any; '`%i`'?: any; '`%M`'?: any; '`%m`'?: any; '`%mm`'?: any; '`%q`'?: any; '`%s`'?: any; '`%Y`'?: any; '`%y`'?: any; guide?: { /** * Sets the transparency of the scale-x / scale-y guide. See the red lines. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the line color of the scale-x / scale-y guide. See the red lines. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow * " | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the style applied to lines and borders of the scale-x / scale-y guide. See the red lines. "solid" | "dotted" | "dashed" | "da * shdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. For the scale-x / scale-y guide. See the red lines. 4 | "6px" * | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; }; item?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not. true | false | 1 | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Cuts off extra text. Use with width. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the object's font color. Similar to font-color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, * 15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. Similar to angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the object's font color. Similar to color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" * | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style. Similar to italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight. Similar to bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the text is displayed with italic characters or not. true | false | 1 | 0 */ italic?: boolean; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, with the first * value affecting the top padding, the second value affecting the right padding, and so on, in a clockwise direction. 10 | "5px" | " * 10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration to use underlined characters. Similar to underline. May not display properly in Mozilla Firefox when ch * arts are rendered using SVG. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text is displayed with underlined characters or not. Similar to text-decoration. May not display properly in Mozi * lla Firefox when charts are rendered using SVG. true | false | 1 | 0 */ underline?: boolean; /** * Sets the text's vertical alignment to one of the three applicable values, relative to the object's box. "top" | "middle" | "bottom * " */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; }; } interface scaleY { /** * Sets the text's transparency of the scale-y (The vertical scale line on the chart). 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * true | false | 1 | 0 */ 'auto-fit'?: boolean; autoFit?: boolean; /** * Sets the number of decimals which will be displayed as scale-y values. Note this attribute does round the values to fit within the * define number of decimals. 5 | 10 | ... */ decimals?: number; /** * Sets the separator to be used in place of the default decimal point. Any string or character can be used to replace the decimal. ' * .' | ',' | ... */ 'decimals-separator'?: string; decimalsSeparator?: string; /** * Sets whether the scale values will be displayed in scientific notation. Particularly useful when dealing with large numbers. true * | false | 1 | 0 */ exponent?: boolean; /** * Sets the number of decimals that will be displayed when using scientific notation. Use with the 'exponent' attribute. 5 | 10 | ... */ 'exponent-decimals'?: number; exponentDecimals?: number; /** * To format the appearance of the scale values. Use with the %scale-value (%v) token. '%v%' | '$%v' | '%v' | ... */ format?: string; /** * To force all of the scale items to display. It is generally used with the 'max-items' attribute. true | false | 1 | 0 */ 'items-overlap'?: boolean; itemsOverlap?: boolean; /** * Allows you to set custom labels that correspond to each of the ticks on a scale. If there are more ticks than labels, the default * values will be used for the remaining labels. ['Jan', 'Feb', 'Mar', ...] | ... */ labels?: any; /** * ''horizontal' | 'h' | 'vertical' | 'v' | 'row x col' | 'x col' | 'row x' | 'float'' */ layout?: string; /** * Sets the color of the axis line. 'none' | 'transparent' | '#f00' | '#f00 #00f' | 'red yellow' | 'rgb(100, 15, 15)' | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | '6px' | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | '6px' | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the line style of the axis line. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the width of the axis line. 4 | '6px' | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Logarithmic Scales only: To set the base value, which defaults to Math.E (Euler's number, the base of natural logarithms). Math.E * | 10 | 2 | ... */ 'log-base'?: any; logBase?: any; /** * Sets the object's margin/s. 10 | '5px' | '10 20' | '5px 10px 15px 20px' | ... */ margin?: any; /** * Sets the object's bottom margin. 4 | '6px' | ... */ 'margin-bottom'?: any; marginBottom?: any; /** * Sets the object's left margin. 4 | '6px' | ... */ 'margin-left'?: any; marginLeft?: any; /** * Sets the object's right margin. 4 | '6px' | ... */ 'margin-right'?: any; marginRight?: any; /** * Sets the object's top margin. 4 | '6px' | ... */ 'margin-top'?: any; marginTop?: any; /** * Sets the max number of values displaying along the bottom horizontal line. 5 | 10 | ... */ 'max-items'?: number; maxItems?: number; /** * To set the maximum number of scale items displayed. It is generally used with the 'items-overlap'attribute. 5 | 10 | ... */ 'max-labels'?: number; maxLabels?: number; /** * Sets the maximum number of ticks to display on the y axis. 5 | 10 | ... */ 'max-ticks'?: number; maxTicks?: number; /** * Sets the maximum value for the y axis. 'max-value': is one of the multiple ways you can set y axis values. Commonly used with time * series data. Also see 'mix-value': and 'step': 4 | '6px' | ... */ 'max-value'?: number; maxValue?: number; /** * Sets the minimum value for the y axis. 'min-value': is one of the multiple ways you can set y axis values. Commonly used with time * series data. Also see 'max-value': and 'step': 'auto' | 4 | '6px' | ... */ 'min-value'?: number; minValue?: number; /** * Sets the number of minor tick marks displayed between the major tick marks. Note that this attribute is required to style the mino * r tick marks and/or guides. 5 | 10 | ... */ 'minor-ticks'?: number; minorTicks?: number; /** * Setting 'mirrored': true will flip/mirror the y axis values. 'scale-y': {} values will read top to bottom. true | false | 1 | 0 */ mirrored?: boolean; /** * Setting 'multiplier': true will abbreviate long numbers as small digits with a short unit indicator such as K, M, B true | false | * 1 | 0 */ multiplier?: boolean; /** * Sets the negative symbol just outside of the formatted value. 'standard' | 'currency' */ negation?: string; /** * Sets an offset on both sides of the plotted data. This will cause the data to appear as if it were 'squeezed' together. 4 | '6px' * | ... */ offset?: number; /** * Sets an offset from the end of the plotted data. This will cause the data to appear as if it were 'squeezed' from the top side. 4 * | '6px' | '5%' | 35%' | ... */ 'offset-end'?: number; offsetEnd?: number; /** * Sets an offset at the start of the plotted data. This will cause the data to appear as if it were 'squeezed' from the bottom side. * 4 | '6px' | '5%' | 35%' | ... */ 'offset-start'?: number; offsetStart?: number; /** * Sets an x offset that will be applied to the scale-y object. 4 | '6px' | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a y offset that will be applied to the scale-y object. 4 | '6px' | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the placement of the scale object. 'default' | 'opposite' */ placement?: string; /** * To change the scale type from linear (default) to logarithmic. 'lin' | 'log' */ progression?: string; /** * Used on radial charts (pie, radar, gauge) to specify the starting angle of the nodes. -45 | 115 | ... */ 'ref-angle'?: number; refAngle?: number; /** * To set the value the reference line is drawn at. 5 | 10 | ... */ 'ref-value'?: number; refValue?: number; /** * Sets the scale of the y axis 5 | 10 | ... */ 'scale-factor'?: number; scaleFactor?: number; /** * Setting to true will cause the values on the y axis to use an abbreviated notation with a short unit such as K,M,B, etc. true | fa * lse | 1 | 0 */ short?: boolean; /** * Specifies which unit of measure to use when short is set to true. K | M | B | KB | MB | GB | TB | PB */ 'short-unit'?: string; shortUnit?: string; /** * Specifies which labels will be visible on the y axis. ['A', 'B'] | ... */ 'show-labels'?: any; showLabels?: any; /** * Sets the size of the object/shape. 4 | '6px' | ... */ size?: any; /** * Auto size-factor automatically scales a pie chart to allow all value-box objects to appear without clipping. 'auto' */ 'size-factor'?: string; sizeFactor?: string; /** * Sets the characters used to separate thousands in larger numbers. '.' | ',' | ... */ 'thousands-separator'?: string; thousandsSeparator?: string; /** * An alternative way to create category scale labels. Similar to a 'labels' array, the 'values' array also acts as a maximum scale v * alue. [1, 7, 9] | ['Jan', 'Feb', 'Mar', 'Apr'] | ['Q1', 'Q2', 'Q3', 'Q4'] */ values?: any; /** * You can set the 'scale-y': { } to 'visible': false to hide the y axis. The y-axis will still calculate plots correctly, however yo * u will not be able to see the x axis line or any of the attributes such as scale values. If you simply want to hide the x axis lin * e you can utilize 'line-color':'none'. This will remove the visibility of the x axis line and still allow you to style ticks, item * s, etc separately, true | false | 1 | 0 */ visible?: boolean; /** * To turn on chart zooming on scale. Default is false. */ zooming?: boolean; /** * When zooming is enabled, setting zoom-snap to true snaps the zoom area to the nearest data node as a zoom area is selected. By def * ault, zoom-snap is set to false. true | false | 1 | 0 */ 'zoom-snap'?: boolean; zoomSnap?: boolean; guide?: { /** * Sets the transparency of the scale-x / scale-y guide. See the red lines. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the scale-x / scale-y guide. See the blue background in between the red lines. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the line color of the scale-x / scale-y guide. See the red lines. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow * " | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * When using a dashed or dotted line-type, this will set the size of each gap between line segments. Can be used with line-segment-s * ize to create unique dashed or dotted lines. For the scale-x / scale-y guide. See the space between red lines. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * When using a dashed or dotted line-type, this will set the size of each visible segment of line. Can be used with line-gap-size to * create unique dashed or dotted lines. For the scale-x / scale-y guide. See the red lines. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the scale-x / scale-y guide. See the red lines. "solid" | "dotted" | "dashed" | "da * shdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. For the scale-x / scale-y guide. See the red lines. 4 | "6px" * | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; items?: [ { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that values require the leading zero before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string } ]; }; item?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. 0....1 */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a two-color background gradient of the object. To be used with background-color-2. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a two-color background gradient of the object. To be used with background-color-1. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not. true | false | 1 | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the object's font color. Similar to font-color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, * 15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. Similar to angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the object's font color. Similar to color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" * | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style. Similar to italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight. Similar to bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the text is displayed with italic characters or not. true | false | 1 | 0 */ italic?: boolean; /** * If set to 'true', scale labels will lock in place and not rotate based upon the viewing angle in 3D charts. true | false | 1 | 0 */ 'lock-rotation'?: boolean; lockRotation?: boolean; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, with the first * value affecting the top padding, the second value affecting the right padding, and so on, in a clockwise direction. 10 | "5px" | " * 10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration to use underlined characters. Similar to underline. May not display properly in Mozilla Firefox when ch * arts are rendered using SVG. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text is displayed with underlined characters or not. Similar to text-decoration. May not display properly in Mozi * lla Firefox when charts are rendered using SVG. true | false | 1 | 0 */ underline?: boolean; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; label?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. In the scale-x / scale-y label. See the red * text. Works for output flash. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. In the scale-x / scale-y label. See the red text. Works for output canvas and svg. -4 * 5 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). In the scale-x / * scale-y label. See the red text. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. See the red text. Works f * or output canvas and svg. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not in the scale-x / scale-y label. See the red text. true | false | 1 * | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Cuts off extra text. Use with width. For the scale-x / scale-y label. See the red text. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the object's font color. Similar to font-color. For the scale-x / scale-y label. See the red text. "none" | "transparent" | " * #f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. For the scale-x / scale-y label. See the red text. -45 | 115 * | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. For the scale-x / scale-y label. See the red text. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. For the scale-x / scale-y label. See the red text. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. For the scale-x / scale-y label. See the red text. "linear" | " * radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. Similar to angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the object's font color. Similar to color. For the scale-x / scale-y label. See the red text. "none" | "transparent" | "#f00" * | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. For the scale-x / scale-y label. See the red text. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size. For the scale-x / scale-y label. See the red text. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style. Similar to italic. For the scale-x / scale-y label. See the red text. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight. Similar to bold. For the scale-x / scale-y label. See the red text. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. For the scale-x / scale-y label. See the red text. Works with output canvas and svg. 10 | "20px" | 0.3 | * "30%" | ... */ height?: any; /** * Sets whether the text is displayed with italic characters or not. For the scale-x / scale-y label. See the red text. true | false * | 1 | 0 */ italic?: boolean; /** * If set to 'true', scale labels will lock in place and not rotate based upon the viewing angle in 3D charts. */ 'lock-rotation'?: boolean; lockRotation?: boolean; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "...". For the scale-x / scale-y label. See the red text. 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, with the first * value affecting the top padding, the second value affecting the right padding, and so on, in a clockwise direction. 10 | "5px" | " * 10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration. Similar to underline. For output canvas and flash. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text is displayed with underlined characters or not. For output canvas and flash. true | false | 1 | 0 */ underline?: boolean; /** * Sets the visibility of the object. For the label. Used with output canvas and svg. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; markers?: [ { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Allows you to set how the label is aligned with the chart. "normal" | "opposite" | "auto" */ 'label-alignment'?: string; labelAlignment?: string; /** * Allows you to set how the label is placed on the chart. "normal" | "opposite" | "auto" */ 'label-placement'?: string; labelPlacement?: string; /** * Sets the line color of the object, applicable on non-closed shapes. See also border-color for closed shapes. "none" | "transparent * " | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. See also border-width for closed shapes. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Setting 'placement' to 'top' will overlay the marker on top of your charted data. By default, markers are set to 'placement':'bott * om', which will place the marker behind your charted data. top | bottom */ placement?: string; /** * To indicate the range you want the scale marker to span. Without specification, that range is based on the scale indexes. Add a "v * alue-range" attribute and set the value to true to set the range based on the scale values. Line scale markers accept one or two r * ange values. One value specifies the point that the scale marker is drawn at, similar to a reference line. Two values specify the * starting and ending points, appearing as an angled line. Area scale markers accept two or four range values. Two values specify th * e starting and ending points, always appearing as a rectangle shape. Four values specify the connecting points of the scale marker * , allowing you to create various trapezoid shapes. [1] | [3,4] | [3,4,5,6] | ... */ range?: any; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the marker type to either a single line or a marker that will cover an area. "line" | "area" */ type?: string; /** * To use with the "range" array. When set to true, the scale marker (area or line) accommodates values, including Unix timestamps, a * s your starting and ending values. E.g., "range": [30,34] or "range": [1420491600000,1422651600000]. true | false (default) | 1 | * 0 */ 'value-range'?: boolean; valueRange?: boolean; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; label?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the angle of the object. 'auto' | 30 | 90 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699' * , '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15 * , 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object. 2 | 3 | '5px' | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the font color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object. 'Arial' | 'Tahoma,Verdana' | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object. 10 | 12 | '20px' | ... */ 'font-size'?: number; fontSize?: number; /** * Sets the font style of the object. 'italic' | 'normal' */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object. 'bold' | 'normal' */ 'font-weight'?: string; fontWeight?: string; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the padding of the object. 3 | '5px' | '10px' | ... */ padding?: number; /** * Sets the text alignment of the object. 'left' | 'center' | 'right' */ 'text-align'?: string; textAlign?: string; /** * Sets the text transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 bei * ng completely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the width of the object. 50 | '200px' | ... */ width?: number; }; } ]; 'minor-guide'?: minorGuide; minorGuide?: minorGuide; 'minor-tick'?: minorTick; minorTick?: minorTick; 'ref-line'?: refLine; refLine?: refLine; rules?: [ { /** * Allows you to specify what portions of a chart to apply selected attributes to. '%v > 0' | '%v >= 5' | ... */ rule?: string; } ]; tick?: { /** * Sets the transparency of the tick. In the example, the scale-x ticks are vertical lines | in red in between the months. 0.3 | 0.9 * | ... */ alpha?: number; /** * Sets the line color of the object, applicable on non-closed shapes. See also border-color for closed shapes. "none" | "transparent * " | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. See also border-width for closed shapes. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Determines the placement of tick marks along an axis line. inner | cross | outer */ placement?: string; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. Has limited effect on HTML5 im * plementation. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. Has limited effect on HTML5 implementation. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. Has limited effect on HTML5 implementation. "none" | "transparent" | "#f00" | "#f00 #0 * 0f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; }; tooltip?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the transparency of the border. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'border-alpha'?: number; borderAlpha?: number; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius (rounded corners) of the object. "3px" | "10px" */ 'border-radius'?: any; borderRadius?: any; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the font color of the object text. "none" | "transparent" | "purple" | "#33ccff" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object text. "Courier" | "Georgia" | "Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object text. 12 | "20px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the font style of the object text. "normal" | "italic" */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object text. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets the height of the object. 10 | "20px" | 0.3 | "30%" | ... */ height?: number; /** * Sets the padding around the object text. "10%" | "25px" ... */ padding?: number; /** * To create sticky tooltips. Use this with the "timeout" attribute, which allows you to specify how long you want the tooltips to "s * tick" to the chart. true | false | 1 |0 */ sticky?: boolean; /** * Specifies what text to display in the tooltips. Use with the %scale-value (%v) token. "Scale Tooltips" | "%v Days" | "..." */ text?: string; /** * Sets the transparency of the text. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comple * tely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * To create sticky tooltips. Provide a value in milliseconds. Use this with the "sticky" attribute, which specifies whether or not t * ooltips will "stick" to the chart. "30000 | 10000 | ... */ timeout?: number; /** * Sets the visibility of the object. true | false | 1 | 0 */ visible?: boolean; /** * Sets the width of the object. 10 | "20px" | 0.3 | "30%" | ... */ width?: number; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; transform?: { /** * The text of the scale label, can use tokens for day, hour, minute, year etc to add in such information, ONLY if "type"="date" has * been specified in this transform object. If values for both "text" and "all" have been specified, the value in "text" will be used * . 'Month of %M' | '%d' | ... */ text?: string; /** * To convert Unix timestamps into dates. Use this attribute with the all attribute. 'date' */ type?: string; /** * To set the time-series scale to linear (uniform) or non-linear. true | false | 1 | 0 */ uniform?: boolean; }; } interface scrollXSCrollY { /** * Sets an x offset that will be applied to the scroll-x object. 4 | '6px' | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a y offset that will be applied to the scroll-x object. 4 | '6px' | ... */ 'offset-y'?: any; offsetY?: any; bar?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border radius (rounded corners) of the object. The higher the value, the more rounded the corners appear. 4 | "6px" | "6p * x 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * X-Axis Scrollbar only: Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Y-Axis Scrollbar only: Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; }; handle?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the styling for the bottom border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a s * tring. "1px solid green" | "3px dotted purple" | ... */ 'border-bottom'?: any; borderBottom?: any; /** * Sets the styling for the left border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a str * ing. "1px solid green" | "3px dotted purple" | ... */ 'border-left'?: any; borderLeft?: any; /** * Sets the border radius (rounded corners) of the object. The higher the value, the more rounded the corners appear. 4 | "6px" | "6p * x 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the styling for the right border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a st * ring. "1px solid green" | "3px dotted purple" | ... */ 'border-right'?: any; borderRight?: any; /** * Sets the styling for the top border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a stri * ng. "1px solid green" | "3px dotted purple" | ... */ 'border-top'?: any; borderTop?: any; /** * X-Axis Scrollbar only: Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Y-Axis Scrollbar only: Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; }; } interface selectedMarker { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. See the boxes at each point when clicked. Wo * rks with output flash. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; /** * Sets the type of the object/shape. "pie" | "circle" | "star5" | ... */ type?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; } interface selectedState { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the line color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line width of the object, applicable on non-closed shapes. See also border-width for closed shapes. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; } interface trendDown { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the line color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line width of the object. 1 | 3 | | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; } interface trendEqual { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the line color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line width of the object. 1 | 3 | | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; } interface trendUp { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the line color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line width of the object. 1 | 3 | | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; } interface valueBox { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Note that values require the leading 0 before the decimal point. Use with "background-color" attribute. 0.3 | 0.4 | * 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object. A positive value will turn it in a clockwise direction. A negative value will turn it in a * counterclockwise direction. -90 | 270 | 180 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#FF0 * 000", "#0000FF"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). One color will set a solid background color. Two colors * will, by default, create a horizontal gradient. For more complex gradients, use "gradient-colors" and "gradient-stops". "none" | " * transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a two-color background gradient. To be used with "background-color-2". "none" | "transparent" | "#f00" | " * #f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a two-color background gradient. To be used with "background-color-1". "none" | "transparent" | "#f00" | * "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction(s) in which the background image is being stretched. Works with "background-image". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the "background-repeat" attribute is set to "no-repeat". "0 0" | "50 100" | "80% 60%" | . * .. */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. Works with "background-image". "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the transparency of the border. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'border-alpha'?: number; borderAlpha?: number; /** * Sets the border color of the object, applicable on closed shapes. See the "line-color" attribute for closed shapes. "none" | "tran * sparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See the "line-width" attribute for closed shapes. 4 | "6px" | .. * . */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets whether or not the object will have a callout arrow. true | false | 1 | 0 */ callout?: boolean; /** * Allows you to set the number of decimal places displayed for each value. 2 | 3 | 10 | ... */ decimals?: number; /** * Allows you to set the decimal mark displayed for each value. "." | "," | " " | ... */ 'decimals-separator'?: string; decimalsSeparator?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the object. 5 | "10px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets a Y offset to apply to the object. 5 | "10px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the font color of the value box text. Similar to the "color" attribute. "none" | "transparent" | "#f00" | "#f00 #00f" | "red * yellow" | "rgb(100, 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the value box text. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the value box text. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the font style of the value box text. Similar to the "italic" attribute. "none" | "italic" */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the value box text. Similar to the "bold" attribute. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets the colors for a complex background gradient consisting of two or more colors. Use with the "gradient-stops" attribute. Works * with output svg. "#f00 #0f0 #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of two or more colors. Use with the "gradient-colors" attribu * te. Works with output svg. "0.1 0.5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets an X offset to apply when positioning the object. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the padding around the text of the object. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Specifies where the value boxes are placed in relation to the data points. Options by chart type: "in" | "out" | "auto" | "left" | * "right" | "over" | ... */ placement?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether or not the object's shadow is visible. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the transparency of the text. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comple * tely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the character used to separate thousands. "," | "." | " " | ... */ 'thousands-separator'?: string; thousandsSeparator?: string; /** * Specifies which value boxes are displayed. By default, all values in a series are displayed. You can also display the minimum, max * imum, first, last, and/or no values. "all" | "min" | "max" | "first" | "last" | none" | "min,max" | "first,last,min,max" | ... */ type?: string; /** * Sets the visibility of the value box object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | * 0 */ visible?: boolean; connector?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that values require the leading zero before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the line color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line style of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; }; joined?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that values require the leading zero before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object. 2 | 3 | '5px' | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the font color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font size of the object. 10 | 12 | '20px' | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the padding of the object. 3 | '5px' | '10px' | ... */ padding?: number; /** * Sets the joined venn diagram text to display. 'Joined' | '%joined-value' | ... */ text?: string; }; shared?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that values require the leading zero before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object. 2 | 3 | '5px' | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the font color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font size of the object. 10 | 12 | '20px' | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the padding of the object. 3 | '5px' | '10px' | ... */ padding?: number; /** * Sets the shared venn diagram text to display. 'Shared' | '%shared-value' | ... */ text?: string; }; } interface globals { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require a leading zero before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the border color of the object, applicable to closed shapes. "none" | "transparent" | "#1A237E" | "purple" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object, applicable to closed shapes. "3px" | "7px" | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object, applicable to closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the font color of the object. "none" | "transparent" | "#1A237E" | "purple" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object. 12 | "20px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the font weight of the object. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets the line color of the object, applicable to non-closed shapes. "none" | "transparent" | "#1A237E" | "purple" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line style of the object, applicable to non-closed shapes. "solid" | "dashed" | "dotted" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable to non-closed shapes. 4 | "6px" | ... */ 'line-width'?: number; } interface graphset { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius (rounded corners) of the object. "3px" | "10px" */ 'border-radius'?: any; borderRadius?: any; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets the height of the object. 10 | "20px" | 0.3 | "30%" | ... */ height?: number; /** * Sets the line style of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * The type of the chart "line" | "bar"... */ type?: string; /** * Sets the width of the object. 10 | "20px" | 0.3 | "30%" | ... */ width?: number; '3d-aspect'?: { /** * Sets the view angle when using the isometric 3D engine. Value can be between 0 and 90, with the default viewing angle being 45°. 5 * | 10 | ... */ angle?: number; /** * Sets the Z depth for a 3D chart type displayed in either isometric or true 3D. 5 | 10 | ... */ depth?: number; /** * Sets whether the chart uses a true 3D engine or an isometric view. Disabling true3d forces an isometric view. true | false | 1 | 0 */ true3d?: boolean; /** * Sets the X rotation viewing angle for the true 3D view. Viewing angle may vary depending on the chart type. 5 | 10 | ... */ 'x-angle'?: number; xAngle?: number; /** * Sets the Y rotation viewing angle for the true 3D view. Viewing angle may vary depending on the chart type. 5 | 10 | ... */ 'y-angle'?: number; yAngle?: number; /** * Sets the Z rotation viewing angle for the true 3D view. Viewing angle may vary depending on the chart type. 5 | 10 | ... */ 'z-angle'?: number; zAngle?: number; /** * Sets the perspective zoom for the true 3D view. The default zoom level is 1.0. Note that a leading 0 is required before the decima * l for values less than 1.0. 1 | 1.5 | 0.8 | ... */ zoom?: number; }; '3dAspect'?: { /** * Sets the view angle when using the isometric 3D engine. Value can be between 0 and 90, with the default viewing angle being 45°. 5 * | 10 | ... */ angle?: number; /** * Sets the Z depth for a 3D chart type displayed in either isometric or true 3D. 5 | 10 | ... */ depth?: number; /** * Sets whether the chart uses a true 3D engine or an isometric view. Disabling true3d forces an isometric view. true | false | 1 | 0 */ true3d?: boolean; /** * Sets the X rotation viewing angle for the true 3D view. Viewing angle may vary depending on the chart type. 5 | 10 | ... */ 'x-angle'?: number; xAngle?: number; /** * Sets the Y rotation viewing angle for the true 3D view. Viewing angle may vary depending on the chart type. 5 | 10 | ... */ 'y-angle'?: number; yAngle?: number; /** * Sets the Z rotation viewing angle for the true 3D view. Viewing angle may vary depending on the chart type. 5 | 10 | ... */ 'z-angle'?: number; zAngle?: number; /** * Sets the perspective zoom for the true 3D view. The default zoom level is 1.0. Note that a leading 0 is required before the decima * l for values less than 1.0. 1 | 1.5 | 0.8 | ... */ zoom?: number; }; arrows?: [ { /** * Sets the text's font angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the text's color. Similar to color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the arrow's label font size. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Text displayed in a label over the arrow. "Upturn" | "10% decrease" | ... */ text?: string; /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the arrow head width and head height. The first numeric entry in the array sets the head width and the second entry sets the * head height. [...] */ aspect?: any; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the direction of the arrow "top" | "bottom" | "left" | "right" */ direction?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the length of the arrow. 50 | 100 | ... */ length?: number; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; from?: { /** * Sets the arrow's starting point to that of a charted value. The plot value refers to the set of values in a series, and the index * refers to the specific value within that series. For example, node:plot=0,index=10 sets the starting point of the arrow at the 11t * h value within the 1st set of values in the series. Note that 0 refers to the first value or set of values, with 1 being the secon * d value or set of values, and so on. "node:index=4" | "node:plot=0,index=1" | ... */ hook?: string; /** * Sets an x-offset for the arrow's starting point. Can be used to make adjustments to an arrow's starting x ordinate or hook point. * 10 | 56 | ... */ 'offset-x'?: number; offsetX?: number; /** * Sets a y-offset for the arrow's starting point. Can be used to make adjustments to an arrow's starting y ordinate or hook point. 1 * 0 | 56 | ... */ 'offset-y'?: number; offsetY?: number; /** * Sets the x ordinate for an arrow's starting point. Ordinates are counted in pixels, starting from the top-left corner of the chart * . 100 | 450 | ... */ x?: number; /** * Sets the y ordinate for an arrow's starting point. Ordinates are counted in pixels, starting from the top-left corner of the chart * . 100 | 450 | ... */ y?: number; }; to?: { /** * Sets the arrow's end point to that of a charted value. The plot value refers to the set of values in a series, and the index refer * s to the specific value within that series. For example, node:plot=0,index=10 sets the end point of the arrow at the 11th value wi * thin the 1st set of values in the series. Note that 0 refers to the first value or set of values, with 1 being the second value or * set of values, and so on. "node:index=4" | "node:plot=0,index=1" | ... */ hook?: string; /** * Sets an x-offset for the arrow's end point. Can be used to make adjustments to an arrow's end x ordinate or hook point. 10 | 56 | * ... */ 'offset-x'?: number; offsetX?: number; /** * Sets a y-offset for the arrow's end point. Can be used to make adjustments to an arrow's end y ordinate or hook point. 10 | 56 | . * .. */ 'offset-y'?: number; offsetY?: number; /** * Sets the x ordinate for an arrow's end point. Ordinates are counted in pixels, starting from the top-left corner of the chart. 100 * | 450 | ... */ x?: number; /** * Sets the y ordinate for an arrow's end point. Ordinates are counted in pixels, starting from the top-left corner of the chart. 100 * | 450 | ... */ y?: number; }; } ]; crosshair?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * X-Axis Crosshairs Only: When true, plot nodes will be highlighted only when the guide is directly next to the node. When false (th * e default setting), the plot nodes closest to the guide will be highlighted. true | false | 1 | 0 */ exact?: boolean; /** * Sets the line color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Reverses the order of items in plotLabel. Generally used with positive stacked charts. */ 'reverse-series'?: boolean; reverseSeries?: boolean; /** * X-Axis Crosshairs Only: For graphsets with multiple chart objects, setting the attribute to true in "crosshair-x" will allow you t * o use crosshairs across all charts simultaneously. true | false | 1 | 0 */ shared?: boolean; /** * X-Axis Crosshairs Only: Sets the mode used to display crosshair plot-labels. When set to "move" (the default setting), plot-labels * for all nodes will be displayed. The "hover" setting will allow only one plot-label to be displayed at a time, with the visibilit * y of each label being triggered when the user hovers over a node. "move" | "hover" */ trigger?: string; /** * Y-Axis Crosshairs Only: Sets the type of the "crosshair-y", either in single mode (one line for all scales) or multiple (a line fo * r every plot). "single" | "multiple" */ type?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; marker?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object, applicable on closed shapes. See the square points between the lines. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See the square points between the lines. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: number; /** * The type of the marker object to render. square | circle | diamond | triangle | star5 | star6 | star7 | star8 | rpoly5 | gear5 | g * ear6 | gear7 | gear8 */ type?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; }; 'plot-label'?: plotLabel; plotLabel?: plotLabel; 'scale-label'?: scaleLabel; scaleLabel?: scaleLabel; }; 'crosshair-x'?: crosshairX; crosshairX?: crosshairX; 'crosshair-y'?: crosshairY; crosshairY?: crosshairY; csv?: { /** * In case of fixed width column format of the CSV data, specifies the dimensions for each column. Some csv files are formatted based * on the idea of "fixed sized columns", not by the standard comma or semicolon "separator". So, the columns array holds the number * of characters for each column so that the parser will be able to split each line in the correct way [...] */ columns?: any; /** * Sets the CSV data directly embedded in the JSON, as a string. However new-line characters are not allowed in the definition of an * attribute in json syntax, and therefore the row separator character will likely need also be overridden with the "row-separator" a * ttribute if "data-string" is used in place of "url". "Apple,25,34\r\nPear,-16,10\r\nLemon,22,-5\r\nOrange,41,21" | ... */ 'data-string'?: string; dataString?: string; /** * Specifies if the CSV data contains descriptive headers for each column as the first or second row (depending on title presence). t * rue | false | 1 | 0 */ 'horizontal-labels'?: boolean; horizontalLabels?: boolean; /** * Specifies if the CSV data should be processed in a mirrored way (per line instead of per column). Note the different format used f * or the data-string. true | false | 1 | 0 */ mirrored?: boolean; /** * Sets the separator between the data rows when using a data-string instead of an external .CSV file. The default value is "\r\n". " * _" | "&" | "\r\n" | ... */ 'row-separator'?: string; rowSeparator?: string; /** * Specifies whether or not each column in the csv data should have its own scale on the chart. true | false | 1 | 0 */ 'separate-scales'?: boolean; separateScales?: boolean; /** * Sets the separator between the data cells, default is ",". Any single character can be used as a separator. "*" | "/" | "," | ... */ separator?: string; /** * Smart-Scales will analyze the CSV data to determine if each column of data is of a different enough type of data to deserve a sepa * rate scale. If it is, smart-scales will assign the unique data columns to separate scales. true | false | 1 | 0 */ 'smart-scales'?: boolean; smartScales?: boolean; /** * Specifies if the CSV data contains a descriptive title on the first line. If this attribute it not included, then the library look * s at the data to decide if the first line is intended to be a title or not. If it thinks it is, The first line will become the tit * le of the graph. If there is a title line in the CSV and "title":"true" is set, the first line will be the graph title, but if "ti * tle":"false" is specified, that first line will become a scale-label. true | false | 1 | 0 */ title?: boolean; /** * Sets the url for the CSV data source. "http://www.domain.com/link.php" | "%FILEPATH%/fruit.csv" | "/resources/datacsv.txt" | ... */ url?: string; /** * Specifies if the CSV data contains descriptive headers for each row. true | false | 1 | 0 */ 'vertical-labels'?: boolean; verticalLabels?: boolean; }; heatmap?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * TODO: description of async attribute true | false | 1 | 0 */ async?: boolean; /** * Sets the blur radius of the heatmap regions. 10 | 20 | ... */ blur?: number; /** * Sets the type of blur shape. "circle" | "square" | ... */ 'brush-typebrushType'?: string; /** * Sets the blur shapes to composite or not. true | false | 1 | 0 */ composite?: boolean; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; /** * Sets whether or not the data is sorted. true | false | 1 | 0 */ 'sort-datasortData'?: boolean; graph?: { /** * Sets the key-scale value "scale-k" | "scale-v" | ... */ 'key-scalekeyScale'?: string; /** * Sets the value-scale value "scale-x" | "scale-y" | ... */ 'val-scalevalScale'?: string; }; tooltip?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. For graph plot tooltip. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. For graph plot tooltip. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). For graph plot to * oltip. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. For graph plot tooltip. " * none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. For graph plot tooltip. * "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". For graph plot tooltip. "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. For graph plot tooltip. "image.png" | * ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. For graph plot tooltip. "0 0" | "50 100" | "80% * 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. For graph plot tooltip. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the transparency of the border. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'border-alpha'?: number; borderAlpha?: number; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. For graph plot tooltip. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object. For graph plot tooltip. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(1 * 00, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. For graph plot tooltip. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. For grap * h plot tooltip. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. For graph plot tooltip. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. For graph plot tooltip. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object. For graph plot tooltip. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. For graph plot tooltip. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. For graph plot tooltip. 4 | "6px * " | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. For graph plot tooltip. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. For graph plot tooltip. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. For graph plot tooltip. "top" | "right" | " * bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. For graph plot tooltip. 4 | "6px" * | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Cuts off extra text. Use with width. For graph plot tooltip. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the text's color of the tooltip. Similar with font-color. For graph plot tooltip. "none" | "transparent" | "#f00" | "#f00 #00 * f" | "red yellow" | "rgb(100, 15, 15)" | ... */ color?: string; /** * Allows you to set the number of decimal places displayed for each value. 2 | 3 | 10 | ... */ decimals?: number; /** * Allows you to set the decimal mark displayed for each value. "." | "," | " " | ... */ 'decimals-separator'?: string; decimalsSeparator?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. For graph plot tooltip. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. For graph plot tooltip. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. For graph plot tooltip. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. For graph plot tooltip. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the rotation angle of the text of the tooltip. Similar with angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the text's color of the tooltip. Similar with color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, * 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family of the tooltip. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size of the tooltip. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style of the tooltip. Similar with italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight of the tooltip. Similar with bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. For graph p * lot tooltip. "#f00 #0f0 #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. For gra * ph plot tooltip. "0.1 0.5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. For graph plot tooltip. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets the item id of the map on which the object/shape is being added. "itemid" | ... */ item?: string; /** * Sets the map id of the map on which the object/shape is being added. "mapid" | ... */ map?: string; /** * Sets the object's margins. For graph plot tooltip. Works with output flash. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ margin?: any; /** * Sets the object's bottom margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-bottom'?: any; marginBottom?: any; /** * Sets the object's left margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-left'?: any; marginLeft?: any; /** * Sets the object's right margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-right'?: any; marginRight?: any; /** * Sets the object's top margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-top'?: any; marginTop?: any; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." For graph plot tooltip. Works with output canvas and svg. 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. For graph plot tooltip. Works with output canvas and svg. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. For graph plot tooltip. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets an Y offset to apply when positioning the object/shape. For graph plot tooltip. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text of the tooltip. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Specifies where tooltips are fixed relative to their node values. Refer to the applicable chart types page for more information. O * ptions by Chart Type: "node:top" | "node:center" | "node:out" | ... */ placement?: string; /** * Sets the object's position relative to it's container. Similar results can be obtained by setting marginand margin-... attributes. * For graph plot tooltip. */ position?: string; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the text of the tooltip. */ text?: string; /** * Sets the transparency of the text. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comple * tely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the character used to separate thousands. "," | "." | " " | ... */ 'thousands-separator'?: string; thousandsSeparator?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. For graph plot tooltip. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; /** * Sets the z position of the object. Objects with higher z indexes will appear "above" those with lower z index values. 5 | 10 | ... */ 'z-index'?: number; zIndex?: number; }; }; images?: [ { /** * Sets the image source. Source can be the path to a local image file or a web image's location. Acceptable file formats include PNG * , GIF, JPEG, and TIFF. */ src?: string; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's position relative to it's container. Similar results can be obtained by setting margin and margin-... attributes * . */ position?: string; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; /** * Sets the z position of the object. Objects with higher z indexes will appear "above" those with lower z index values. 5 | 10 | ... */ 'z-index'?: number; } ]; labels?: [ { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Allows you to set the label's anchor position to the center of a chart. "c" */ anchor?: string; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not. true | false | 1 | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Truncates text based on the setting of width. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the object's font color. Similar to font-color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, * 15)" | ... */ color?: string; /** * Sets the style of the cursor when hovering over the label. "hand" | "normal" */ cursor?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. Similar to angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the object's font color. Similar to color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" * | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style. Similar to italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight. Similar to bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Hooks the label to a specific node or scale index. The plot value refers to the index of a series object, and index refers to the * specific value within that series. "node:index=4" | "node:plot=0,index=1" | "scale:name=scale-y,index=3" | "scale:value=1420501300 * 000" (timestamp) |... */ hook?: string; /** * Sets whether the text is displayed with italic characters or not. true | false | 1 | 0 */ italic?: boolean; /** * Prevents hooked labels from showing outside of the plotarea none | xy */ limit?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, with the first * value affecting the top padding, the second value affecting the right padding, and so on, in a clockwise direction. 10 | "5px" | " * 10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the url's target for the link associated with the object. Use with "url". "_blank" | ... */ target?: string; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration to use underlined characters. Similar to underline. May not display properly in Mozilla Firefox when ch * arts are rendered using SVG. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text is displayed with underlined characters or not. Similar to text-decoration. May not display properly in Mozi * lla Firefox when charts are rendered using SVG. true | false | 1 | 0 */ underline?: boolean; /** * Sets the URL for the link associated with the object. "http://www.domain.com/link.php" | "link.asp" | ... */ url?: string; /** * Sets the text's vertical alignment to one of the three applicable values, relative to the object's box. "top" | "middle" | "bottom * " */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; 'callout-tip'?: calloutTip; calloutTip?: calloutTip; } ]; legend?: { /** * Forces the plotarea to consider the legend positioning and prevent overlapping with it. true | false | 1 | 0 */ 'adjust-layout'?: boolean; adjustLayout?: boolean; /** * Automatically aligns the legend and adjusts "plotarea" margins accordingly. "left" | "center" | "right" */ align?: string; /** * Sets the transparency of the object. The higher the value, the less transparent the object appears. Requires the formatting 0.x. 0 * .3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the object's bottom border style. Accepts solid, dotted, and dashed. Also accepts named colors. If color is not set properly, * will default to black. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. The higher the value, the more rounded the corners appear. 4 | "6px" | "6px * 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length for an extension line off the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets a location for the point of the tip of the callout arrow. Uses XY coordinates. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset for the origin of the callout arrow. Uses positive or negative values to move the arrow right/left/up/down. 4 | "6 * px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets which edge will be the location for the object's callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Sets legend to be collapsed by default true | false | 1 | 0 */ collapse?: boolean; /** * Sets the handler used to drag the legend: icon will create a dragging icon on the legend header, which will be the only area on wh * ich you can click and drag, header will make the whole header object active for dragging the legend. "header" | "icon" */ 'drag-handler'?: string; dragHandler?: string; /** * Sets whether the legend can be dragged or not. true | false | 1 | 0 */ draggable?: boolean; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient (more than 2 colors). To be used with gradient-stops. "#f00 #0f0 #00f" | .. * . */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the position for the introduction of each color for a complex background gradient (more than 2 colors). To be used with gradi * ent-colors. "0.1 0.5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * An alias for the "highlight" attribute in the "plot" object. Highlights the corresponding plot when the legend item is moused over * . true | false | 1 | 0 */ 'highlight-plot'?: boolean; highlightPlot?: boolean; /** * Sets the layout for the legend items. "horizontal" | "h" | "vertical" | "v" | "row x col" | "x col" | "row x" | "float" */ layout?: string; /** * Sets the object's margin/s from the top-left of the chart. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ margin?: any; /** * Sets the object's bottom margin. 4 | "6px" | ... */ 'margin-bottom'?: any; marginBottom?: any; /** * Sets the object's left margin. 4 | "6px" | ... */ 'margin-left'?: any; marginLeft?: any; /** * Sets the object's right margin. 4 | "6px" | ... */ 'margin-right'?: any; marginRight?: any; /** * Sets the object's top margin. 4 | "6px" | ... */ 'margin-top'?: any; marginTop?: any; /** * Sets the maximum number of items displayed on the legend. To be used with overflow. 5 | 10 | ... */ 'max-items'?: number; maxItems?: number; /** * Sets whether the legend can be minimized or not. */ minimize?: boolean; /** * Sets an X offset to apply when positioning the legend. A positive value moves the legend to the right. A negative value moves the * legend to the left. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the legend. A positive value moves the legend down. A negative value moves the legend up * . 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the display mode for legend items beyond max-items setting: none will display all items, hidden will display just top max-ite * ms items, page will enable the pagination module, scrollwill enable legend scrolling, with top max-items items per page. To be use * d with max-item. "none" | "hidden" | "page" | "scroll" */ overflow?: string; /** * Reverses the items in the legend */ 'reverse-series'?: boolean; reverseSeries?: boolean; /** * Sets the object's position relative to its container. Similar results can be obtained by setting [margin] and [margin-...] attribu * tes. Uses x,y coordinates originating from the top left of the chart. */ position?: string; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. The higher the value, the less transparent the shadow will be. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * For graphsets with multiple chart objects, setting this attribute to true within the legend object of each chart will allow you to * use one legend to toggle data on or off for each chart simultaneously. It should be noted that while each chart must have a legen * d object, the visible attribute can be set to false to hide a legend. true | false | 1 | 0 */ shared?: any; /** * Sets the action performed on legend item toggle: hide will simply hide the respective plot, remove will repaint the chart without * considering the respective plot, disabled will not generate any action for the legend items/markers. "hide" | "remove" | "disabled * " */ 'toggle-action'?: string; toggleAction?: string; /** * Automatically aligns the legend and adjusts "plotarea" margins accordingly. "top" | "middle" | "bottom" */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; footer?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not in the Footer of the Legend. true | false | 1 | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. Defaults to 1px if border * -width is not set. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. Defaults to dark gray if * border-color is not set. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Clips the text to a specified width. Requires width. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the text's color in the Footer of the Legend. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15 * )" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. Affects the angle of a linear fill or the position of a radial fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets a Y offset to apply to the fill. Affects position of gradient stops on a linear fill or the position of a radial fill. 4 | "6 * px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the rotation angle of the Footer of the Legend. Similar with angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the text's color of the Footer of the Legend. Similar with color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow * " | "rgb(100, 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size of the Footer of the Legend. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style of the Footer of the Legend. Similar with italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight of the Footer of the Legend. Similar with bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the text of the Footer of the Legend is displayed with italic characters or not. Similar with font-weight. true | fal * se | 1 | 0 */ italic?: boolean; /** * Sets the maximum number of characters displayed by the text label of the Footer of the Legend. If value is smaller than the length * of the text, the original text will be trimmed and '...' will be appended at the end. 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's bottom padding around the text of the Footer of the Legend. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text of the Footer of the Legend. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text of the Footer of the Legend. padding-left here may push the text out of the contain * ing legend if the number is big enough. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text of the Footer of the Legend. padding-right here will not push the text out of the * containing legend. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text of the Footer of the Legend. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the text content of the object of the Footer of the Legend. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the box of the Footer of the Legend. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency of the Footer of the Legend. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration of the Footer of the Legend. Similar with underline. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text of the Footer of the Legend is displayed with underlined characters or not. true | false | 1 | 0 */ underline?: boolean; /** * Sets the text's vertical alignment relative to the object's box of the Footer of the Legend. "top" | "middle" | "bottom" */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. Requires width. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; header?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not in the Header of the Legend. true | false | 1 | 0 */ bold?: boolean; /** * Defaults to black if border-color is not set. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Defaults to 1px if border-width is not set. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Requires border-color. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Cuts off the text at a specified width. Requires a setting for width. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the text's color in the Header of the Legend. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15 * )" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the rotation angle of the Header of the Legend. Similar with angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the text's color of the Header of the Legend. Similar with color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow * " | "rgb(100, 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family of the Footer of the Legend. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size of the Header of the Legend. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style of the Header of the Legend. Similar with italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight of the Header of the Legend. Similar with bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the text of the Header of the Legend is displayed with italic characters or not. true | false | 1 | 0 */ italic?: boolean; /** * Sets the maximum number of characters displayed by the text label of the Header of the Legend. If value is smaller than the length * of the text, the original text will be trimmed and '...' will be appended at the end. 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's bottom padding around the text of the Header of the Legend. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text of the Header of the Legend. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text of the Header of the Legend. padding-left here may push the text out of the contain * ing legend if the number is big enough. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text of the Header of the Legend. padding-right here will not push the text out of the * containing legend. 4 | "6px" | ... */ 'padding-right'?: number; paddingRight?: number; /** * Sets the object's top padding around the text of the Header of the Legend. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the text content of the object of the Header of the Legend. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the box of the Header of the Legend. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency of the Header of the Legend. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration of the Header of the Legend. Similar with underline. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text of the Header of the Legend is displayed with underlined characters or not. true | false | 1 | 0 */ underline?: boolean; /** * Sets the text's vertical alignment relative to the object's box of the Header of the Legend. "top" | "middle" | "bottom" */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. Requires a widthsetting. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; icon?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the line color of the object, applicable on non-closed shapes. See also border-colorfor closed shapes. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line width of the object, applicable on non-closed shapes. See also border-widthfor closed shapes. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; }; 'item-off'?: itemOff; itemOff?: itemOff; item?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Sets the style of the cursor when hovering over a node. "hand" | "normal" */ cursor?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. Similar to angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the object's font color. Similar to color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" * | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style. Similar to italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight. Similar to bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets if the legend marker has a small horizontal line through its middle. true | false | 1 | 0 */ 'show-line'?: boolean; showLine?: boolean; /** * Sets the visibility of the legend item's marker. true | false | 1 | 0 */ 'show-marker'?: boolean; showMarker?: boolean; /** * Sets the action performed on legend item toggle: hide will simply hide the respective plot, remove will repaint the chart without * considering the respective plot, disabled will not generate any action for the legend items/markers. Equivalent of legend's toggle * -action. "hide" | "remove" | "disabled" */ 'toggle-action'?: string; toggleAction?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; }; marker?: { /** * Sets if the legend marker has a small horizontal line through its middle. true | false | 1 | 0 */ 'show-line'?: boolean; showLine?: boolean; /** * Sets the action performed on legend item toggle: hide will simply hide the respective plot, remove will repaint the chart without * considering the respective plot, disabled will not generate any action for the legend items/markers. Equivalent of legend's toggle * -action. "hide" | "remove" | "disabled" */ 'toggle-action'?: string; toggleAction?: string; /** * The type of the marker object to render. square | circle | diamond | triangle | star5 | star6 | star7 | star8 | rpoly5 | gear5 | g * ear6 | gear7 | gear8 */ type?: string; /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object, for rounded corners. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the style of the cursor when hovering over a node. "hand" | "normal" */ cursor?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the line color of the object, applicable on non-closed shapes. See also border-colorfor closed shapes. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. See also border-widthfor closed shapes. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; 'highlight-state'?: highlightState; highlightState?: highlightState; }; 'page-off'?: pageOff; pageOff?: pageOff; 'page-on'?: pageOn; pageOn?: pageOn; 'page-status'?: pageStatus; pageStatus?: pageStatus; scroll?: { bar?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the styling for the bottom border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a s * tring. "1px solid green" | "3px dotted purple" | ... */ 'border-bottom'?: any; borderBottom?: any; /** * Sets the styling for the left border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a str * ing. "1px solid green" | "3px dotted purple" | ... */ 'border-left'?: any; borderLeft?: any; /** * Sets the border radius (rounded corners) of the object. The higher the value, the more rounded the corners appear. 4 | "6px" | "6p * x 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the styling for the right border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a st * ring. "1px solid green" | "3px dotted purple" | ... */ 'border-right'?: any; borderRight?: any; /** * Sets the styling for the top border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a stri * ng. "1px solid green" | "3px dotted purple" | ... */ 'border-top'?: any; borderTop?: any; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; }; handle?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the styling for the bottom border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a s * tring. "1px solid green" | "3px dotted purple" | ... */ 'border-bottom'?: any; borderBottom?: any; /** * Sets the styling for the left border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a str * ing. "1px solid green" | "3px dotted purple" | ... */ 'border-left'?: any; borderLeft?: any; /** * Sets the border radius (rounded corners) of the object. The higher the value, the more rounded the corners appear. 4 | "6px" | "6p * x 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the styling for the right border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a st * ring. "1px solid green" | "3px dotted purple" | ... */ 'border-right'?: any; borderRight?: any; /** * Sets the styling for the top border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a stri * ng. "1px solid green" | "3px dotted purple" | ... */ 'border-top'?: any; borderTop?: any; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; }; }; tooltip?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the transparency of the border. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'border-alpha'?: number; borderAlpha?: number; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius (rounded corners) of the object. "3px" | "10px" */ 'border-radius'?: any; borderRadius?: any; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the font color of the object text. "none" | "transparent" | "purple" | "#33ccff" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object text. "Courier" | "Georgia" | "Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object text. 12 | "20px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the font style of the object text. "normal" | "italic" */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object text. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets the height of the object. 10 | "20px" | 0.3 | "30%" | ... */ height?: number; /** * Sets the padding around the object text. "10%" | "25px" ... */ padding?: number; /** * To create sticky tooltips. Use this with the "timeout" attribute, which allows you to specify how long you want the tooltips to "s * tick" to the chart. true | false | 1 |0 */ sticky?: boolean; /** * Specifies what text to display in the tooltips. "Legend Tooltips" | "%t %plot-description" | "..." */ text?: string; /** * Sets the transparency of the text. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comple * tely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * To create sticky tooltips. Provide a value in milliseconds. Use this with the "sticky" attribute, which specifies whether or not t * ooltips will "stick" to the chart. "30000 | 10000 | ... */ timeout?: number; /** * Sets the width of the object. 10 | "20px" | 0.3 | "30%" | ... */ width?: number; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; }; /** * Sets the maximum numbers of nodes for which a tracking area will be created. This is best used to optimize charts with large sets * of data. 5 | 10 | ... */ 'max-trackers'?: number; maxTrackers?: number; 'media-rules'?: [ { /** * Sets the maximum chart height in pixels. 600 | 400 | 300 */ 'max-height'?: number; maxHeight?: number; /** * Sets the maximum chart width in pixels. 1000 | 800 | 600 */ 'max-width'?: number; maxWidth?: number; /** * Sets the minimum chart height in pixels. 600 | 400 | 300 */ 'min-height'?: number; minHeight?: number; /** * Sets the minimum chart width in pixels. 1000 | 800 | 600 */ 'min-width'?: number; minWidth?: number; /** * Removes the object (legend, title) from the chart at that specified breakpoint. Use the attribute to save screen space at smaller * breakpoints. true | false */ visible?: boolean; } ]; 'no-data'?: noData; noData?: noData; options?: { /** * To set the layout of the word cloud. "spiral" | "flow-center" | "flow-top" */ aspect?: string; /** * To define words to be excluded from the word cloud, e.g., "and" or "the". [...] */ ignore?: any; /** * When the "color-type" attribute is set to "color", use this attribute to set the color of the text in the word cloud. "red" | "#3F * 51B5" | ... */ color?: string; /** * To set the type of color arrangement applied to the word cloud. Use the "color" value with the "color" attribute. Use the "palette * " value with the "palette" array. "random" (default) | "color" | "palette" */ 'color-type'?: string; colorType?: string; /** * To set the maximum font size. 20 | "30px" | ... */ 'max-font-size'?: any; maxFontSize?: any; /** * To set the maximum number of items displayed in the word cloud. 100 | 30 | ... */ 'max-items'?: any; maxItems?: any; /** * To set the minimum font size. 10 | "12px" | ... */ 'min-font-size'?: any; minFontSize?: any; /** * To set the minimum length of the words displayed in the word cloud. 3 | 5 | ... */ 'min-length'?: any; minLength?: any; /** * When the "color-type" attribute is set to "palette", use this attribute to set the color palette of the word cloud. [...] */ palette?: any; /** * To set whether every one or two words rotates 90 degrees. true | false (default) */ rotate?: boolean; /** * To control the step metering. Use this with the "step-radius" attribute. 45 | 90 | ... */ 'step-angle'?: any; stepAngle?: any; /** * To control the step metering. Use this with the "step-angle" attribute. 30 | 50 | ... */ 'step-radius'?: any; stepRadius?: any; /** * To provide the data for the word cloud. (Alternatively, data can be provided through a "words" array.) "text data..." | ... */ text?: string; /** * To set the type of item to be analyzed: words or characters. "word" (default) | "character" */ token?: string; button?: { /** * To set the text of the button 3m | 2015 | all */ text?: string; /** * To set multiplier for count ytd | all | year | month | week | day | hour | minute */ type?: string; /** * Offset from start to zoom. This attribute is coupled with the type attribute to determine where to set the zoom level. 1 | 2 | 3 */ count?: any; }; 'context-menu'?: contextMenu; contextMenu?: contextMenu; indicator?: { /** * To set the visibility of the object. true | false */ visible?: boolean; npv?: { /** * To set the number of decimals that will be displayed. 0 | 1 |2 | ... */ decimals?: number; /** * To set the font color. 'gray' | '#666699' | ... */ 'font-color'?: any; fontColor?: any; /** * To set the font family. 'Arial' | 'Georgia' | ... */ 'font-family'?: string; fontFamily?: string; /** * To set the font size. 30 | 24 | 16 | ... */ 'font-size'?: number; fontSize?: number; /** * To set the font style. 'normal' | 'italic' */ 'font-style'?: string; fontStyle?: string; /** * To set the font weight. 'normal' | 'bold' */ 'font-weight'?: string; fontWeight?: string; /** * To set the visibility of the object. true | false */ visible?: boolean; }; title?: { /** * To set the font color. 'gray' | '#666699' | ... */ 'font-color'?: any; fontColor?: any; /** * To set the font family. 'Arial' | 'Georgia' | ... */ 'font-family'?: string; fontFamily?: string; /** * To set the font size. 30 | 24 | 16 | ... */ 'font-size'?: number; fontSize?: number; /** * To set the font style. 'normal' | 'italic' */ 'font-style'?: string; fontStyle?: string; /** * To set the font weight. 'normal' | 'bold' */ 'font-weight'?: string; fontWeight?: string; /** * To set the visibility of the object. true | false */ visible?: boolean; }; value?: { /** * To set the font color. 'gray' | '#666699' | ... */ 'font-color'?: any; fontColor?: any; /** * To set the font family. 'Arial' | 'Georgia' | ... */ 'font-family'?: string; fontFamily?: string; /** * To set the font size. 30 | 24 | 16 | ... */ 'font-size'?: number; fontSize?: number; /** * To set the font style. 'normal' | 'italic' */ 'font-style'?: string; fontStyle?: string; /** * To set the font weight. 'normal' | 'bold' */ 'font-weight'?: string; fontWeight?: string; /** * To set the visibility of the object. true | false */ visible?: boolean; }; }; style?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699' * , '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15 * , 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object. 2 | 3 | '5px' | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the font family of the object. 'Arial' | 'Tahoma,Verdana' | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the padding of the object. 3 | '5px' | '10px' | ... */ padding?: number; /** * Sets the text transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 bei * ng completely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; 'hover-state'?: hoverState; hoverState?: hoverState; tooltip?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 being co * mpletely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666 * 699', '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100 * , 15, 15)' | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the transparency of the border. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'border-alpha'?: number; borderAlpha?: number; /** * Sets the border color of the object. Colors can be entered by name (e.g., 'purple', 'blue'), hexadecimal notation (e.g., '#666699' * , '#33ccff'), or RGB notation (e.g., 'rgb(255,0,0)', 'rgb(0,0,255)'). 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15 * , 15)' | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border radius of the object. 2 | 3 | '5px' | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 1 | 3 | '6px' | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the font angle of the object. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the font color of the object. 'none' | 'transparent' | 'purple' | '#33ccff' | 'rgb(100, 15, 15)' | ... */ 'font-color'?: any; fontColor?: any; /** * Sets the font family of the object. 'Arial' | 'Tahoma,Verdana' | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object. 12 | "20px" | ... */ 'font-size'?: number; fontSize?: number; /** * Sets the font style of the object. "normal" | "italic" */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets the line style of the object. 'solid' | 'dotted' | 'dashed' | 'dashdot' */ 'line-style'?: string; lineStyle?: string; /** * Sets the padding of the object. 3 | '5px' | '10px' | ... */ padding?: number; /** * Sets the text to be displayed in the tooltips. "%text: %hits" | ... */ text?: any; /** * Sets the text transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 bei * ng completely opaque. Note that the leading zero is required before the decimal. 0.3 | 0.4 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the visibility of the object. true | false (default) */ visible?: boolean; }; }; violin?: { /** * To set the trim. true | false | 0 | 1 */ trim?: boolean; /** * To set the jitter width. 0 | .5 | 1 | 2 | ... */ jitter?: any; /** * To set the `rounding-factor` on median edges. 0 | .5 | 1 | 2 | ... */ roundingFactor?: any; /** * To set the `mean-factor` width. 0 | .5 | 1 | 2 | ... */ meanFactor?: any; /** * To set the styling of the violin object. {} */ style?: any; }; words?: [ { /** * To set the word count. 5 | 20 | 100 | ... */ count?: any; /** * To set the word. "Flowers" | "Freesia" | "Peony" | ... */ text?: string; } ]; }; plot?: { /** * Sets the transparency level of backgrounds, borders, and lines. Values must range between 0.0 and 1.0, with 0.0 being completely t * ransparent and 1.0 being completely opaque. Note that values require the leading zero before the decimal point. 0.3 | 0.9 | ... */ alpha?: number; /** * Modifies how data points appear on a chart. Refer to the applicable chart types page for more information. Options by Chart Type: * "segmented" | "spline" | "stepped" | "jumped" | "cone" | "histogram" | ... */ aspect?: string; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use "gradient-c * olors" and "gradient-stops". "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with "background-color-2". "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with "background-color-1". "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the "background-repeat" value is "no-repeat". "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Nested Pie Charts Only: This attribute is used to set the space between band in nested pie charts ("type":"nestedpie"). 5 | 10 | . * .. */ 'band-space'?: number; bandSpace?: number; /** * Bar Charts and Bullet Charts Only: Sets the max width of bars. "10" | "10%" | "10px" */ 'bar-max-width'?: number; barMaxWidth?: number; /** * Bar Charts and Bullet Charts Only: Sets the amount of space between each bar in a single plot index. "10" | "10%" | "10px" */ 'bar-space'?: number; barSpace?: number; /** * Bar Charts and Bullet Charts Only: Sets the width of each bar. "10" | "10%" | "10px" */ 'bar-width'?: number; barWidth?: number; /** * Bar Charts and Bullet Charts Only: Defines how much the bars in each plot index should overlap. "10" | "10%" | "10px" */ 'bars-overlap'?: number; barsOverlap?: number; /** * Bar Charts and Bullet Charts Only: Defines the spacing to the left of the bars at each index position. "10" | "10%" | "10px" */ 'bars-space-left'?: number; barsSpaceLeft?: number; /** * Bar Charts and Bullet Charts Only: Defines the spacing to the right of the bars at each index position. "10" | "10%" | "10px" */ 'bars-space-right'?: number; barsSpaceRight?: number; /** * Sets the border color of the object, applicable on closed shapes. See also "line-color" for closed shapes. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the border width of the object, applicable on closed shapes. See also "line-width" for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the "callout-position". 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * By defalut null values within series arrays will create a blank space within a plot. Setting connected-nulls to true will connect * values through a null data point. true | false | 1 | 0 */ 'connect-nulls'?: boolean; connectNulls?: boolean; /** * Area Charts Only: Sets whether the contour lines on area plots will be on top of all areas or will be hidden by the next area plot * on top of it. You will notice when the attribute is set to true the lines are all set above the shaded regions. true | false | 1 * | 0 */ 'contour-on-top'?: boolean; contourOnTop?: boolean; /** * Sets the style of the cursor when hovering over a node. "hand" | "normal" */ cursor?: string; /** * This attribute allows you to create custom tokens and associate static or dynamic data to them. This attribute can be used almost * anywhere in a chart. "Some Text" | ... */ 'data-...'?: string; /** * Certain plot to add in selection tool. */ 'data-append-selection'?: boolean; dataAppendSelection?: boolean; /** * Certain plot to ignore in selection tool. */ 'data-ignore-selection'?: boolean; dataIgnoreSelection?: boolean; /** * Using the decimals attribute will allow you to set the number of decimal places associated to each value. 5 | 10 | ... */ decimals?: number; /** * The "decimals-separator": attribute allows you to set what type of punctuation the will be used in the decimal place. "." | "," | * ... */ 'decimals-separator'?: string; decimalsSeparator?: string; /** * This attribute sets description text for the plot which can be addressed in various areas with the %plot-description token. "Some * Text" | ... */ description?: string; /** * Turns off click on slices */ detached?: boolean; /** * By default ZingChart uses sampling when rendering charts. This helps improve rendering speeds and typically does not effect the ap * pearance of the chart. However, using the attribute "exact": true within the "plot": { } object forces ZingChart to render all nod * es. true | false | 1 | 0 */ exact?: boolean; /** * This attribute sets the values to scientific notation true | false | 1 | 0 */ exponent?: boolean; /** * This attribute set the number of decimals to be used when using exponents for scientific notation 5 | 10 | ... */ exponentDecimals?: number; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Bullet Charts Only: Accepts numerical values. Determines where goals are set for all plots. The "goals": [ ] values can also be se * t individually within each value set. [45, 70, 60] */ goals?: any; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with "gradient-stops". "#f00 #0f * 0 #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with "gradient-colors". "0.1 * 0.5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * When true, automatically selects all nodes with the same scale index as the selected node. The selection-mode attribute must also * be set. true | false | 1 | 0 */ 'group-selections'?: boolean; groupSelections?: boolean; /** * When set to true, it highlights the corresponding series when the user hovers over it in the legend. Note: This attribute may be used in conjunction with the "highlight-state" and/or * "highlight-marker" object(s), which allow for custom styling. * Default Value: false */ hightlight?: boolean; /** * Venn Diagrams Only: This attribute allow you to set the values for the area to be shared between each node. [30] */ join?: any; /** * The "legend-text": attribute is typically used within "series": [ ] value sets. Using this attribute allows you to associate both * a "text":" " and "legend-text":" " to each value set "Some Text" | ... */ 'legend-text'?: string; legendText?: string; /** * Sets the line color of the object, applicable on non-closed shapes. See also "border-color"for closed shapes. "none" | "transparen * t" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with "line-segment-size". This will control the size of the gaps bet * ween each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with "line-gap-size". This will control the size of the visible segm * ent of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. See also "border-width" for closed shapes. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Applies to charts such as line and area which have markers. When there are too many markers for the chart ZingChart does not displ * ay all markers. Example 1000 nodes on a 300px wide chart. Setting max-nodes will override the default setting and force nodes to b * e displayed. 5 | 10 | ... */ 'max-nodes'?: number; maxNodes?: number; /** * Heat Maps Only: Sets a maximum ratio applied to the value of the node when calculating its aspect. 0 | 0.4 | ... */ 'max-ratio'?: number; maxRatio?: number; /** * Bubble Charts and Bubble Pie Charts Only: Defines the maximum size of the bubble if the value representing size is not sharing the * same ratio with the value scale. 5 | 10 | ... */ 'max-size'?: number; maxSize?: number; /** * Sets the maximum numbers of nodes for which a tracking area will be created. This is best used to optimize charts with large sets * of data. 5 | 10 | ... */ 'max-trackers'?: number; maxTrackers?: number; /** * Sets whether or not a node is wrapped equally before and after its position. true | false | 1 | 0 */ 'mid-point'?: boolean; midPoint?: boolean; /** * Heat Maps Only: Sets a minimum ratio applied to the value of the node when calculating its aspect. 0 | 0.4 | ... */ 'min-ratio'?: number; minRatio?: number; /** * Bubble Charts and Bubble Pie Charts Only: Defines the minimum size of the bubble if the value representing size is not sharing the * same ratio with the value scale. 5 | 10 | ... */ 'min-size'?: number; minSize?: number; /** * Sets whether monotone interpolation is used for charts using the "spline" aspect. true | false | 1 | 0 */ monotone?: boolean; /** * Setting "multiplier": true will take large numbers such as thousands, millions, etc and replace the full number with an abbreviate * d notation with a short unit such as K, M, B, etc true | false | 1 | 0 */ multiplier?: boolean; /** * This attribute will determine how negative values are handled. When using "format":"$%v" setting "negation":"currency" will move t * he - symbol to the outside of the $ sign. When using "negation" within the "plot": { } object you will see changes in things such * as tooltips or anywhere else series data is used to populate values. You need to set "negation" in things such as "scale-y": { } s * eparately. "standard" | "currency" */ negation?: string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Pie Charts Only: Use this to transform the shape of the pie slices. */ 'pie-transformpieTransform'?: string; /** * Pie Charts Only: Provides the ability to rotate the chart. 5 | 10 | ... */ 'ref-angle'?: number; refAngle?: number; /** * Heat Maps Only: Sets the value (default 'plot-max') which is used as a reference for calculating node aspect. "plot-max" | "plot-t * otal" | "chart-max" | "chart-total" */ reference?: string; /** * By default ZingChart uses sampling when rendering large datasets. If you are trying to render 10000 data points on a chart which i * s only 500px wide there is not enough space for each data point. ZingChart will automatically determine which data points to show. * The "sampling-step": attribute allows you to set the step for sampling. For example if you have 10000 data points and set "sampli * ng-step":10 it will show point 1,10,20,... Also note the "exact": true attribute if you want to force all data points. 5 | 10 | .. * . */ 'sampling-step'?: number; samplingStep?: number; /** * Specifies the scales used by the series item. scale-x,scale-y | scale-x,scale-y-2 | ... */ scales?: string; /** * Bubble Charts and Bubble Pie Charts Only: Sets the method used to relate the bubble numerical value to it's aspect. "radius" | "sq * rt" | "area" */ scaling?: string; /** * When scrolling is enabled for a chart, ZingChart automatically samples the data in order to maintain performance during the re-ren * dering of the chart that occurs during scrolling. By default, ZingChart will automatically sample every other item (scroll-step-mu * ltiplier:2). Setting scroll-step-multiplier to 1 will force the library to sample every data point, essentially disabling sampling * . 5 | 10 | ... */ 'scroll-step-multiplier'?: number; scrollStepMultiplier?: number; /** * Line Charts and Area Charts Only: Allows you to specify whether tooltips are activated by the markers and lines (default) or the m * arkers only. true (default) | false */ 'segment-trackers'?: boolean; segmentTrackers?: boolean; /** * To set how data points are selected on a chart. 'none' (default) prevents any selection. 'plot' allows you to select one node (or data point) per series (or dataset). 'graph' allows * you to select one node per chart. 'multiple' allows you to select as many nodes as you want. Note: Use this attribute with the selected-state and/or selected-marker object(s), which * allow you specify the styling attributes you want applied. * Accepted Values: ['none', 'plot', 'graph', 'multiple'] */ 'selection-mode'?: string; selectionMode?: string; /** * A boolean to smart sample and render data at a sampled size. Used in conjuction with exact:false true | false */ 'smart-sampling'?: boolean; smartSampling?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Setting "short": true will abbreviate long numbers such as 100000 to 1K or 1000000 to 1M. When set within the "plot": {} object th * is change will be noticed anywhere values are pulled from series data. This can also be used in places such as "scale-y, scale-x, * etc" true | false | 1 | 0 */ short?: boolean; /** * By default when setting "short": true ZingChart will round to the nearest short unit (ie 100000 to 100K and 1000000 to 1M). You ca * n set the short-unit and ZingChart will round all numbers to that unit. Note when setting this within the "plot": { } object the c * hanges will only effect values which are pulled from the series values. Things such as scale are set separately. "k" | "K" | "m" | * "M" | "b" | "B" */ 'short-unit'?: string; shortUnit?: string; /** * On bar charts, when the value of a bar is 0, setting `show-zero`: true will add 1 pixel to the height of the bar so that it is onl * y just visible. true | false | 1 | 0 */ 'show-zero'?: boolean; showZero?: boolean; /** * Bubble Charts and Bubble Pie Charts Only: Sets a multiplier (default 1) used to increase/decrease the bubble size 5 | 10 | ... */ 'size-factor'?: number; sizeFactor?: number; /** * Hole size in middle of chart */ slice?: number; /** * Nested Pie Charts Only: Sets the initial offset of the pie layers when making a nestedpie 5 | 10 | ... */ 'slice-start'?: number; sliceStart?: number; /** * Using the "stack": attribute allows you to assign which plot index you want to each value set associated with when using a stacked * chart. 5 | 10 | ... */ stack?: number; /** * Setting "stacked": true will take each of the "series": [ ] value sets and stack them on top of one another true | false | 1 | 0 */ stacked?: boolean; /** * Applicable on aspect=stepped, sets the location of the stepping relative to two consecutive nodes. "before" | "middle" | "after" */ 'step-start'?: string; stepStart?: string; /** * Sets the url's target for the link associated with the object. Use with "url". "_blank" | ... */ target?: string; /** * Sets the thickness of pie3d charts. 5 | 10 | ... */ thickness?: number; /** * When you set the "thousands-separator": attribute the punctuation which is used will be placed to separate digits which go into 1, * 000's 10,000's etc. When placed in the "plot": { } object this will only effect values which are pulled directly from the series d * ata. Objects such as "scale-y": { }, "scale-x": { }, etc..., will need to be set separately. "." | "," | ... */ 'thousands-separator'?: string; thousandsSeparator?: string; /** * Using the "tooltip-text":" " attribute allows you to set text for tooltips. This can also be done using a variety of other tokens * "Some Text" | ... */ 'tooltip-text'?: string; tooltipText?: string; /** * Sets the URL for the link associated with the object. "http://www.domain.com/link.php" | "link.asp" | ... */ url?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the z-axis end point on 3d charts. 10 | "10px" | ... */ 'z-end'?: number; zEnd?: number; /** * Sets the z-axis start point on 3d charts. 10 | "10px" | ... */ 'z-start'?: number; animation?: { '1'?: any; '2'?: any; '3'?: any; '4'?: any; '5'?: any; '6'?: any; '7'?: any; '8'?: any; '9'?: any; '10'?: any; '11'?: any; '12'?: any; '13'?: any; /** * Sets the delay in milliseconds between each step of the animation. 5 | 10 | ... */ delay?: number; /** * Determines whether or not animation occurs when a change is made to the chart via an API event (e.g., adding node, adding plot, re * moving node). true (default) | false | 1 | 0 */ 'on-change'?: boolean; 'on-legend-toggle'?: any; onLegendToggle?: any; /** * Sets the animation effect. Numeric Code String Name 1 `ANIMGATION_FADE_IN` 2 `ANIMATION_EXPAND_VERTICAL` 3 `ANIMATION_EXPAND_TOP` * 4 `ANIMATION_EXPAND_BOTTOM` 5 `ANIMGATION_FADE_IN` 6 `ANIMATION_EXPAND_RIGHT` 7 `ANIMATION_EXPAND_HORIZONTAL` 8 `ANIMATION_SLIDE_L * EFT` 9 `ANIMATION_SLIDE_RIGHT` 10 `ANIMATION_SLIDE_TOP` 11 `ANIMATION_SLIDE_BOTTOM` 12 `ANIMATION_UNFOLD_HORIZONTAL` 13 `ANIMATION * _UNFOLD_VERTICAL` */ effect?: number; method?: number; sequence?: number; speed?: number; }; 'background-marker'?: backgroundMarker; backgroundMarker?: backgroundMarker; 'background-state'?: backgroundState; backgroundState?: backgroundState; error?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the line color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. See also border-width for closed shapes. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; }; errors?: [{}]; goal?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Note that values require the leading zero before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: any; backgroundColor?: any; /** * Sets the border color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: any; borderColor?: any; /** * Sets the border radius of the object, for rounded corners. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the height of the object. 10 | "20px" */ height?: number; /** * Sets the line style of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * Only applies to Horizontal Bar Charts: Sets the width of the object. 10 | "20px" */ width?: number; }; 'guide-label'?: guideLabel; guideLabel?: guideLabel; highlight?: boolean; 'highlight-marker'?: highlightMarker; highlightMarker?: highlightMarker; 'highlight-state'?: highlightState; highlightState?: highlightState; 'hover-marker'?: hoverMarker; hoverMarker?: hoverMarker; 'hover-state'?: hoverState; hoverState?: hoverState; 'legend-item'?: legendItem; legendItem?: legendItem; 'legend-marker'?: legendMarker; legendMarker?: legendMarker; marker?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. See the square points between the lines. 0.3 * | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. See the square points between the lines. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. See the square points between the lines. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | " * rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. See the square points bet * ween the lines. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. See the square points be * tween the lines. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". Used with background-image. See the square points between * the lines. "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. See the square points between the lin * es. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. See the square points between the lines. "0 0" * | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. See the square points between the lines. "no-repeat" | "repeat" | "repeat-x" | " * repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See the square points between the lines. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See the square points between the lines. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the angle of the axis along which the linear gradient is drawn. See the square points between the lines. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. See the square points between the lines. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. See the square points between the lines. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. See the square points between the lines. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the map id of the map on which the object/shape is being added. "mapid" | ... */ map?: string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; /** * The type of the marker object to render. square | circle | diamond | triangle | star5 | star6 | star7 | star8 | rpoly5 | gear5 | g * ear6 | gear7 | gear8 */ type?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; /** * Sets the z position of the object. Objects with higher z indexes will appear "above" those with lower z index values. 5 | 10 | ... */ 'z-index'?: number; zIndex?: number; }; preview?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Area Chart only: Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely trans * parent and 1.0 being completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ 'alpha-area'?: number; alphaArea?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the line color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line style of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 2 | 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * To set the stock preview chart type: area chart or line chart. "area" (default) | "line" */ type?: string; }; rules?: [ { /** * A rule allows you to include logic in order to apply a set of attributes only to certain aspects of your chart that meet the crite * ria specified within each "rule": group. You can include any number of "rule": groups nested within a "rules": set. Place the desi * red attribute or attributes within each "rule": group to apply those attributes to the areas that fulfill the requirement. The eff * ect of rules depends largely on the placement of the "rules": set within your JSON code. In the above example, the styling attribu * tes within each rule will be applied to the scale-y guide. "%c == 2" | "%v <= 0" | "%v > 0" | ... */ rule?: string; } ]; 'selected-marker'?: selectedMarker; selectedMarker?: selectedMarker; 'selected-state'?: selectedState; selectedState?: selectedState; tooltip?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. For graph plot tooltip. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. For graph plot tooltip. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). For graph plot to * oltip. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. For graph plot tooltip. " * none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. For graph plot tooltip. * "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". For graph plot tooltip. "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. For graph plot tooltip. "image.png" | * ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. For graph plot tooltip. "0 0" | "50 100" | "80% * 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. For graph plot tooltip. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the transparency of the border. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'border-alpha'?: number; borderAlpha?: number; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. For graph plot tooltip. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object. For graph plot tooltip. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(1 * 00, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. For graph plot tooltip. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. For grap * h plot tooltip. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. For graph plot tooltip. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. For graph plot tooltip. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object. For graph plot tooltip. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. For graph plot tooltip. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. For graph plot tooltip. 4 | "6px * " | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. For graph plot tooltip. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. For graph plot tooltip. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. For graph plot tooltip. "top" | "right" | " * bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. For graph plot tooltip. 4 | "6px" * | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Cuts off extra text. Use with width. For graph plot tooltip. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the text's color of the tooltip. Similar with font-color. For graph plot tooltip. "none" | "transparent" | "#f00" | "#f00 #00 * f" | "red yellow" | "rgb(100, 15, 15)" | ... */ color?: string; /** * Allows you to set the number of decimal places displayed for each value. 2 | 3 | 10 | ... */ decimals?: number; /** * Allows you to set the decimal mark displayed for each value. "." | "," | " " | ... */ 'decimals-separator'?: string; decimalsSeparator?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. For graph plot tooltip. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. For graph plot tooltip. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. For graph plot tooltip. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. For graph plot tooltip. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the rotation angle of the text of the tooltip. Similar with angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the text's color of the tooltip. Similar with color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, * 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family of the tooltip. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size of the tooltip. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style of the tooltip. Similar with italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight of the tooltip. Similar with bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. For graph p * lot tooltip. "#f00 #0f0 #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. For gra * ph plot tooltip. "0.1 0.5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. For graph plot tooltip. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets the item id of the map on which the object/shape is being added. "itemid" | ... */ item?: string; /** * Sets the map id of the map on which the object/shape is being added. "mapid" | ... */ map?: string; /** * Sets the object's margins. For graph plot tooltip. Works with output flash. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ margin?: any; /** * Sets the object's bottom margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-bottom'?: any; marginBottom?: any; /** * Sets the object's left margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-left'?: any; marginLeft?: any; /** * Sets the object's right margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-right'?: any; marginRight?: any; /** * Sets the object's top margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-top'?: any; marginTop?: any; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." For graph plot tooltip. Works with output canvas and svg. 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. For graph plot tooltip. Works with output canvas and svg. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. For graph plot tooltip. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets an Y offset to apply when positioning the object/shape. For graph plot tooltip. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text of the tooltip. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Specifies where tooltips are fixed relative to their node values. Refer to the applicable chart types page for more information. O * ptions by Chart Type: "node:top" | "node:center" | "node:out" | ... */ placement?: string; /** * Sets the object's position relative to it's container. Similar results can be obtained by setting marginand margin-... attributes. * For graph plot tooltip. */ position?: string; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the transparency of the text. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comple * tely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the character used to separate thousands. "," | "." | " " | ... */ 'thousands-separator'?: string; thousandsSeparator?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. For graph plot tooltip. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; /** * Sets the z position of the object. Objects with higher z indexes will appear "above" those with lower z index values. 5 | 10 | ... */ 'z-index'?: number; zIndex?: number; }; trend?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the line color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line width of the object. 1 | 3 | | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; }; 'value-box'?: valueBox; valueBox?: valueBox; }; plotarea?: { /** * If true, it is similar with setting margin:"dynamic", added with adjust-layout attributes on title and legend. true | false | 1 | * 0 */ 'adjust-layout'?: boolean; adjustLayout?: boolean; /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets the item id of the map on which the object/shape is being added. "itemid" | ... */ item?: string; /** * Sets the map id of the map on which the object/shape is being added. "mapid" | ... */ map?: string; /** * Sets the object's margin/s. The plotarea object also accepts "dynamic" as value for the margin attribute, in which case it analyze * s the scale labels and change the plotarea size accordingly in order to fit all scale labels. "dynamic" | 10 | "5px" | "10 20" | " * 5px 10px 15px 20px" | ... */ margin?: any; /** * Sets the object's top margin. The plotarea object also accepts "dynamic" as value for the margin attribute, in which case it analy * zes the scale labels and change the plotarea size accordingly in order to fit all scale labels. "dynamic" | 10 | "5px" | "10 20" | * "5px 10px 15px 20px" | ... */ 'margin-bottom'?: any; marginBottom?: any; /** * Sets the object's top margin. The plotarea object also accepts "dynamic" as value for the margin attribute, in which case it analy * zes the scale labels and change the plotarea size accordingly in order to fit all scale labels. "dynamic" | 10 | "5px" | "10 20" | * "5px 10px 15px 20px" | ... */ 'margin-left'?: any; marginLeft?: any; /** * Sets the object's top margin. The plotarea object also accepts "dynamic" as value for the margin attribute, in which case it analy * zes the scale labels and change the plotarea size accordingly in order to fit all scale labels. "dynamic" | 10 | "5px" | "10 20" | * "5px 10px 15px 20px" | ... */ 'margin-right'?: any; marginRight?: any; /** * Sets the object's top margin. The plotarea object also accepts "dynamic" as value for the margin attribute, in which case it analy * zes the scale labels and change the plotarea size accordingly in order to fit all scale labels. "dynamic" | 10 | "5px" | "10 20" | * "5px 10px 15px 20px" | ... */ 'margin-top'?: any; marginTop?: any; /** * Sets an additional margin specifically to the bottom of the plotarea when using dynamic margins. Offset will only be set if there * is a scale object on the bottom of the chart. "dynamic" | 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ 'margin-bottom-offset'?: any; marginBottomOffset?: any; /** * Sets an additional margin specifically to the left of the plotarea when using dynamic margins. Offset will only be set if there is * a scale object on the left of the chart. "dynamic" | 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ 'margin-left-offset'?: any; marginLeftOffset?: any; /** * Sets an additional margin specifically to the left of the plotarea when using dynamic margins. Offset will only be set if there is * a scale object on the right of the chart. "dynamic" | 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ 'margin-right-offset'?: any; marginRightOffset?: any; /** * Sets an additional margin specifically to the top of the plotarea when using dynamic margins. Offset will only be set if there is * a scale object on the top of the chart. "dynamic" | 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ 'margin-top-offset'?: any; marginTopOffset?: any; /** * Sets the tolerance of the mask (in number of pixels) that covers the plotarea to allow objects to overflow outside of the plotarea * . 4 | "6px" | ... */ 'mask-tolerance'?: number; maskTolerance?: number; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's position relative to it's container. Similar results can be obtained by setting marginand margin-... attributes. */ position?: string; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; /** * Sets the z position of the object. Objects with higher z indexes will appear "above" those with lower z index values. 5 | 10 | ... */ 'z-index'?: number; zIndex?: number; }; preview?: { /** * Forces the plotarea to consider the preview object positioning and prevent overlapping with it. true | false | 1 | 0 */ 'adjust-layout'?: boolean; adjustLayout?: boolean; /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the chart is updated when the preview active area is being moved. Default is false for classic theme and true for lig * ht/dark themes. The graph will update only when a the mouse is released. true | false | 1 | 0 */ live?: boolean; /** * Sets the object's margins. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ margin?: any; /** * Sets the minimum width of preview's active area. 5 | 10 | ... */ 'min-distance'?: number; minDistance?: number; /** * Sets the object's position relative to its container. Similar results can be obtained by setting marginand margin-... attributes. */ position?: string; /** * Sets whether the zoom level is preserved when a chart is altered or reloaded. true | false | 1 | 0 */ 'preserve-zoom'?: boolean; preserveZoom?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets the "x" position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the "y" position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; active?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; }; handle?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the styling for the bottom border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a s * tring. "1px solid green" | "3px dotted purple" | ... */ 'border-bottom'?: any; borderBottom?: any; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the styling for the left border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a str * ing. "1px solid green" | "3px dotted purple" | ... */ 'border-left'?: any; borderLeft?: any; /** * Sets the border radius (rounded corners) of the object. The higher the value, the more rounded the corners appear. 4 | "6px" | "6p * x 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the styling for the right border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a st * ring. "1px solid green" | "3px dotted purple" | ... */ 'border-right'?: any; borderRight?: any; /** * Sets the styling for the top border. Provide border width, line style (solid, dotted, dashed, dashdot), and border color in a stri * ng. "1px solid green" | "3px dotted purple" | ... */ 'border-top'?: any; borderTop?: any; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; }; label?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. In the scale-x / scale-y label. See the red * text. Works for output flash. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. In the scale-x / scale-y label. See the red text. Works for output canvas and svg. -4 * 5 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). In the scale-x / * scale-y label. See the red text. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. See the red text. Works f * or output canvas and svg. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not in the scale-x / scale-y label. See the red text. true | false | 1 * | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Cuts off extra text. Use with width. For the scale-x / scale-y label. See the red text. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the object's font color. Similar to font-color. For the scale-x / scale-y label. See the red text. "none" | "transparent" | " * #f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. For the scale-x / scale-y label. See the red text. -45 | 115 * | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. For the scale-x / scale-y label. See the red text. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. For the scale-x / scale-y label. See the red text. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. For the scale-x / scale-y label. See the red text. "linear" | " * radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. Similar to angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the object's font color. Similar to color. For the scale-x / scale-y label. See the red text. "none" | "transparent" | "#f00" * | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. For the scale-x / scale-y label. See the red text. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size. For the scale-x / scale-y label. See the red text. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style. Similar to italic. For the scale-x / scale-y label. See the red text. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight. Similar to bold. For the scale-x / scale-y label. See the red text. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. For the scale-x / scale-y label. See the red text. Works with output canvas and svg. 10 | "20px" | 0.3 | * "30%" | ... */ height?: any; /** * Sets whether the text is displayed with italic characters or not. For the scale-x / scale-y label. See the red text. true | false * | 1 | 0 */ italic?: boolean; /** * If set to 'true', scale labels will lock in place and not rotate based upon the viewing angle in 3D charts. */ 'lock-rotation'?: boolean; lockRotation?: boolean; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "...". For the scale-x / scale-y label. See the red text. 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, with the first * value affecting the top padding, the second value affecting the right padding, and so on, in a clockwise direction. 10 | "5px" | " * 10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration. Similar to underline. For output canvas and flash. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text is displayed with underlined characters or not. For output canvas and flash. true | false | 1 | 0 */ underline?: boolean; /** * Sets the visibility of the object. For the label. Used with output canvas and svg. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; mask?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; }; }; 'scale-k'?: scaleK; scaleK?: scaleK; 'scale-r'?: scaleR; scaleR?: scaleR; 'scale-v'?: scaleV; scaleV?: scaleV; 'scale-x'?: scaleX; scaleX?: scaleX; 'scale-y'?: scaleY; scaleY?: scaleY; scale?: { /** * To modify the size of the chart. Provide a value in relation to 1.0 or 100%. 0.3 | 0.9 | "30%" | "90%" | ... */ 'size-factor'?: number; sizeFactor?: number; }; 'scroll-x-scroll-y'?: scrollXSCrollY; scrollXScrollY?: scrollXSCrollY; selectionTool?: { mask?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Requires border-width. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. Defaults to black when border-color is not defined. See also lin * e-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string }; }; series?: series[]; shapes?: [ { /** * Sets the end angle of a pie shape. "10" | "212" | ... */ 'angle-end'?: number; angleEnd?: number; /** * Sets the beginning angle of a pie shape. "10" | "212" | ... */ 'angle-start'?: number; angleStart?: number; /** * Sets the height of the shape "10" | "212" | ... */ height?: number; /** * Id of the shape "myShape" | "Square2" | ... */ id?: string; /** * Sets the radius of the inner ring of a pie shape. "10" | "42" | ... */ slice?: number; /** * Sets the width of the shape "10" | "212" | ... */ width?: number; /** * Sets the transparency of the object. The higher the value, the less transparent the object appears. Value ranges from 0.1 to 1 Req * uires the formatting 0.x 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. Relies on border-width se * tting. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. Defaults to black when border-color is not defined. See also lin * e-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the angle of the axis along which the linear fill is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. Positive value moves the offset right. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets a Y offset to apply to the fill. With a radial fill, positive value moves the offset down. With a linear fill, affects locati * on of the gradient stop. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient (more than 2 colors) of the object. Used with gradient stops. "#f00 #0f0 #0 * 0f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets a set of steps corresponding for each color for a complex background gradient (more than 2 colors) of the object. Paired with * gradient-colors. "0.1 0.5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the item id of the map on which the object/shape is being added. "itemid" | ... */ item?: string; /** * Sets the line color of the object, applicable on non-closed shapes. See also border-color for closed shapes. "none" | "transparent * " | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. See also border-width for closed shapes. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the map id of the map on which the object/shape is being added. "mapid" | ... */ map?: string; /** * Sets a radial offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-r'?: any; offsetR?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** Sets map options */ options?: any; /** * Sets the coordinates of the object/shape points. [ [10,10], [10,20], [20,20], [20,10], [10,10] ] | ... */ points?: any; /** * Sets whether the object gets a shadow or not. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; /** * Sets the type of the object/shape. "rect" | "circle" | "star5" | "star9" | "square" | "diamond" | "triangle" | "plus" | "cross" | * "line" | "poly" | "pie" | ... */ type?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; /** * Sets the z position of the object. Objects with higher z indexes will appear "above" those with lower z index values. 5 | 10 | ... */ 'z-index'?: number; } ]; source?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. In this case, the alpha is applied to the ba * ckground of the object. To affect the alpha of text, use text-alpha. 0....1 */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * For source, bold is the default. true | false | 1 | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Requires border-width. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Requires border-width and defaults to black if there is no border-color specified. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Requires border-width. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Truncates text based on the setting of width. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the object's font color. Similar to font-color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, * 15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Works with fill-angle to position gradient. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Works with fill-angle to position gradient. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. Similar to angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the object's font color. Similar to color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" * | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style. Similar to italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight. Similar to bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the text is displayed with italic characters or not. true | false | 1 | 0 */ italic?: boolean; /** * Sets the item id of the map on which the object/shape is being added. "itemid" | ... */ item?: string; /** * Sets the map id of the map on which the object/shape is being added. "mapid" | ... */ map?: string; /** * Margin is set from top-left of the chart. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ margin?: any; /** * Sets the object's bottom margin. 4 | "6px" | ... */ 'margin-bottom'?: any; marginBottom?: any; /** * Sets the object's left margin. 4 | "6px" | ... */ 'margin-left'?: any; marginLeft?: any; /** * Sets the object's right margin. 4 | "6px" | ... */ 'margin-right'?: any; marginRight?: any; /** * Sets the object's top margin. 4 | "6px" | ... */ 'margin-top'?: any; marginTop?: any; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, with the first * value affecting the top padding, the second value affecting the right padding, and so on, in a clockwise direction. 10 | "5px" | " * 10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Sets the object's position relative to it's container. Similar results can be obtained by setting marginand margin-... attributes. * For source, applying width may also make this more apparent. "50 75" | "50px 75px" */ position?: string; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * For source, this may require position in order to be visible. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration to use underlined characters. Similar to underline. May not display properly in Mozilla Firefox when ch * arts are rendered using SVG. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text is displayed with underlined characters or not. Similar to text-decoration. May not display properly in Mozi * lla Firefox when charts are rendered using SVG. true | false | 1 | 0 */ underline?: boolean; /** * Sets the text's vertical alignment to one of the three applicable values, relative to the object's box. "top" | "middle" | "bottom * " */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; /** * Negative values move the object left from the left edge of the chart. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Positive values move the object down from the top of the chart. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; /** * Sets the z position of the object. Objects with higher z indexes will appear "above" those with lower z index values. 5 | 10 | ... */ 'z-index'?: number; zIndex?: number; }; subtitle?: { /** * Sets the transparency of the object. Requires that background-color be set. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" * | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" * | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not in the subtitle. true | false | 1 | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Defaults to black when color is not set properly. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. Requires border width. See also line-color for closed shapes. "n * one" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Operates like border-bottom. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. The higher the value, the more rounded the corners appear. 4 | "6px" | "6px * 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Operates like border-bottom. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Operates like border-bottom. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. If no border-color is set * , will display in black. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether or not the object will have a callout arrow. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length for extension line off the tip of the callout arrow. Requires border-width. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets a location for the point of the tip of the callout arrow. Uses XY coordinates. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset for the origin of the callout arrow. Uses positive or negative values to move the arrow right/left/up/down. 4 | "6 * px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets which edge will be the location for the object's callout arrow. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Cuts off extra text. Use with width. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the color of the text in the subtitle. Similar with font-color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" * | "rgb(100, 15, 15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear fill is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the fill type. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the rotation angle of the subtitle text. Similar with angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the color of the subtitle text. Similar with color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, * 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the subtitle text. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the subtitle text. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the font style of the subtitle text. Similar with italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the subtitle text. Similar with bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the text of the subtitle is displayed with italic characters or not. Similar with font-weight. true | false | 1 | 0 */ italic?: boolean; /** * Sets the item id of the map on which the object/shape is being added. "itemid" | ... */ item?: string; /** * Sets the map id of the map on which the object/shape is being added. "mapid" | ... */ map?: string; /** * Sets the object's margin/s by positioning it within the specified area. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ margin?: any; /** * Sets the object's bottom margin. 4 | "6px" | ... */ 'margin-bottom'?: any; marginBottom?: any; /** * Sets the object's left margin. 4 | "6px" | ... */ 'margin-left'?: any; marginLeft?: any; /** * Sets the object's left margin. 4 | "6px" | ... */ 'margin-right'?: any; marginRight?: any; /** * Sets the object's margin from the top of the chart. 4 | "6px" | ... */ 'margin-top'?: any; marginTop?: any; /** * Sets the maximum number of characters displayed in the text label of the subtitle. If value is smaller than the length of the text * , the original text will be trimmed and '...' will be appended at the end. 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text of the subtitle. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text of the subtitle. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text of the subtitle. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text of the subtitle. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text of the subtitle. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Sets the object's position relative to it's container. Similar results can be obtained by setting marginand margin-... attributes. */ position?: string; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the text content of the object of the subtitle. Defaults to gray when font-color is not set. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the box of the subtitle. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the transparency of the subtitle text. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text decoration for the subtitle text. Similar with underline. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text of the subtitle is displayed with underlined characters or not. true | false | 1 | 0 */ underline?: boolean; /** * Sets the text's vertical alignment relative to the subtitle object's box . "top" | "middle" | "bottom" */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the visibility of the object. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. May truncate text. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Forces wrapping of the text inside a confined box width. Requires a setting for width. Without text wrap, text will be truncated. * true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; /** * Sets the z position of the object. Objects with higher z indexes will appear "above" those with lower z index values. 5 | 10 | ... */ 'z-index'?: number; zIndex?: number; }; /** * Time-Series Charts only: To set the UTC timezone. Use with the 'utc' attribute and 'transform' object in the applicable scale object. * Default Value: 0 */ 'time-zone'?: number; timeZone?: number; title?: { /** * Forces the plotarea to consider the title positioning and prevent overlapping with it. true | false | 1 | 0 */ 'adjust-layout'?: boolean; adjustLayout?: boolean; /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" * | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" * | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not in the title. true | false | 1 | 0 */ bold?: boolean; /** * Sets the object's bottom border style. Defaults to black when color is not set properly. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. Requires border width. See also line-color for closed shapes. "n * one" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Operates like border-bottom. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. The higher the value, the more rounded the corners appear. 4 | "6px" | "6px * 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Operates like border-bottom. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Operates like border-bottom. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. If no border-color is set * , will display in black.. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets if the object will have a callout arrow. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length for extension line off the tip of the callout arrow. Requires border-width. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets a location for the point of the tip of the callout arrow. Uses XY coordinates. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset for the origin of the callout arrow. Uses positive or negative values to move the arrow right/left/up/down. 4 | "6 * px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets which edge will be the location for the object's callout arrow. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the text's color in the title. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the rotation angle of the title. Similar with angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the text's color of the title. Similar with color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 1 * 5, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family of the title. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size of the title. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style of the title. Similar with italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight of the title. Similar with bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets whether the text of the title is displayed with italic characters or not. Similar with font-weight. true | false | 1 | 0 */ italic?: boolean; /** * Sets the item id of the map on which the object/shape is being added. "itemid" | ... */ item?: string; /** * Sets the map id of the map on which the object/shape is being added. "mapid" | ... */ map?: string; /** * Sets the object's margin/s. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ margin?: any; /** * Sets the object's bottom margin. 4 | "6px" | ... */ 'margin-bottom'?: any; marginBottom?: any; /** * Sets the object's left margin. 4 | "6px" | ... */ 'margin-left'?: any; marginLeft?: any; /** * Sets the object's right margin. 4 | "6px" | ... */ 'margin-right'?: any; marginRight?: any; /** * Sets the object's top margin. 4 | "6px" | ... */ 'margin-top'?: any; marginTop?: any; /** * Sets the maximum number of characters displayed by the text label of the title. If value is smaller than the length of the text, t * he original text will be trimmed and '...' will be appended at the end. 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's bottom padding around the text of the title. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text of the title. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text of the title. padding-left here may push the text out of the containing legend if t * he number is big enough. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text of the title. padding-right here will not push the text out of the containing lege * nd. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text of the title. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Sets the object's position relative to it's container. Similar results can be obtained by setting marginand margin-... attributes. */ position?: string; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the text content of the title. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the box of the text. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency of the title. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration of the title. Similar with underline. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text of the title is displayed with underlined characters or not. true | false | 1 | 0 */ underline?: boolean; /** * Sets the text's vertical alignment relative to the object's box of the title. "top" | "middle" | "bottom" */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; /** * Sets the z position of the object. Objects with higher z indexes will appear "above" those with lower z index values. 5 | 10 | ... */ 'z-index'?: number; zIndex?: number; }; tooltip?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. For graph plot tooltip. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. For graph plot tooltip. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). For graph plot to * oltip. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. For graph plot tooltip. " * none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. For graph plot tooltip. * "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". For graph plot tooltip. "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. For graph plot tooltip. "image.png" | * ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. For graph plot tooltip. "0 0" | "50 100" | "80% * 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. For graph plot tooltip. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the transparency of the border. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'border-alpha'?: number; borderAlpha?: number; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. For graph plot tooltip. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object. For graph plot tooltip. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(1 * 00, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. For graph plot tooltip. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. For grap * h plot tooltip. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. For graph plot tooltip. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. For graph plot tooltip. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object. For graph plot tooltip. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. For graph plot tooltip. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. For graph plot tooltip. 4 | "6px * " | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. For graph plot tooltip. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. For graph plot tooltip. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. For graph plot tooltip. "top" | "right" | " * bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. For graph plot tooltip. 4 | "6px" * | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Cuts off extra text. Use with width. For graph plot tooltip. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the text's color of the tooltip. Similar with font-color. For graph plot tooltip. "none" | "transparent" | "#f00" | "#f00 #00 * f" | "red yellow" | "rgb(100, 15, 15)" | ... */ color?: string; /** * Allows you to set the number of decimal places displayed for each value. 2 | 3 | 10 | ... */ decimals?: number; /** * Allows you to set the decimal mark displayed for each value. "." | "," | " " | ... */ 'decimals-separator'?: string; decimalsSeparator?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. For graph plot tooltip. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. For graph plot tooltip. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. For graph plot tooltip. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. For graph plot tooltip. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the rotation angle of the text of the tooltip. Similar with angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the text's color of the tooltip. Similar with color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, * 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family of the tooltip. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size of the tooltip. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style of the tooltip. Similar with italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight of the tooltip. Similar with bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. For graph p * lot tooltip. "#f00 #0f0 #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. For gra * ph plot tooltip. "0.1 0.5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. For graph plot tooltip. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets the item id of the map on which the object/shape is being added. "itemid" | ... */ item?: string; /** * Sets the map id of the map on which the object/shape is being added. "mapid" | ... */ map?: string; /** * Sets the object's margins. For graph plot tooltip. Works with output flash. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ margin?: any; /** * Sets the object's bottom margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-bottom'?: any; marginBottom?: any; /** * Sets the object's left margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-left'?: any; marginLeft?: any; /** * Sets the object's right margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-right'?: any; marginRight?: any; /** * Sets the object's top margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-top'?: any; marginTop?: any; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." For graph plot tooltip. Works with output canvas and svg. 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. For graph plot tooltip. Works with output canvas and svg. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. For graph plot tooltip. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets an Y offset to apply when positioning the object/shape. For graph plot tooltip. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text of the tooltip. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Specifies where tooltips are fixed relative to their node values. Refer to the applicable chart types page for more information. O * ptions by Chart Type: "node:top" | "node:center" | "node:out" | ... */ placement?: string; /** * Sets the object's position relative to it's container. Similar results can be obtained by setting marginand margin-... attributes. * For graph plot tooltip. */ position?: string; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the transparency of the text. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comple * tely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the character used to separate thousands. "," | "." | " " | ... */ 'thousands-separator'?: string; thousandsSeparator?: string; /** * Allows the underlying data to be 'transformed' to a new format if it was in that format originally. For example, if data is coded * as a date and time, and 'type':'date' is specified as an attribute of this object, '1311261385209' will display 'Wed, 19 of May 05 * :00 PM' if '%D, %d %M %h:%i %A' is specified under the transform attribute of scale-x. {...} */ transform?: any; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. For graph plot tooltip. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; /** * Sets the z position of the object. Objects with higher z indexes will appear "above" those with lower z index values. 5 | 10 | ... */ 'z-index'?: number; zIndex?: number; }; /** * Time-Series Charts only: To set the chart to UTC time. Use with the 'timezone' attribute and 'transform' object in the applicable scale object. */ utc?: boolean; widget?: { /** * Type of the widget. The zingchart.widgets.myWidget object must exist and define a "parse" method returning an object with "graphs" * , "labels" and "shapes" collections which will be injected in the original JSON. "myWidget" | ... */ type?: string; }; zoom?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * API charts only: Sets whether the zoom level is preserved on chart data alteration or reloads. true | false | 1 | 0 */ 'preserve-zoom'?: boolean; preserveZoom?: boolean; label?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the border color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object. 1 | 3 | | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the font color of the object text. "none" | "transparent" | "purple" | "#33ccff" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the font family of the object text. "Courier" | "Georgia" | "Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the font size of the object text. 12 | "20px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the font style of the object text. "normal" | "italic" */ 'font-style'?: string; fontStyle?: string; /** * Sets the font weight of the object text. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets the padding around the object text. "10%" | "25px" ... */ padding?: number; /** * Sets the visibility of the object. true | false | 1 | 0 */ visible?: boolean; }; /** * To enabled shared zooming when there are mulitple charts in a graphset */ shared?: boolean; }; /** * @description When zooming is enabled, setting zoom-snap to true snaps the zoom area to the nearest data node as a zoom area is selected. By default, zoom-snap is set to false. */ zoomSnap?: boolean; } interface behavior { /** * To enable or disable individual context menu item behaviors. "all" | "none" */ enabled?: string; /** * To specify the behavior ID of the context menu item that is being accessed. "3D" | "LogScale" | "LinScale" | ... */ id?: string; } interface gui { /** * To create custom context menu items */ behaviors?: behavior[]; 'context-menu'?: contextMenuGui; contextMenu?: contextMenuGui; } interface history { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets the object's margin/s. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ margin?: any; /** * Sets the object's bottom margin. 4 | "6px" | ... */ 'margin-bottom'?: any; marginBottom?: any; /** * Sets the object's left margin. 4 | "6px" | ... */ 'margin-left'?: any; marginLeft?: any; /** * Sets the object's right margin. 4 | "6px" | ... */ 'margin-right'?: any; marginRight?: any; /** * Sets the object's top margin. 4 | "6px" | ... */ 'margin-top'?: any; marginTop?: any; /** * Sets the object's position relative to it's container. Similar results can be obtained by setting marginand margin-... attributes. */ position?: string; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; 'item-off'?: itemOff; itemOff?: itemOff; item?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; }; } interface refresh { /** * Sets the type of data refresh, full being the only option at loader's level. "full" */ type?: string; /** * Defines the specific type of feed. http | js | websockets */ transport?: string; /** * The url path for the feed. feed() | https://myPhpFunction.php | wss://websockets.zingchart.com:8889 */ url?: string; /** * Sets the timeout between two refresh operations. If value is smaller than 50, seconds are assumed, otherwise milliseconds are assu * med. 5 | 10 | ... */ interval?: number; /** * Sets the max amount of nodes visible in the graph. 5 | 10 | ... */ 'max-ticks'?: number; maxTicks?: number; /** * The number of nodes before starting the feed from 0 again. 500 | 1000 | ... */ 'reset-timeout'?: number; resetTimeout?: number; /** * Enabling true will allow dynamic value range of the scale pertaining to the values. false (default) | true */ 'adjust-scale'?: boolean; adjustScale?: boolean; curtain?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets whether the text is displayed with bold characters or not. true | false | 1 | 0 */ bold?: string; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object, applicable on closed shapes. See also line-color for closed shapes. "none" | "transparent" | * "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object, applicable on closed shapes. See also line-width for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the length of the extension that extends beyond the tip of the callout arrow. 4 | "6px" | ... */ 'callout-extension'?: any; calloutExtension?: any; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Sets the object's font color. Similar to font-color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, * 15)" | ... */ color?: string; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the object's font angle. A positive value will rotate the object by that number of degrees clockwise, while a negative value * will rotate the object by that number of degrees counter-clockwise. Similar to angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the object's font color. Similar to color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" * | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style. Similar to italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight. Similar to bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets whether the text is displayed with italic characters or not. true | false | 1 | 0 */ italic?: boolean; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text. Up to four values can be entered to set the padding for all four sides, with the first * value affecting the top padding, the second value affecting the right padding, and so on, in a clockwise direction. 10 | "5px" | " * 10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the text content of the object. "Some Text" | ... */ text?: string; /** * Sets the text's horizontal alignment relative to the object's box. "left" | "center" | "right" */ 'text-align'?: string; textAlign?: string; /** * Sets the text's transparency independent of the object's transparency. Value must be between 0.0 and 1.0, with 0.0 being 100% tran * sparent and 1.0 being 100% opaque. The leading 0 before the decimal is required. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the text's decoration to use underlined characters. Similar to underline. May not display properly in Mozilla Firefox when ch * arts are rendered using SVG. "none" | "underline" */ 'text-decoration'?: string; textDecoration?: string; /** * Sets whether the text is displayed with underlined characters or not. Similar to text-decoration. May not display properly in Mozi * lla Firefox when charts are rendered using SVG. true | false | 1 | 0 */ underline?: boolean; /** * Sets the text's vertical alignment to one of the three applicable values, relative to the object's box. "top" | "middle" | "bottom * " */ 'vertical-align'?: string; verticalAlign?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets whether the text will wrap, depending on the width of the object. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; }; } interface series { /** * Sets the transparency level of backgrounds, borders, and lines. Values must range between 0.0 and 1.0, with 0.0 being completely t * ransparent and 1.0 being completely opaque. Note that values require the leading zero before the decimal point. 0.3 | 0.9 | ... */ alpha?: number; /** * Modifies how data points appear on a chart. Refer to the applicable chart types page for more information. Options by Chart Type: * "segmented" | "spline" | "stepped" | "jumped" | "cone" | "histogram" | ... */ aspect?: string; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use "gradient-c * olors" and "gradient-stops". "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with "background-color-2". "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with "background-color-1". "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the "background-repeat" value is "no-repeat". "0 0" | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Nested Pie Charts Only: This attribute is used to set the space between band in nested pie charts ("type":"nestedpie"). 5 | 10 | . * .. */ 'band-space'?: number; bandSpace?: number; /** * Bar Charts and Bullet Charts Only: Sets the amount of space between each bar in a single plot index. "10" | "10%" | "10px" */ 'bar-space'?: number; barSpace?: number; /** * Bar Charts and Bullet Charts Only: Sets the width of each bar. "10" | "10%" | "10px" */ 'bar-width'?: number; barWidth?: number; /** * Bar Charts and Bullet Charts Only: Defines how much the bars in each plot index should overlap. "10" | "10%" | "10px" */ 'bars-overlap'?: number; barsOverlap?: number; /** * Bar Charts and Bullet Charts Only: Defines the spacing to the left of the bars at each index position. "10" | "10%" | "10px" */ 'bars-space-left'?: number; barsSpaceLeft?: number; /** * Bar Charts and Bullet Charts Only: Defines the spacing to the right of the bars at each index position. "10" | "10%" | "10px" */ 'bars-space-right'?: number; barsSpaceRight?: number; /** * Sets the border color of the object, applicable on closed shapes. See also "line-color" for closed shapes. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. A negati * ve value will cut a corner off without rounding. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the border width of the object, applicable on closed shapes. See also "line-width" for closed shapes. 4 | "6px" | ... */ 'border-width'?: number | string; borderWidth?: number | string; /** * Sets whether an object will have a callout arrow or not. true | false | 1 | 0 */ callout?: boolean; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. 4 | "6px" | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the "callout-position". 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. "top" | "right" | "bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. 4 | "6px" | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Area Charts Only: Sets whether the contour lines on area plots will be on top of all areas or will be hidden by the next area plot * on top of it. You will notice when the attribute is set to true the lines are all set above the shaded regions. true | false | 1 * | 0 */ 'contour-on-top'?: boolean; contourOnTop?: boolean; /** * By defalut null values within series arrays will create a blank space within a plot. Setting connect-nulls to true will connect va * lues through a null data point. true | false | 1 | 0 */ 'connect-nulls'?: boolean; connectNulls?: boolean; /** * Sets the style of the cursor when hovering over a node. "hand" | "normal" */ cursor?: string; /** * This attribute allows you to create custom tokens and associate static or dynamic data to them. This attribute can be used almost * anywhere in a chart. "Some Text" | ... */ 'data-...'?: string; /** * This attribute allows you to click and drag a bar's height in a bar chart. true | false | 1 | 0 */ 'data-dragging'?: boolean; dataDragging?: boolean; /** * Using the decimals attribute will allow you to set the number of decimal places associated to each value. 5 | 10 | ... */ decimals?: number; /** * The "decimals-separator": attribute allows you to set what type of punctuation the will be used in the decimal place. "." | "," | * ... */ 'decimals-separator'?: string; decimalsSeparator?: string; /** * This attribute sets description text for the plot which can be addressed in various areas with the %plot-description token. "Some * Text" | ... */ description?: string; /** * By default ZingChart uses sampling when rendering charts. This helps improve rendering speeds and typically does not effect the ap * pearance of the chart. However, using the attribute "exact": true within the "plot": { } object forces ZingChart to render all nod * es. true | false | 1 | 0 */ exact?: boolean; /** * This attribute sets the values to scientific notation true | false | 1 | 0 */ exponent?: boolean; /** * This attribute set the number of decimals to be used when using exponents for scientific notation 5 | 10 | ... */ 'exponent-decimals'?: number; exponentDecimals?: number; /** * Sets the angle of the axis along which the linear gradient is drawn. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Bullet Charts Only: Accepts numerical values. Determines where goals are set for all plots. The "goals": [ ] values can also be se * t individually within each value set. [45, 70, 60] */ goals?: any; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with "gradient-stops". "#f00 #0f * 0 #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with "gradient-colors". "0.1 * 0.5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * When true, automatically selects all nodes with the same scale index as the selected node. The selection-mode attribute must also * be set. true | false | 1 | 0 */ 'group-selections'?: boolean; groupSelections?: boolean; /** * Sets the ID of the object. "myid" | "f1" | ... */ id?: string; /** * Venn Diagrams Only: This attribute allow you to set the values for the area to be shared between each node. [30] */ join?: any; /** * The "legend-text": attribute is typically used within "series": [ ] value sets. Using this attribute allows you to associate both * a "text":" " and "legend-text":" " to each value set "Some Text" | ... */ 'legend-text'?: string; legendText?: string; /** * Sets the line color of the object, applicable on non-closed shapes. See also "border-color" for closed shapes. "none" | "transpare * nt" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with "line-segment-size". This will control the size of the gaps bet * ween each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with "line-gap-size". This will control the size of the visible segm * ent of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. See also "border-width" for closed shapes. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Applies to charts such as line and area which have markers. When there are too many markers for the chart ZingChart does not displ * ay all markers. Example 1000 nodes on a 300px wide chart. Setting max-nodes will override the default setting and force nodes to b * e displayed. 5 | 10 | ... */ 'max-nodes'?: number; maxNodes?: number; /** * Heat Maps Only: Sets a maximum ratio applied to the value of the node when calculating its aspect. 0 | 0.4 | ... */ 'max-ratio'?: number; maxRatio?: number; /** * Bubble Charts and Bubble Pie Charts Only: Defines the maximum size of the bubble if the value representing size is not sharing the * same ratio with the value scale. 5 | 10 | ... */ 'max-size'?: number; maxSize?: number; /** * Sets the maximum numbers of nodes for which a tracking area will be created. This is best used to optimize charts with large sets * of data. 5 | 10 | ... */ 'max-trackers'?: number; maxTrackers?: number; /** * Sets whether or not a node is wrapped equally before and after its position. true | false | 1 | 0 */ 'mid-point'?: boolean; midPoint?: boolean; /** * Heat Maps Only: Sets a minimum ratio applied to the value of the node when calculating its aspect. 0 | 0.4 | ... */ 'min-ratio'?: number; minRatio?: number; /** * Bubble Charts and Bubble Pie Charts Only: Defines the minimum size of the bubble if the value representing size is not sharing the * same ratio with the value scale. 5 | 10 | ... */ 'min-size'?: number; minSize?: number; /** * Sets whether monotone interpolation is used for charts using the "spline" aspect. true | false | 1 | 0 */ monotone?: boolean; /** * Setting "multiplier": true will take large numbers such as thousands, millions, etc and replace the full number with an abbreviate * d notation with a short unit such as K, M, B, etc true | false | 1 | 0 */ multiplier?: boolean; /** * This attribute will determine how negative values are handled. When using "format":"$%v" setting "negation":"currency" will move t * he - symbol to the outside of the $ sign. When using "negation" within the "plot": { } object you will see changes in things such * as tooltips or anywhere else series data is used to populate values. You need to set "negation" in things such as "scale-y": { } s * eparately. "standard" | "currency" */ negation?: string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Bar, Line and Area Charts only Include object in any series to override style displayed in the preview window. {...} */ 'preview-state'?: any; previewState?: any; /** * Pie Charts Only: Provides the ability to rotate the chart. 5 | 10 | ... */ 'ref-angle'?: number; refAngle?: number; /** * Heat Maps Only: Sets the value (default 'plot-max') which is used as a reference for calculating node aspect. "plot-max" | "plot-t * otal" | "chart-max" | "chart-total" */ reference?: string; /** * By default ZingChart uses sampling when rendering large datasets. If you are trying to render 10000 data points on a chart which i * s only 500px wide there is not enough space for each data point. ZingChart will automatically determine which data points to show. * The "sampling-step": attribute allows you to set the step for sampling. For example if you have 10000 data points and set "sampli * ng-step":10 it will show point 1,10,20,... Also note the "exact": true attribute if you want to force all data points. 5 | 10 | .. * . */ 'sampling-step'?: number; samplingStep?: number; /** * Specifies the scales used by the series item. scale-x,scale-y | scale-x,scale-y-2 | ... */ scales?: string; /** * Bubble Charts and Bubble Pie Charts Only: Sets the method used to relate the bubble numerical value to it's aspect. "radius" | "sq * rt" | "area" */ scaling?: string; /** * When scrolling is enabled for a chart, ZingChart automatically samples the data in order to maintain performance during the re-ren * dering of the chart that occurs during scrolling. By default, ZingChart will automatically sample every other item (scroll-step-mu * ltiplier:2). Setting scroll-step-multiplier to 1 will force the library to sample every data point, essentially disabling sampling * . 5 | 10 | ... */ 'scroll-step-multiplier'?: number; scrollStepMultiplier?: number; /** * Line Charts and Area Charts Only: Allows you to specify whether tooltips are activated by the markers and lines (default) or the m * arkers only. true (default) | false */ 'segment-trackers'?: boolean; segmentTrackers?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Setting "short": true will abbreviate long numbers such as 100000 to 1K or 1000000 to 1M. When set within the "plot": {} object th * is change will be noticed anywhere values are pulled from series data. This can also be used in places such as "scale-y, scale-x, * etc" true | false | 1 | 0 */ short?: boolean; /** * By default when setting "short": true ZingChart will round to the nearest short unit (ie 100000 to 100K and 1000000 to 1M). You ca * n set the short-unit and ZingChart will round all numbers to that unit. Note when setting this within the "plot": { } object the c * hanges will only effect values which are pulled from the series values. Things such as scale are set separately. "k" | "K" | "m" | * "M" | "b" | "B" */ 'short-unit'?: string; shortUnit?: string; /** * On bar charts, when the value of a bar is 0, setting `show-zero`: true will add 1 pixel to the height of the bar so that it is onl * y just visible. true | false | 1 | 0 */ 'show-zero'?: boolean; showZero?: boolean; /** * Bubble Charts and Bubble Pie Charts Only: Sets a multiplier (default 1) used to increase/decrease the bubble size 5 | 10 | ... */ 'size-factor'?: number; sizeFactor?: number; /** * Nested Pie Charts Only: Sets the initial offset of the pie layers when making a nestedpie 5 | 10 | ... */ 'slice-start'?: number; sliceStart?: number; /** * Using the "stack": attribute allows you to assign which plot index you want to each value set associated with when using a stacked * chart. 5 | 10 | ... */ stack?: number; /** * Setting "stacked": true will take each of the "series": [ ] value sets and stack them on top of one another true | false | 1 | 0 */ stacked?: boolean; /** * Applicable on aspect=stepped, sets the location of the stepping relative to two consecutive nodes. "before" | "middle" | "after" */ 'step-start'?: string; stepStart?: string; /** * Sets the url's target for the link associated with the object. Use with "url". "_blank" | ... */ target?: string; /** * Sets the thickness of pie3d charts. 5 | 10 | ... */ thickness?: number; /** * When you set the "thousands-separator": attribute the punctuation which is used will be placed to separate digits which go into 1, * 000's 10,000's etc. When placed in the "plot": { } object this will only effect values which are pulled directly from the series d * ata. Objects such as "scale-y": { }, "scale-x": { }, etc..., will need to be set separately. "." | "," | ... */ 'thousands-separator'?: string; thousandsSeparator?: string; /** * Using the "tooltip-text":" " attribute allows you to set text for tooltips. This can also be done using a variety of other tokens * "Some Text" | ... */ 'tooltip-text'?: string; tooltipText?: string; /** * Sets the type of the object/shape. * Accepted Values: ['arc', 'arrow', 'circle', 'cross', 'diamond', 'ellipse','gear3', 'gear4', 'gear5', 'gear6', 'gear7', 'gear8', 'gear9', 'hamburger', 'line', 'parallelogram', 'pie','plus', * 'poly', 'rect', 'rpoly3', 'rpoly4', 'rpoly5', 'rpoly6', 'rpoly7', 'rpoly8', 'rpoly9', 'square', 'star3', 'star4', 'star5', 'star6', 'star7', 'star8', 'star9', 'trapezoid', 'triangle'] * Default Value: 'poly' */ type?: string; /** * Sets the URL for the link associated with the object. "http://www.domain.com/link.php" | "link.asp" | ... */ url?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the z-axis end point on 3d charts. 10 | "10px" | ... */ 'z-end'?: number; zEnd?: number; /** * Sets the z-axis start point on 3d charts. 10 | "10px" | ... */ 'z-start'?: number; zStart?: number; animation?: { /** * Sets the delay in milliseconds between each step of the animation. 5 | 10 | ... */ delay?: number; /** * Sets the type of animation effect. ANIMATION_FADE_IN | ANIMATION_EXPAND_VERTICAL | 1 | 2 | ... */ effect?: number; /** * Sets the method used for each animation effect. ANIMATION_LINEAR | ANIMATION_BACK_EASE_OUT | 0 | 1 | ... */ method?: number; /** * Determines whether or not animation occurs when a change is made to the chart via an API event (e.g., adding node, adding plot, re * moving node). true (default) | false | 1 | 0 */ 'on-change'?: boolean; onChange?: boolean; /** * Determines whether or not animation occurs when users toggle legend items on and off. Note that in the "legend" object, the "toggl * e-action" attribute must be set to "remove". true (default) | false | 1 | 0 */ 'on-legend-toggle'?: boolean; onLegendToggle?: boolean; /** * Determines animation groups. ANIMATION_NO_SEQUENCE | ANIMATION_BY_PLOT | 0 | 1 | ... */ sequence?: number; /** * Sets the length of the animation in milliseconds. ANIMATION_SLOW | ANIMATION_FAST | 1000 | 4000 | ... */ speed?: number; }; 'background-marker'?: backgroundMarker; backgroundMarker?: backgroundMarker; 'background-state'?: backgroundState; backgroundState?: backgroundState; error?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the line color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Can be used to create custom dashed or dotted lines when used with line-segment-size. This will control the size of the gaps betwe * en each line segment. 4 | "6px" | ... */ 'line-gap-size'?: any; lineGapSize?: any; /** * Can be used to create custom dashed or dotted lines when used with line-gap-size. This will control the size of the visible segmen * t of line. 4 | "6px" | ... */ 'line-segment-size'?: any; lineSegmentSize?: any; /** * Sets the style applied to lines and borders of the object. "solid" | "dotted" | "dashed" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object, applicable on non-closed shapes. See also border-width for closed shapes. 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; }; errors?: [{}]; goal?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Note that values require the leading zero before the decimal. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the background color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: any; backgroundColor?: any; /** * Sets the border color of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: any; borderColor?: any; /** * Sets the border radius of the object, for rounded corners. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: number | string; borderRadius?: number | string; /** * Sets the border width of the object. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the height of the object. 10 | "20px" */ height?: number; /** * Sets the line style of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; }; 'guide-label'?: guideLabel; guideLabel?: guideLabel; 'highlight-marker'?: highlightMarker; highlightMarker?: highlightMarker; 'highlight-state'?: highlightState; highlightState?: highlightState; 'hover-marker'?: hoverMarker; hoverMarker?: hoverMarker; 'hover-state'?: hoverState; hoverState?: hoverState; 'legend-item'?: legendItem; legendItem?: legendItem; 'legend-marker'?: legendMarker; legendMarker?: legendMarker; marker?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. See the square points between the lines. 0.3 * | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. See the square points between the lines. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). One color will se * t a solid background color, two colors will, by default, create a horizontal gradient. For more complex gradients, use gradient-co * lors and gradient-stops. See the square points between the lines. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | " * rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. See the square points bet * ween the lines. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. See the square points be * tween the lines. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". Used with background-image. See the square points between * the lines. "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. See the square points between the lin * es. "image.png" | ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. See the square points between the lines. "0 0" * | "50 100" | "80% 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. See the square points between the lines. "no-repeat" | "repeat" | "repeat-x" | " * repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the border color of the object, applicable on closed shapes. See the square points between the lines. "none" | "transparent" * | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. * 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the border width of the object, applicable on closed shapes. See the square points between the lines. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string /** * Sets the angle of the axis along which the linear gradient is drawn. See the square points between the lines. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. See the square points between the lines. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. See the square points between the lines. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. See the square points between the lines. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the text's font size of the marker. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. "#f00 #0f0 * #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. "0.1 0. * 5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the map id of the map on which the object/shape is being added. "mapid" | ... */ map?: string; /** * Sets an X offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets a Y offset to apply when positioning the object/shape. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the size of the object/shape. 4 | "6px" | ... */ size?: any; /** * Sets the character used to separate thousands. "," | "." | " " | ... */ 'thousands-separator'?: string; thousandsSeparator?: string; /** * The type of the marker object to render. square | circle | diamond | triangle | star5 | star6 | star7 | star8 | rpoly5 | gear5 | g * ear6 | gear7 | gear8 */ type?: string; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the X position of the object. 10 | "20px" | 0.3 | "30%" | ... */ x?: any; /** * Sets the Y position of the object. 10 | "20px" | 0.3 | "30%" | ... */ y?: any; /** * Sets the z position of the object. Objects with higher z indexes will appear "above" those with lower z index values. 5 | 10 | ... */ 'z-index'?: number; zIndex?: number; }; preview?: { /** * Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely transparent and 1.0 be * ing completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ alpha?: number; /** * Area Chart only: Sets the transparency level of the object. Values must range between 0.0 and 1.0, with 0.0 being completely trans * parent and 1.0 being completely opaque. Note that values require the leading 0 before the decimal point. 0.3 | 0.4 | 0.9 | ... */ 'alpha-area'?: number; alphaArea?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g., "purple", "blue"), hexadecimal notation (e.g., "#666 * 699", #33ccff"), or RGB notation (e.g., "rgb(255,0,0)", "rgb(0,0,255)"). "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, * 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the line color of the object. "none" | "transparent" | "purple" | "#33ccff" | "rgb(100, 15, 15)" | ... */ 'line-color'?: string; lineColor?: string; /** * Sets the line style of the object. "solid" | "dotted" | "dashed" | "dashdot" */ 'line-style'?: string; lineStyle?: string; /** * Sets the line width of the object. 2 | 4 | "6px" | ... */ 'line-width'?: number | string; lineWidth?: number | string; /** * To set the stock preview chart type: area chart or line chart. "area" (default) | "line" */ type?: string; }; rules?: [ { /** * A rule allows you to include logic in order to apply a set of attributes only to certain aspects of your chart that meet the crite * ria specified within each "rule": group. You can include any number of "rule": groups nested within a "rules": set. Place the desi * red attribute or attributes within each "rule": group to apply those attributes to the areas that fulfill the requirement. The eff * ect of rules depends largely on the placement of the "rules": set within your JSON code. In the above example, the styling attribu * tes within each rule will be applied to the scale-y guide. "%c == 2" | "%v <= 0" | "%v > 0" | ... */ rule?: string; } ]; 'selected-marker'?: selectedMarker; selectedMarker?: selectedMarker; 'selected-state'?: selectedState; selectedState?: selectedState; text?: string; tooltip?: { /** * Sets the transparency of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. For graph plot tooltip. 0.3 | 0.9 | ... */ alpha?: number; /** * Sets the rotation angle of the object/shape. For graph plot tooltip. -45 | 115 | ... */ angle?: number; /** * Sets the background color of the object. Colors can be entered by name (e.g. "red", "blue", "yellow"), in hexadecimal notation (e. * g. "#FF0000", "#0000FF", "#FFFF00"), or in RGB notation (e.g. "rgb(255,0,0)", "rgb(0,0,255)", "rgb(255,255,0)"). For graph plot to * oltip. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color'?: string; backgroundColor?: string; /** * Sets the first color of a 2 color background gradient of the object. To be used with background-color-2. For graph plot tooltip. " * none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-1'?: string; backgroundColor1?: string; /** * Sets the second color of a 2 color background gradient of the object. To be used with background-color-1. For graph plot tooltip. * "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | ... */ 'background-color-2'?: string; backgroundColor2?: string; /** * Sets the direction/s on which the background image is being "stretched". For graph plot tooltip. "x" | "y" | "xy" */ 'background-fit'?: string; backgroundFit?: string; /** * Sets a background image for the object. Value can be a local file or a web image's location. For graph plot tooltip. "image.png" | * ... */ 'background-image'?: string; backgroundImage?: string; /** * Sets the position of the background when the background-repeat value is no-repeat. For graph plot tooltip. "0 0" | "50 100" | "80% * 60%" | ... */ 'background-position'?: string; backgroundPosition?: string; /** * Sets the repeating mode for the background image. For graph plot tooltip. "no-repeat" | "repeat" | "repeat-x" | "repeat-y" */ 'background-repeat'?: string; backgroundRepeat?: string; /** * Sets the transparency of the border. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comp * letely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'border-alpha'?: number; borderAlpha?: number; /** * Sets the object's bottom border style. Accepts solid, dashed, and dotted styles. For graph plot tooltip. "2px solid #f00" | ... */ 'border-bottom'?: string; borderBottom?: string; /** * Sets the border color of the object. For graph plot tooltip. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(1 * 00, 15, 15)" | ... */ 'border-color'?: string; borderColor?: string; /** * Sets the object's left border style. Accepts solid, dashed, and dotted styles. For graph plot tooltip. "2px solid #f00" | ... */ 'border-left'?: string; borderLeft?: string; /** * Sets the object's border radius, for rounded corners. Larger values create rounder corners, while smaller values create sharper co * rners. A single value will affect all 4 corners, while multiple values will have separate effects on each corner, with the first v * alue affecting the top-left corner, the second value affecting the top-right corner, and so on, in a clockwise direction. For grap * h plot tooltip. 4 | "6px" | "6px 10px 3px 5px" | "-10px" | ... */ 'border-radius'?: any; borderRadius?: any; /** * Sets the object's bottom-left border radius, for rounded corners. Larger values create rounder corners, while smaller values creat * e sharper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-left'?: any; borderRadiusBottomLeft?: any; /** * Sets the object's bottom-right border radius, for rounded corners. Larger values create rounder corners, while smaller values crea * te sharper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-bottom-right'?: any; borderRadiusBottomRight?: any; /** * Sets the object's top-left border radius, for rounded corners. Larger values create rounder corners, while smaller values create s * harper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-left'?: any; borderRadiusTopLeft?: any; /** * Sets the object's top-right border radius, for rounded corners. Larger values create rounder corners, while smaller values create * sharper corners. A negative value will cut a corner off without rounding. For graph plot tooltip. 4 | "6px" | "-6px" | -4 | ... */ 'border-radius-top-right'?: any; borderRadiusTopRight?: any; /** * Sets the object's right border style. Accepts solid, dashed, and dotted styles. For graph plot tooltip. "2px solid #f00" | ... */ 'border-right'?: string; borderRight?: string; /** * Sets the object's top border style. Values must include the border width, style, and color. Accepts solid, dashed, and dotted styl * es. For graph plot tooltip. "2px solid #f00" | ... */ 'border-top'?: string; borderTop?: string; /** * Sets the border width of the object. For graph plot tooltip. 4 | "6px" | ... */ 'border-width'?: number | string borderWidth?: number | string; /** * Sets whether an object will have a callout arrow or not. For graph plot tooltip. true | false | 1 | 0 */ callout?: boolean; /** * Sets the height of the object's callout arrow. A larger value will create a taller callout arrow. For graph plot tooltip. 4 | "6px * " | ... */ 'callout-height'?: any; calloutHeight?: any; /** * Sets the point of the tip of the callout arrow to a specified coordinate on the chart, with the starting point of [0,0] being the * top left corner of the chart. For graph plot tooltip. [200, 50] | ... */ 'callout-hook'?: any; calloutHook?: any; /** * Sets the offset along the callout direction of the arrow's base. Positive and negative values can be used to offset the callout ar * row up, down, left, or right depending on the callout-position. For graph plot tooltip. 4 | "6px" | ... */ 'callout-offset'?: any; calloutOffset?: any; /** * Sets the position for the object's callout arrow. The position is "bottom" by default. For graph plot tooltip. "top" | "right" | " * bottom" | "left" */ 'callout-position'?: string; calloutPosition?: string; /** * Sets the width of the object's callout arrow. A larger value will create a wider callout arrow. For graph plot tooltip. 4 | "6px" * | ... */ 'callout-width'?: any; calloutWidth?: any; /** * Cuts off extra text. Use with width. For graph plot tooltip. true | false | 1 | 0 */ 'clip-text'?: boolean; clipText?: boolean; /** * Sets the text's color of the tooltip. Similar with font-color. For graph plot tooltip. "none" | "transparent" | "#f00" | "#f00 #00 * f" | "red yellow" | "rgb(100, 15, 15)" | ... */ color?: string; /** * Allows you to set the number of decimal places displayed for each value. 2 | 3 | 10 | ... */ decimals?: number; /** * Sets the angle of the axis along which the linear gradient is drawn. For graph plot tooltip. -45 | 115 | ... */ 'fill-angle'?: number; fillAngle?: number; /** * Sets an X offset to apply to the fill. For graph plot tooltip. 4 | "6px" | ... */ 'fill-offset-x'?: any; fillOffsetX?: any; /** * Sets an Y offset to apply to the fill. For graph plot tooltip. 4 | "6px" | ... */ 'fill-offset-y'?: any; fillOffsetY?: any; /** * Sets the background gradient fill type to either linear or radial. For graph plot tooltip. "linear" | "radial" */ 'fill-type'?: string; fillType?: string; /** * Sets the rotation angle of the text of the tooltip. Similar with angle. -45 | 115 | ... */ 'font-angle'?: number; fontAngle?: number; /** * Sets the text's color of the tooltip. Similar with color. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, * 15, 15)" | ... */ 'font-color'?: string; fontColor?: string; /** * Sets the text's font family of the tooltip. "Arial" | "Tahoma,Verdana" | ... */ 'font-family'?: string; fontFamily?: string; /** * Sets the text's font size of the tooltip. 4 | "6px" | ... */ 'font-size'?: any; fontSize?: any; /** * Sets the text's font style of the tooltip. Similar with italic. "none" | "italic" | "oblique" */ 'font-style'?: string; fontStyle?: string; /** * Sets the text's font weight of the tooltip. Similar with bold. "normal" | "bold" */ 'font-weight'?: string; fontWeight?: string; /** * Sets a set of colors for a complex background gradient consisting of 2 or more colors. To be used with gradient-stops. For graph p * lot tooltip. "#f00 #0f0 #00f" | ... */ 'gradient-colors'?: string; gradientColors?: string; /** * Sets the gradient stops for a complex background gradient consisting of 2 or more colors. To be used with gradient-colors. For gra * ph plot tooltip. "0.1 0.5 0.9" | ... */ 'gradient-stops'?: string; gradientStops?: string; /** * Sets the object's height. For graph plot tooltip. 10 | "20px" | 0.3 | "30%" | ... */ height?: any; /** * Sets the object's margins. For graph plot tooltip. Works with output flash. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ margin?: any; /** * Sets the object's bottom margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-bottom'?: any; marginBottom?: any; /** * Sets the object's left margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-left'?: any; marginLeft?: any; /** * Sets the object's right margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-right'?: any; marginRight?: any; /** * Sets the object's top margin. For graph plot tooltip. Works with output flash. 4 | "6px" | ... */ 'margin-top'?: any; marginTop?: any; /** * Sets the maximum numbers of characters displayed in the object. The value determines how many characters will be displayed before * the text is cut and appended with "..." For graph plot tooltip. Works with output canvas and svg. 5 | 10 | ... */ 'max-chars'?: number; maxChars?: number; /** * Sets the maximum width of the text box. If text is longer than the max-width value, it will overlap the box or will wrap if wrap-t * ext is set to true. For graph plot tooltip. Works with output canvas and svg. 10 | "20px" | 0.3 | "30%" | ... */ 'max-width'?: any; maxWidth?: any; /** * Sets an X offset to apply when positioning the object/shape. For graph plot tooltip. 4 | "6px" | ... */ 'offset-x'?: any; offsetX?: any; /** * Sets an Y offset to apply when positioning the object/shape. For graph plot tooltip. 4 | "6px" | ... */ 'offset-y'?: any; offsetY?: any; /** * Sets the object's padding around the text of the tooltip. 10 | "5px" | "10 20" | "5px 10px 15px 20px" | ... */ padding?: any; /** * Sets the object's bottom padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-bottom'?: any; paddingBottom?: any; /** * Sets the object's left padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-left'?: any; paddingLeft?: any; /** * Sets the object's right padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-right'?: any; paddingRight?: any; /** * Sets the object's top padding around the text of the tooltip. 4 | "6px" | ... */ 'padding-top'?: any; paddingTop?: any; /** * Specifies where tooltips are fixed relative to their node values. Refer to the applicable chart types page for more information. O * ptions by Chart Type: "node:top" | "node:center" | "node:out" | ... */ placement?: string; /** * Sets the object's position relative to it's container. Similar results can be obtained by setting marginand margin-... attributes. * For graph plot tooltip. */ position?: string; /** * Renders text right-to-left. Default value is false. true | false | 1 | 0 */ rtl?: boolean; /** * Sets whether the object's shadow is visible or not. Has limited effect on HTML5 implementation. true | false | 1 | 0 */ shadow?: boolean; /** * Sets the transparency of the shadow of the object. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and * 1.0 being completely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'shadow-alpha'?: number; shadowAlpha?: number; /** * Sets the angle of the shadow underneath the object. -45 | 115 | ... */ 'shadow-angle'?: number; shadowAngle?: number; /** * Sets the blur effect size for the shadow of the object. Has limited effect on HTML5 implementation. 4 | "6px" | ... */ 'shadow-blur'?: any; shadowBlur?: any; /** * Sets the color of the shadow of the object. "none" | "transparent" | "#f00" | "#f00 #00f" | "red yellow" | "rgb(100, 15, 15)" | .. * . */ 'shadow-color'?: string; shadowColor?: string; /** * Sets the distance between the shadow and the object. 4 | "6px" | ... */ 'shadow-distance'?: any; shadowDistance?: any; /** * Sets the transparency of the text. Values must range between 0.0 and 1.0, with 0.0 being completely invisible and 1.0 being comple * tely opaque. Please note that values also require the leading 0 before the decimal. 0.3 | 0.9 | ... */ 'text-alpha'?: number; textAlpha?: number; /** * Sets the visibility of the object. Allows you to turn off the object without removing lines of JSON. true | false | 1 | 0 */ visible?: boolean; /** * Sets the object's width. 10 | "20px" | 0.3 | "30%" | ... */ width?: any; /** * Sets whether the text will wrap, depending on the width of the object. For graph plot tooltip. true | false | 1 | 0 */ 'wrap-text'?: boolean; wrapText?: boolean; /** * Sets the z position of the object. Objects with higher z indexes will appear "above" those with lower z index values. 5 | 10 | ... */ 'z-index'?: number; zIndex?: number; }; 'trend-down'?: trendDown; trendDown?: trendDown; 'trend-equal'?: trendEqual; trendEqual?: trendEqual; 'trend-up'?: trendUp; trendUp?: trendUp; 'value-box'?: valueBox; valueBox?: valueBox; values?: any; } } declare namespace ZC { let BUILDCODE: string[]; let LICENSE: string[]; let LICENSEKEY: string[]; let VERSION: string; } export default zingchart; export { zingchart, ZC };
the_stack
import { botId } from "./bot.ts"; import type { DiscordenoChannel } from "./structures/channel.ts"; import type { DiscordenoGuild } from "./structures/guild.ts"; import type { DiscordenoMember } from "./structures/member.ts"; import type { DiscordenoMessage } from "./structures/message.ts"; import type { PresenceUpdate } from "./types/activity/presence_update.ts"; import type { Emoji } from "./types/emojis/emoji.ts"; import { DiscordenoThread } from "./util/transformers/channel_to_thread.ts"; import { Collection } from "./util/collection.ts"; import { Channel } from "./types/channels/channel.ts"; import { Guild } from "./types/guilds/guild.ts"; import { GuildMember } from "./types/members/guild_member.ts"; import { Message } from "./types/messages/message.ts"; import { Role } from "./types/permissions/role.ts"; import { VoiceState } from "./types/voice/voice_state.ts"; import { User } from "./types/users/user.ts"; export const cache = { isReady: false, /** All of the guild objects the bot has access to, mapped by their Ids */ guilds: new Collection<bigint, DiscordenoGuild>([], { sweeper: { filter: guildSweeper, interval: 3600000 } }), /** All of the channel objects the bot has access to, mapped by their Ids. Sweep channels 1 minute after guilds are sweeped so dispatchedGuildIds is filled. */ channels: new Collection<bigint, DiscordenoChannel>([], { sweeper: { filter: channelSweeper, interval: 3660000 } }), /** All of the message objects the bot has cached since the bot acquired `READY` state, mapped by their Ids */ messages: new Collection<bigint, DiscordenoMessage>([], { sweeper: { filter: messageSweeper, interval: 300000 } }), /** All of the member objects that have been cached since the bot acquired `READY` state, mapped by their Ids */ members: new Collection<bigint, DiscordenoMember>([], { sweeper: { filter: memberSweeper, interval: 300000 } }), /** All of the unavailable guilds, mapped by their Ids (id, timestamp) */ unavailableGuilds: new Collection<bigint, number>(), /** All of the presence update objects received in PRESENCE_UPDATE gateway event, mapped by their user Id */ presences: new Collection<bigint, PresenceUpdate>([], { sweeper: { filter: () => true, interval: 300000 } }), fetchAllMembersProcessingRequests: new Collection< string, (value: Collection<bigint, DiscordenoMember> | PromiseLike<Collection<bigint, DiscordenoMember>>) => void >(), executedSlashCommands: new Set<string>(), get emojis() { return new Collection<bigint, Emoji>( this.guilds.reduce((a, b) => [...a, ...b.emojis.map((e, id) => [id, e])], [] as any[]) ); }, activeGuildIds: new Set<bigint>(), dispatchedGuildIds: new Set<bigint>(), dispatchedChannelIds: new Set<bigint>(), threads: new Collection<bigint, DiscordenoThread>(), /** ADVANCED USER ONLY: Please ask for help before modifying these. The properties that you want to use for your bot's structures. If you do not set any properties, all properties will be used by default. */ requiredStructureProperties: { /** Only these properties will be added to memory for your channels. */ channels: new Set<keyof Channel>(), /** Only these properties will be added to memory for your guilds. */ guilds: new Set<keyof Guild | "shardId" | "bitfield">(), /** Only these properties will be added to memory for your members. */ members: new Set<keyof GuildMember | keyof User | "guilds" | "bitfield" | "cachedAt">(), /** Only these properties will be added to memory for your messages. */ messages: new Set< | keyof Message | "isBot" | "tag" | "authorId" | "mentionedUserIds" | "mentionedRoleIds" | "mentionedChannelIds" | "bitfield" >(), /** Only these properties will be added to memory for your roles. */ roles: new Set<keyof Role | "botId" | "isNitroBoostRole" | "integrationId" | "bitfield">(), /** Only these properties will be added to memory for your voice states. */ voiceStates: new Set<keyof VoiceState | "bitfield">(), }, }; function messageSweeper(message: DiscordenoMessage) { // DM messages aren't needed if (!message.guildId) return true; // Only delete messages older than 10 minutes return Date.now() - message.timestamp > 600000; } function memberSweeper(member: DiscordenoMember) { // Don't sweep the bot else strange things will happen if (member.id === botId) return false; // Only sweep members who were not active the last 30 minutes return Date.now() - member.cachedAt > 1800000; } function guildSweeper(guild: DiscordenoGuild) { // Reset activity for next interval if (cache.activeGuildIds.delete(guild.id)) return false; // This is inactive guild. Not a single thing has happened for atleast 30 minutes. // Not a reaction, not a message, not any event! cache.dispatchedGuildIds.add(guild.id); return true; } function channelSweeper(channel: DiscordenoChannel, key: bigint) { // If this is in a guild and the guild was dispatched, then we can dispatch the channel if (channel.guildId && cache.dispatchedGuildIds.has(channel.guildId)) { cache.dispatchedChannelIds.add(channel.id); return true; } // THE KEY DM CHANNELS ARE STORED BY IS THE USER ID. If the user is not cached, we dont need to cache their dm channel. if (!channel.guildId && !cache.members.has(key)) return true; return false; } export let cacheHandlers = { /** Deletes all items from the cache */ async clear(table: TableName) { return cache[table].clear(); }, /** Deletes 1 item from cache using the key */ async delete(table: TableName, key: bigint) { return cache[table].delete(key); }, /** Check if something exists in cache with a key */ async has(table: TableName, key: bigint) { return cache[table].has(key); }, /** Get the number of key-value pairs */ async size(table: TableName) { return cache[table].size; }, // Done differently to have overloads /** Add a key value pair to the cache */ set, /** Get the value from the cache using its key */ get, /** Run a function on all items in this cache */ forEach, /** Allows you to filter our all items in this cache. */ filter, }; export type TableName = "guilds" | "unavailableGuilds" | "channels" | "messages" | "members" | "presences" | "threads"; async function set( table: "threads", key: bigint, value: DiscordenoThread ): Promise<Collection<bigint, DiscordenoThread>>; async function set(table: "guilds", key: bigint, value: DiscordenoGuild): Promise<Collection<bigint, DiscordenoGuild>>; async function set( table: "channels", key: bigint, value: DiscordenoChannel ): Promise<Collection<bigint, DiscordenoChannel>>; async function set( table: "messages", key: bigint, value: DiscordenoMessage ): Promise<Collection<bigint, DiscordenoMessage>>; async function set( table: "members", key: bigint, value: DiscordenoMember ): Promise<Collection<bigint, DiscordenoMember>>; async function set(table: "presences", key: bigint, value: PresenceUpdate): Promise<Collection<bigint, PresenceUpdate>>; async function set(table: "unavailableGuilds", key: bigint, value: number): Promise<Collection<bigint, number>>; async function set(table: TableName, key: bigint, value: any) { return cache[table].set(key, value); } async function get(table: "threads", key: bigint): Promise<DiscordenoThread | undefined>; async function get(table: "guilds", key: bigint): Promise<DiscordenoGuild | undefined>; async function get(table: "channels", key: bigint): Promise<DiscordenoChannel | undefined>; async function get(table: "messages", key: bigint): Promise<DiscordenoMessage | undefined>; async function get(table: "members", key: bigint): Promise<DiscordenoMember | undefined>; async function get(table: "presences", key: bigint): Promise<PresenceUpdate | undefined>; async function get(table: "unavailableGuilds", key: bigint): Promise<number | undefined>; async function get(table: TableName, key: bigint) { return cache[table].get(key); } // callback: (value: DiscordenoThread, key: bigint, map: Map<bigint, DiscordenoThread>) => void async function forEach(type: "DELETE_MESSAGES_FROM_CHANNEL", options: { channelId: bigint }): Promise<void>; async function forEach(type: "DELETE_MESSAGES_FROM_GUILD", options: { guildId: bigint }): Promise<void>; async function forEach(type: "DELETE_CHANNELS_FROM_GUILD", options: { guildId: bigint }): Promise<void>; async function forEach(type: "DELETE_GUILD_FROM_MEMBER", options: { guildId: bigint }): Promise<void>; async function forEach(type: "DELETE_ROLE_FROM_MEMBER", options: { guildId: bigint; roleId: bigint }): Promise<void>; async function forEach( type: | "DELETE_MESSAGES_FROM_CHANNEL" | "DELETE_MESSAGES_FROM_GUILD" | "DELETE_CHANNELS_FROM_GUILD" | "DELETE_GUILD_FROM_MEMBER" | "DELETE_ROLE_FROM_MEMBER", options?: Record<string, unknown> ) { if (type === "DELETE_MESSAGES_FROM_CHANNEL") { cache.messages.forEach((message) => { if (message.channelId === options?.channelId) cache.messages.delete(message.id); }); return; } if (type === "DELETE_MESSAGES_FROM_GUILD") { cache.messages.forEach((message) => { if (message.guildId === options?.guildId) cache.messages.delete(message.id); }); return; } if (type === "DELETE_CHANNELS_FROM_GUILD") { cache.channels.forEach((channel) => { if (channel.guildId === options?.guildId) cache.channels.delete(channel.id); }); return; } if (type === "DELETE_GUILD_FROM_MEMBER") { cache.members.forEach((member) => { if (!member.guilds.has(options?.guildId as bigint)) return; member.guilds.delete(options?.guildId as bigint); if (!member.guilds.size) { return cache.members.delete(member.id); } cache.members.set(member.id, member); }); return; } if (type === "DELETE_ROLE_FROM_MEMBER") { cache.members.forEach((member) => { // Not in the relevant guild so just skip if (!member.guilds.has(options?.guildId as bigint)) return; const guildMember = member.guilds.get(options?.guildId as bigint)!; guildMember.roles = guildMember.roles.filter((id) => id !== (options?.roleId as bigint)); cache.members.set(member.id, member); }); return; } } async function filter( type: "GET_MEMBERS_IN_GUILD", options: { guildId: bigint } ): Promise<Collection<bigint, DiscordenoMember>>; async function filter( type: "GET_MEMBERS_IN_GUILD", options?: Record<string, unknown> ): Promise<Collection<bigint, DiscordenoMember> | undefined> { if (type === "GET_MEMBERS_IN_GUILD") { return cache.members.filter((member) => member.guilds.has(options?.guildId as bigint)); } }
the_stack
import * as exec from '../src/exec' import * as im from '../src/interfaces' import * as childProcess from 'child_process' import * as fs from 'fs' import * as os from 'os' import * as path from 'path' import * as stream from 'stream' import * as io from '@actions/io' /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32' let outstream: stream.Writable let errstream: stream.Writable describe('@actions/exec', () => { beforeAll(() => { io.mkdirP(getTestTemp()) outstream = fs.createWriteStream(path.join(getTestTemp(), 'my.log')) errstream = fs.createWriteStream(path.join(getTestTemp(), 'myerr.log')) }) beforeEach(() => { outstream.write = jest.fn() errstream.write = jest.fn() }) it('Runs exec successfully with arguments split out', async () => { const _testExecOptions = getExecOptions() let exitCode = 1 let toolpath = '' if (IS_WINDOWS) { toolpath = await io.which('cmd', true) exitCode = await exec.exec( `"${toolpath}"`, ['/c', 'echo', 'hello'], _testExecOptions ) } else { toolpath = await io.which('ls', true) exitCode = await exec.exec( `"${toolpath}"`, ['-l', '-a'], _testExecOptions ) } expect(exitCode).toBe(0) if (IS_WINDOWS) { expect(outstream.write).toBeCalledWith( `[command]${toolpath} /c echo hello${os.EOL}` ) expect(outstream.write).toBeCalledWith(Buffer.from(`hello${os.EOL}`)) } else { expect(outstream.write).toBeCalledWith( `[command]${toolpath} -l -a${os.EOL}` ) } }) it('Runs exec successfully with arguments partially split out', async () => { const _testExecOptions = getExecOptions() let exitCode = 1 let toolpath = '' if (IS_WINDOWS) { toolpath = await io.which('cmd', true) exitCode = await exec.exec( `"${toolpath}" /c`, ['echo', 'hello'], _testExecOptions ) } else { toolpath = await io.which('ls', true) exitCode = await exec.exec(`"${toolpath}" -l`, ['-a'], _testExecOptions) } expect(exitCode).toBe(0) if (IS_WINDOWS) { expect(outstream.write).toBeCalledWith( `[command]${toolpath} /c echo hello${os.EOL}` ) expect(outstream.write).toBeCalledWith(Buffer.from(`hello${os.EOL}`)) } else { expect(outstream.write).toBeCalledWith( `[command]${toolpath} -l -a${os.EOL}` ) } }) it('Runs exec successfully with arguments as part of command line', async () => { const _testExecOptions = getExecOptions() let exitCode = 1 let toolpath = '' if (IS_WINDOWS) { toolpath = await io.which('cmd', true) exitCode = await exec.exec( `"${toolpath}" /c echo hello`, [], _testExecOptions ) } else { toolpath = await io.which('ls', true) exitCode = await exec.exec(`"${toolpath}" -l -a`, [], _testExecOptions) } expect(exitCode).toBe(0) if (IS_WINDOWS) { expect(outstream.write).toBeCalledWith( `[command]${toolpath} /c echo hello${os.EOL}` ) expect(outstream.write).toBeCalledWith(Buffer.from(`hello${os.EOL}`)) } else { expect(outstream.write).toBeCalledWith( `[command]${toolpath} -l -a${os.EOL}` ) } }) it('Runs exec successfully with command from PATH', async () => { const execOptions = getExecOptions() const outStream = new StringStream() execOptions.outStream = outStream let output = '' execOptions.listeners = { stdout: (data: Buffer) => { output += data.toString() } } let exitCode = 1 let tool: string let args: string[] if (IS_WINDOWS) { tool = 'cmd' args = ['/c', 'echo', 'hello'] } else { tool = 'sh' args = ['-c', 'echo hello'] } exitCode = await exec.exec(tool, args, execOptions) expect(exitCode).toBe(0) const rootedTool = await io.which(tool, true) expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]${rootedTool} ${args.join(' ')}` ) expect(output.trim()).toBe(`hello`) }) it('Exec fails with error on bad call', async () => { const _testExecOptions = getExecOptions() let toolpath = '' let args: string[] = [] if (IS_WINDOWS) { toolpath = await io.which('cmd', true) args = ['/c', 'non-existent'] } else { toolpath = await io.which('ls', true) args = ['-l', 'non-existent'] } let failed = false await exec.exec(`"${toolpath}"`, args, _testExecOptions).catch(err => { failed = true expect(err.message).toContain( `The process '${toolpath}' failed with exit code ` ) }) expect(failed).toBe(true) if (IS_WINDOWS) { expect(outstream.write).toBeCalledWith( `[command]${toolpath} /c non-existent${os.EOL}` ) } else { expect(outstream.write).toBeCalledWith( `[command]${toolpath} -l non-existent${os.EOL}` ) } }) it('Succeeds on stderr by default', async () => { const scriptPath: string = path.join( __dirname, 'scripts', 'stderroutput.js' ) const nodePath: string = await io.which('node', true) const _testExecOptions = getExecOptions() const exitCode = await exec.exec( `"${nodePath}"`, [scriptPath], _testExecOptions ) expect(exitCode).toBe(0) expect(outstream.write).toBeCalledWith( Buffer.from('this is output to stderr') ) }) it('Fails on stderr if specified', async () => { const scriptPath: string = path.join( __dirname, 'scripts', 'stderroutput.js' ) const nodePath: string = await io.which('node', true) const _testExecOptions = getExecOptions() _testExecOptions.failOnStdErr = true let failed = false await exec .exec(`"${nodePath}"`, [scriptPath], _testExecOptions) .catch(() => { failed = true }) expect(failed).toBe(true) expect(errstream.write).toBeCalledWith( Buffer.from('this is output to stderr') ) }) it('Fails when process fails to launch', async () => { const nodePath: string = await io.which('node', true) const _testExecOptions = getExecOptions() _testExecOptions.cwd = path.join(__dirname, 'nosuchdir') let failed = false await exec.exec(`"${nodePath}"`, [], _testExecOptions).catch(() => { failed = true }) expect(failed).toBe(true) }) it('Handles output callbacks', async () => { const stdErrPath: string = path.join( __dirname, 'scripts', 'stderroutput.js' ) const stdOutPath: string = path.join( __dirname, 'scripts', 'stdoutoutput.js' ) const nodePath: string = await io.which('node', true) let stdoutCalled = false let stderrCalled = false const _testExecOptions = getExecOptions() _testExecOptions.listeners = { stdout: (data: Buffer) => { expect(data).toEqual(Buffer.from('this is output to stdout')) stdoutCalled = true }, stderr: (data: Buffer) => { expect(data).toEqual(Buffer.from('this is output to stderr')) stderrCalled = true } } let exitCode = await exec.exec( `"${nodePath}"`, [stdOutPath], _testExecOptions ) expect(exitCode).toBe(0) exitCode = await exec.exec(`"${nodePath}"`, [stdErrPath], _testExecOptions) expect(exitCode).toBe(0) expect(stdoutCalled).toBeTruthy() expect(stderrCalled).toBeTruthy() }) it('Handles large stdline', async () => { const stdlinePath: string = path.join( __dirname, 'scripts', 'stdlineoutput.js' ) const nodePath: string = await io.which('node', true) const _testExecOptions = getExecOptions() let largeLine = '' _testExecOptions.listeners = { stdline: (line: string) => { largeLine = line } } const exitCode = await exec.exec( `"${nodePath}"`, [stdlinePath], _testExecOptions ) expect(exitCode).toBe(0) expect(Buffer.byteLength(largeLine)).toEqual(2 ** 16 + 1) }) it('Handles stdin shell', async () => { let command: string if (IS_WINDOWS) { command = 'wait-for-input.cmd' } else { command = 'wait-for-input.sh' } const waitForInput: string = path.join(__dirname, 'scripts', command) const _testExecOptions = getExecOptions() _testExecOptions.listeners = { stdout: (data: Buffer) => { expect(data).toEqual(Buffer.from(`this is my input${os.EOL}`)) } } _testExecOptions.input = Buffer.from('this is my input') const exitCode = await exec.exec(`"${waitForInput}"`, [], _testExecOptions) expect(exitCode).toBe(0) }) it('Handles stdin js', async () => { const waitForInput: string = path.join( __dirname, 'scripts', 'wait-for-input.js' ) const _testExecOptions = getExecOptions() _testExecOptions.listeners = { stdout: (data: Buffer) => { expect(data).toEqual(Buffer.from(`this is my input`)) } } _testExecOptions.input = Buffer.from('this is my input') const nodePath = await io.which('node', true) const exitCode = await exec.exec(nodePath, [waitForInput], _testExecOptions) expect(exitCode).toBe(0) }) it('Handles child process holding streams open', async function() { const semaphorePath = path.join( getTestTemp(), 'child-process-semaphore.txt' ) fs.writeFileSync(semaphorePath, '') const nodePath = await io.which('node', true) const scriptPath = path.join(__dirname, 'scripts', 'wait-for-file.js') const debugList: string[] = [] const _testExecOptions = getExecOptions() _testExecOptions.delay = 500 _testExecOptions.windowsVerbatimArguments = true _testExecOptions.listeners = { debug: (data: string) => { debugList.push(data) } } let exitCode: number if (IS_WINDOWS) { const toolName: string = await io.which('cmd.exe', true) const args = [ '/D', // Disable execution of AutoRun commands from registry. '/E:ON', // Enable command extensions. Note, command extensions are enabled by default, unless disabled via registry. '/V:OFF', // Disable delayed environment expansion. Note, delayed environment expansion is disabled by default, unless enabled via registry. '/S', // Will cause first and last quote after /C to be stripped. '/C', `"start "" /B "${nodePath}" "${scriptPath}" "file=${semaphorePath}""` ] exitCode = await exec.exec(`"${toolName}"`, args, _testExecOptions) } else { const toolName: string = await io.which('bash', true) const args = ['-c', `node '${scriptPath}' 'file=${semaphorePath}' &`] exitCode = await exec.exec(`"${toolName}"`, args, _testExecOptions) } expect(exitCode).toBe(0) expect( debugList.filter(x => x.includes('STDIO streams did not close')).length ).toBe(1) fs.unlinkSync(semaphorePath) }, 10000) // this was timing out on some slower hosted macOS runs at default 5s it('Handles child process holding streams open and non-zero exit code', async function() { const semaphorePath = path.join( getTestTemp(), 'child-process-semaphore.txt' ) fs.writeFileSync(semaphorePath, '') const nodePath = await io.which('node', true) const scriptPath = path.join(__dirname, 'scripts', 'wait-for-file.js') const debugList: string[] = [] const _testExecOptions = getExecOptions() _testExecOptions.delay = 500 _testExecOptions.windowsVerbatimArguments = true _testExecOptions.listeners = { debug: (data: string) => { debugList.push(data) } } let toolName: string let args: string[] if (IS_WINDOWS) { toolName = await io.which('cmd.exe', true) args = [ '/D', // Disable execution of AutoRun commands from registry. '/E:ON', // Enable command extensions. Note, command extensions are enabled by default, unless disabled via registry. '/V:OFF', // Disable delayed environment expansion. Note, delayed environment expansion is disabled by default, unless enabled via registry. '/S', // Will cause first and last quote after /C to be stripped. '/C', `"start "" /B "${nodePath}" "${scriptPath}" "file=${semaphorePath}"" & exit /b 123` ] } else { toolName = await io.which('bash', true) args = ['-c', `node '${scriptPath}' 'file=${semaphorePath}' & exit 123`] } await exec .exec(`"${toolName}"`, args, _testExecOptions) .then(() => { throw new Error('Should not have succeeded') }) .catch(err => { expect( err.message.indexOf('failed with exit code 123') ).toBeGreaterThanOrEqual(0) }) expect( debugList.filter(x => x.includes('STDIO streams did not close')).length ).toBe(1) fs.unlinkSync(semaphorePath) }, 10000) // this was timing out on some slower hosted macOS runs at default 5s it('Handles child process holding streams open and stderr', async function() { const semaphorePath = path.join( getTestTemp(), 'child-process-semaphore.txt' ) fs.writeFileSync(semaphorePath, '') const nodePath = await io.which('node', true) const scriptPath = path.join(__dirname, 'scripts', 'wait-for-file.js') const debugList: string[] = [] const _testExecOptions = getExecOptions() _testExecOptions.delay = 500 _testExecOptions.failOnStdErr = true _testExecOptions.windowsVerbatimArguments = true _testExecOptions.listeners = { debug: (data: string) => { debugList.push(data) } } let toolName: string let args: string[] if (IS_WINDOWS) { toolName = await io.which('cmd.exe', true) args = [ '/D', // Disable execution of AutoRun commands from registry. '/E:ON', // Enable command extensions. Note, command extensions are enabled by default, unless disabled via registry. '/V:OFF', // Disable delayed environment expansion. Note, delayed environment expansion is disabled by default, unless enabled via registry. '/S', // Will cause first and last quote after /C to be stripped. '/C', `"start "" /B "${nodePath}" "${scriptPath}" "file=${semaphorePath}"" & echo hi 1>&2` ] } else { toolName = await io.which('bash', true) args = [ '-c', `node '${scriptPath}' 'file=${semaphorePath}' & echo hi 1>&2` ] } await exec .exec(`"${toolName}"`, args, _testExecOptions) .then(() => { throw new Error('Should not have succeeded') }) .catch(err => { expect( err.message.indexOf( 'failed because one or more lines were written to the STDERR stream' ) ).toBeGreaterThanOrEqual(0) }) expect( debugList.filter(x => x.includes('STDIO streams did not close')).length ).toBe(1) fs.unlinkSync(semaphorePath) }) it('Exec roots relative tool path using unrooted options.cwd', async () => { let exitCode: number let command: string if (IS_WINDOWS) { command = './print-args-cmd' // let ToolRunner resolve the extension } else { command = './print-args-sh.sh' } const execOptions = getExecOptions() execOptions.cwd = 'scripts' const outStream = new StringStream() execOptions.outStream = outStream let output = '' execOptions.listeners = { stdout: (data: Buffer) => { output += data.toString() } } const originalCwd = process.cwd() try { process.chdir(__dirname) exitCode = await exec.exec(`${command} hello world`, [], execOptions) } catch (err) { process.chdir(originalCwd) throw err } expect(exitCode).toBe(0) const toolPath = path.resolve( __dirname, execOptions.cwd, `${command}${IS_WINDOWS ? '.cmd' : ''}` ) if (IS_WINDOWS) { expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]${process.env.ComSpec} /D /S /C "${toolPath} hello world"` ) } else { expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]${toolPath} hello world` ) } expect(output.trim()).toBe(`args[0]: "hello"${os.EOL}args[1]: "world"`) }) it('Exec roots throws friendly error when bad cwd is specified', async () => { const execOptions = getExecOptions() execOptions.cwd = 'nonexistent/path' await expect(exec.exec('ls', ['-all'], execOptions)).rejects.toThrowError( `The cwd: ${execOptions.cwd} does not exist!` ) }) it('Exec roots does not throw when valid cwd is provided', async () => { const execOptions = getExecOptions() execOptions.cwd = './' await expect(exec.exec('ls', ['-all'], execOptions)).resolves.toBe(0) }) it('Exec roots relative tool path using rooted options.cwd', async () => { let command: string if (IS_WINDOWS) { command = './print-args-cmd' // let ToolRunner resolve the extension } else { command = './print-args-sh.sh' } const execOptions = getExecOptions() execOptions.cwd = path.join(__dirname, 'scripts') const outStream = new StringStream() execOptions.outStream = outStream let output = '' execOptions.listeners = { stdout: (data: Buffer) => { output += data.toString() } } const exitCode = await exec.exec(`${command} hello world`, [], execOptions) expect(exitCode).toBe(0) const toolPath = path.resolve( __dirname, execOptions.cwd, `${command}${IS_WINDOWS ? '.cmd' : ''}` ) if (IS_WINDOWS) { expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]${process.env.ComSpec} /D /S /C "${toolPath} hello world"` ) } else { expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]${toolPath} hello world` ) } expect(output.trim()).toBe(`args[0]: "hello"${os.EOL}args[1]: "world"`) }) it('Exec roots relative tool path using process.cwd', async () => { let exitCode: number let command: string if (IS_WINDOWS) { command = 'scripts/print-args-cmd' // let ToolRunner resolve the extension } else { command = 'scripts/print-args-sh.sh' } const execOptions = getExecOptions() const outStream = new StringStream() execOptions.outStream = outStream let output = '' execOptions.listeners = { stdout: (data: Buffer) => { output += data.toString() } } const originalCwd = process.cwd() try { process.chdir(__dirname) exitCode = await exec.exec(`${command} hello world`, [], execOptions) } catch (err) { process.chdir(originalCwd) throw err } expect(exitCode).toBe(0) const toolPath = path.resolve( __dirname, `${command}${IS_WINDOWS ? '.cmd' : ''}` ) if (IS_WINDOWS) { expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]${process.env.ComSpec} /D /S /C "${toolPath} hello world"` ) } else { expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]${toolPath} hello world` ) } expect(output.trim()).toBe(`args[0]: "hello"${os.EOL}args[1]: "world"`) }) it('correctly outputs for getExecOutput', async () => { const stdErrPath: string = path.join( __dirname, 'scripts', 'stderroutput.js' ) const stdOutPath: string = path.join( __dirname, 'scripts', 'stdoutoutput.js' ) const nodePath: string = await io.which('node', true) const {exitCode: exitCodeOut, stdout} = await exec.getExecOutput( `"${nodePath}"`, [stdOutPath], getExecOptions() ) expect(exitCodeOut).toBe(0) expect(stdout).toBe('this is output to stdout') const {exitCode: exitCodeErr, stderr} = await exec.getExecOutput( `"${nodePath}"`, [stdErrPath], getExecOptions() ) expect(exitCodeErr).toBe(0) expect(stderr).toBe('this is output to stderr') }) it('correctly outputs for getExecOutput with additional listeners', async () => { const stdErrPath: string = path.join( __dirname, 'scripts', 'stderroutput.js' ) const stdOutPath: string = path.join( __dirname, 'scripts', 'stdoutoutput.js' ) const nodePath: string = await io.which('node', true) let listenerOut = '' const {exitCode: exitCodeOut, stdout} = await exec.getExecOutput( `"${nodePath}"`, [stdOutPath], { ...getExecOptions(), listeners: { stdout: data => { listenerOut = data.toString() } } } ) expect(exitCodeOut).toBe(0) expect(stdout).toBe('this is output to stdout') expect(listenerOut).toBe('this is output to stdout') let listenerErr = '' const {exitCode: exitCodeErr, stderr} = await exec.getExecOutput( `"${nodePath}"`, [stdErrPath], { ...getExecOptions(), listeners: { stderr: data => { listenerErr = data.toString() } } } ) expect(exitCodeErr).toBe(0) expect(stderr).toBe('this is output to stderr') expect(listenerErr).toBe('this is output to stderr') }) it('correctly outputs for getExecOutput when total size exceeds buffer size', async () => { const stdErrPath: string = path.join( __dirname, 'scripts', 'stderroutput.js' ) const stdOutPath: string = path.join( __dirname, 'scripts', 'stdoutoutputlarge.js' ) const nodePath: string = await io.which('node', true) let listenerOut = '' const {exitCode: exitCodeOut, stdout} = await exec.getExecOutput( `"${nodePath}"`, [stdOutPath], { ...getExecOptions(), listeners: { stdout: data => { listenerOut += data.toString() } } } ) expect(exitCodeOut).toBe(0) expect(Buffer.byteLength(stdout || '', 'utf8')).toBe(2 ** 25) expect(Buffer.byteLength(listenerOut, 'utf8')).toBe(2 ** 25) let listenerErr = '' const {exitCode: exitCodeErr, stderr} = await exec.getExecOutput( `"${nodePath}"`, [stdErrPath], { ...getExecOptions(), listeners: { stderr: data => { listenerErr = data.toString() } } } ) expect(exitCodeErr).toBe(0) expect(stderr).toBe('this is output to stderr') expect(listenerErr).toBe('this is output to stderr') }) it('correctly outputs for getExecOutput with multi-byte characters', async () => { const stdOutPath: string = path.join( __dirname, 'scripts', 'stdoutputspecial.js' ) const nodePath: string = await io.which('node', true) let numStdOutBufferCalls = 0 const {exitCode: exitCodeOut, stdout} = await exec.getExecOutput( `"${nodePath}"`, [stdOutPath], { ...getExecOptions(), listeners: { stdout: () => { numStdOutBufferCalls += 1 } } } ) expect(exitCodeOut).toBe(0) //one call for each half of the © character, ensuring it was actually split and not sent together expect(numStdOutBufferCalls).toBe(2) expect(stdout).toBe('©') }) if (IS_WINDOWS) { it('Exec roots relative tool path using process.cwd (Windows path separator)', async () => { let exitCode: number const command = 'scripts\\print-args-cmd' // let ToolRunner resolve the extension const execOptions = getExecOptions() const outStream = new StringStream() execOptions.outStream = outStream let output = '' execOptions.listeners = { stdout: (data: Buffer) => { output += data.toString() } } const originalCwd = process.cwd() try { process.chdir(__dirname) exitCode = await exec.exec(`${command} hello world`, [], execOptions) } catch (err) { process.chdir(originalCwd) throw err } expect(exitCode).toBe(0) const toolPath = path.resolve(__dirname, `${command}.cmd`) expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]${process.env.ComSpec} /D /S /C "${toolPath} hello world"` ) expect(output.trim()).toBe(`args[0]: "hello"${os.EOL}args[1]: "world"`) }) // Win specific quoting tests it('execs .exe with verbatim args (Windows)', async () => { const exePath = process.env.ComSpec const args: string[] = ['/c', 'echo', 'helloworld', 'hello:"world again"'] const outStream = new StringStream() let output = '' const options = { outStream: <stream.Writable>outStream, windowsVerbatimArguments: true, listeners: { stdout: (data: Buffer) => { output += data.toString() } } } const exitCode = await exec.exec(`"${exePath}"`, args, options) expect(exitCode).toBe(0) expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]"${exePath}" /c echo helloworld hello:"world again"` ) expect(output.trim()).toBe('helloworld hello:"world again"') }) it('execs .exe with arg quoting (Windows)', async () => { const exePath = process.env.ComSpec const args: string[] = [ '/c', 'echo', 'helloworld', 'hello world', 'hello:"world again"', 'hello,world' ] const outStream = new StringStream() let output = '' const options = { outStream: <stream.Writable>outStream, listeners: { stdout: (data: Buffer) => { output += data.toString() } } } const exitCode = await exec.exec(`"${exePath}"`, args, options) expect(exitCode).toBe(0) expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]${exePath} /c echo` + ` helloworld` + ` "hello world"` + ` "hello:\\"world again\\""` + ` hello,world` ) expect(output.trim()).toBe( 'helloworld' + ' "hello world"' + ' "hello:\\"world again\\""' + ' hello,world' ) }) it('execs .exe with a space and with verbatim args (Windows)', async () => { // this test validates the quoting that tool runner adds around the tool path // when using the windowsVerbatimArguments option. otherwise the target process // interprets the args as starting after the first space in the tool path. const exePath = compileArgsExe('print args exe with spaces.exe') const args: string[] = ['myarg1 myarg2'] const outStream = new StringStream() let output = '' const options = { outStream: <stream.Writable>outStream, windowsVerbatimArguments: true, listeners: { stdout: (data: Buffer) => { output += data.toString() } } } const exitCode = await exec.exec(`"${exePath}"`, args, options) expect(exitCode).toBe(0) expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]"${exePath}" myarg1 myarg2` ) expect(output.trim()).toBe("args[0]: 'myarg1'\r\nargs[1]: 'myarg2'") }, 20000) // slower windows runs timeout, so upping timeout to 20s (from default of 5s) it('execs .cmd with a space and with verbatim args (Windows)', async () => { // this test validates the quoting that tool runner adds around the script path. // otherwise cmd.exe will not be able to resolve the path to the script. const cmdPath = path.join( __dirname, 'scripts', 'print args cmd with spaces.cmd' ) const args: string[] = ['arg1 arg2', 'arg3'] const outStream = new StringStream() let output = '' const options = { outStream: <stream.Writable>outStream, windowsVerbatimArguments: true, listeners: { stdout: (data: Buffer) => { output += data.toString() } } } const exitCode = await exec.exec(`"${cmdPath}"`, args, options) expect(exitCode).toBe(0) expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]${process.env.ComSpec} /D /S /C ""${cmdPath}" arg1 arg2 arg3"` ) expect(output.trim()).toBe( 'args[0]: "arg1"\r\nargs[1]: "arg2"\r\nargs[2]: "arg3"' ) }) it('execs .cmd with a space and with arg with space (Windows)', async () => { // this test validates the command is wrapped in quotes (i.e. cmd.exe /S /C "<COMMAND>"). // otherwise the leading quote (around the script with space path) would be stripped // and cmd.exe would not be able to resolve the script path. const cmdPath = path.join( __dirname, 'scripts', 'print args cmd with spaces.cmd' ) const args: string[] = ['my arg 1', 'my arg 2'] const outStream = new StringStream() let output = '' const options = { outStream: <stream.Writable>outStream, listeners: { stdout: (data: Buffer) => { output += data.toString() } } } const exitCode = await exec.exec(`"${cmdPath}"`, args, options) expect(exitCode).toBe(0) expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]${process.env.ComSpec} /D /S /C ""${cmdPath}" "my arg 1" "my arg 2""` ) expect(output.trim()).toBe( 'args[0]: "<quote>my arg 1<quote>"\r\n' + 'args[1]: "<quote>my arg 2<quote>"' ) }) it('execs .cmd from path (Windows)', async () => { // this test validates whether a .cmd is resolved from the PATH when the extension is not specified const cmd = 'print-args-cmd' // note, not print-args-cmd.cmd const cmdPath = path.join(__dirname, 'scripts', `${cmd}.cmd`) const args: string[] = ['my arg 1', 'my arg 2'] const outStream = new StringStream() let output = '' const options = { outStream: <stream.Writable>outStream, listeners: { stdout: (data: Buffer) => { output += data.toString() } } } const originalPath = process.env['Path'] try { process.env['Path'] = `${originalPath};${path.dirname(cmdPath)}` const exitCode = await exec.exec(`${cmd}`, args, options) expect(exitCode).toBe(0) expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]${process.env.ComSpec} /D /S /C "${cmdPath} "my arg 1" "my arg 2""` ) expect(output.trim()).toBe( 'args[0]: "<quote>my arg 1<quote>"\r\n' + 'args[1]: "<quote>my arg 2<quote>"' ) } catch (err) { process.env['Path'] = originalPath throw err } }) it('execs .cmd with arg quoting (Windows)', async () => { // this test validates .cmd quoting rules are applied, not the default libuv rules const cmdPath = path.join( __dirname, 'scripts', 'print args cmd with spaces.cmd' ) const args: string[] = [ 'helloworld', 'hello world', 'hello\tworld', 'hello&world', 'hello(world', 'hello)world', 'hello[world', 'hello]world', 'hello{world', 'hello}world', 'hello^world', 'hello=world', 'hello;world', 'hello!world', "hello'world", 'hello+world', 'hello,world', 'hello`world', 'hello~world', 'hello|world', 'hello<world', 'hello>world', 'hello:"world again"', 'hello world\\' ] const outStream = new StringStream() let output = '' const options = { outStream: <stream.Writable>outStream, listeners: { stdout: (data: Buffer) => { output += data.toString() } } } const exitCode = await exec.exec(`"${cmdPath}"`, args, options) expect(exitCode).toBe(0) expect(outStream.getContents().split(os.EOL)[0]).toBe( `[command]${process.env.ComSpec} /D /S /C ""${cmdPath}"` + ` helloworld` + ` "hello world"` + ` "hello\tworld"` + ` "hello&world"` + ` "hello(world"` + ` "hello)world"` + ` "hello[world"` + ` "hello]world"` + ` "hello{world"` + ` "hello}world"` + ` "hello^world"` + ` "hello=world"` + ` "hello;world"` + ` "hello!world"` + ` "hello'world"` + ` "hello+world"` + ` "hello,world"` + ` "hello\`world"` + ` "hello~world"` + ` "hello|world"` + ` "hello<world"` + ` "hello>world"` + ` "hello:""world again"""` + ` "hello world\\\\"` + `"` ) expect(output.trim()).toBe( 'args[0]: "helloworld"\r\n' + 'args[1]: "<quote>hello world<quote>"\r\n' + 'args[2]: "<quote>hello\tworld<quote>"\r\n' + 'args[3]: "<quote>hello&world<quote>"\r\n' + 'args[4]: "<quote>hello(world<quote>"\r\n' + 'args[5]: "<quote>hello)world<quote>"\r\n' + 'args[6]: "<quote>hello[world<quote>"\r\n' + 'args[7]: "<quote>hello]world<quote>"\r\n' + 'args[8]: "<quote>hello{world<quote>"\r\n' + 'args[9]: "<quote>hello}world<quote>"\r\n' + 'args[10]: "<quote>hello^world<quote>"\r\n' + 'args[11]: "<quote>hello=world<quote>"\r\n' + 'args[12]: "<quote>hello;world<quote>"\r\n' + 'args[13]: "<quote>hello!world<quote>"\r\n' + 'args[14]: "<quote>hello\'world<quote>"\r\n' + 'args[15]: "<quote>hello+world<quote>"\r\n' + 'args[16]: "<quote>hello,world<quote>"\r\n' + 'args[17]: "<quote>hello`world<quote>"\r\n' + 'args[18]: "<quote>hello~world<quote>"\r\n' + 'args[19]: "<quote>hello|world<quote>"\r\n' + 'args[20]: "<quote>hello<world<quote>"\r\n' + 'args[21]: "<quote>hello>world<quote>"\r\n' + 'args[22]: "<quote>hello:<quote><quote>world again<quote><quote><quote>"\r\n' + 'args[23]: "<quote>hello world\\\\<quote>"' ) }) } }) function getTestTemp(): string { return path.join(__dirname, '_temp') } function getExecOptions(): im.ExecOptions { return { cwd: __dirname, env: {}, silent: false, failOnStdErr: false, ignoreReturnCode: false, outStream: outstream, errStream: errstream } } export class StringStream extends stream.Writable { constructor() { super() stream.Writable.call(this) } private contents = '' _write( data: string | Buffer | Uint8Array, encoding: string, next: Function ): void { this.contents += data next() } getContents(): string { return this.contents } } // function to compile a .NET program on Windows. const compileExe = (sourceFileName: string, targetFileName: string): string => { const directory = path.join(getTestTemp(), sourceFileName) io.mkdirP(directory) const exePath = path.join(directory, targetFileName) // short-circuit if already compiled try { fs.statSync(exePath) return exePath } catch (err) { if (err.code !== 'ENOENT') { throw err } } const sourceFile = path.join(__dirname, 'scripts', sourceFileName) const cscPath = 'C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\csc.exe' fs.statSync(cscPath) childProcess.execFileSync(cscPath, [ '/target:exe', `/out:${exePath}`, sourceFile ]) return exePath } // function to compile a .NET program that prints the command line args. // the helper program is used to validate that command line args are passed correctly. const compileArgsExe = (targetFileName: string): string => { return compileExe('print-args-exe.cs', targetFileName) }
the_stack
import * as BpmnModdle from 'bpmn-moddle'; import * as fs from 'fs'; import * as path from 'path'; import * as ejs from 'ejs'; import * as BigNumber from 'bignumber.js'; import { ControlFlowInfo, ModelInfo, ParameterInfo, OracleInfo } from './definitions'; const bpmn2solEJS = fs.readFileSync(path.join(__dirname, '../../templates') + '/bpmn2sol.ejs', 'utf-8'); let bpmn2solTemplate = ejs.compile(bpmn2solEJS); const workList2solEJS = fs.readFileSync(path.join(__dirname, '../../templates') + '/workList2sol.ejs', 'utf-8'); let workList2solTemplate = ejs.compile(workList2solEJS); let moddle = new BpmnModdle(); let parseBpmn = (bpmnDoc) => { return new Promise((resolve, reject) => { moddle.fromXML(bpmnDoc, (err, definitions) => { if (!err) resolve(definitions); else reject(err); }); }); }; let is = (element, type) => element.$instanceOf(type); let collectControlFlowInfo = (proc: any, globalNodeMap: Map<string, any>, globalControlFlowInfo: Array<ControlFlowInfo>): ControlFlowInfo => { let nodeList: Array<string> = new Array(); let edgeList: Array<string> = new Array(); let boundaryEvents: Array<string> = new Array(); let nonBlockingBoundaryEvents: Array<string> = new Array(); let controlFlowInfo: ControlFlowInfo; for (let node of proc.flowElements.filter((e) => is(e, "bpmn:FlowNode"))) { if (is(node, "bpmn:BoundaryEvent")) { boundaryEvents.push(node.id); if (node.cancelActivity == false) nonBlockingBoundaryEvents.push(node.id); } else { nodeList.push(node.id); } globalNodeMap.set(node.id, node); } var sources = [...nodeList]; for (let flowEdge of proc.flowElements.filter((e) => is(e, "bpmn:SequenceFlow"))) { if (sources.indexOf(flowEdge.targetRef.id) > -1) { sources.splice(sources.indexOf(flowEdge.targetRef.id), 1); } edgeList.push(flowEdge.id); } // Let us remove all source elements from the node list nodeList = nodeList.filter((node: string) => sources.indexOf(node) < 0); if (nonBlockingBoundaryEvents.length > 0) { let dfs = (sources: string[]) => { let open = [...sources]; let nodeList: Array<string> = new Array(); let edgeList: Array<string> = new Array(); while (open.length > 0) { let currId = open.pop(); let curr = globalNodeMap.get(currId); nodeList.push(currId); if (curr.outgoing && curr.outgoing.length > 0) for (let succEdge of curr.outgoing) { let succ = succEdge.targetRef; edgeList.push(succEdge.id); if (open.indexOf(succ.id) < 0 && nodeList.indexOf(succ.id) < 0) open.push(succ.id); } } return [nodeList, edgeList]; } let [mainPathNodeList, mainPathEdgeList] = dfs(sources); var localBoundary = []; boundaryEvents.forEach(evtId => { if (nonBlockingBoundaryEvents.indexOf(evtId) < 0) localBoundary.push(evtId); }) if (localBoundary.length > 0) { let [boundaryNodePath, boundaryEdgePath] = dfs(localBoundary); boundaryNodePath = boundaryNodePath.filter((node: string) => localBoundary.indexOf(node) < 0); mainPathNodeList = mainPathNodeList.concat(boundaryNodePath); mainPathEdgeList = mainPathEdgeList.concat(boundaryEdgePath); } // Let us remove all source elements from the node list mainPathNodeList = mainPathNodeList.filter((node: string) => sources.indexOf(node) < 0); controlFlowInfo = new ControlFlowInfo(proc, mainPathNodeList, mainPathEdgeList, sources, boundaryEvents); globalControlFlowInfo.push(controlFlowInfo); for (let eventId of nonBlockingBoundaryEvents) { let event = globalNodeMap.get(eventId); if (!mainPathNodeList.find((e: string) => event.attachedToRef.id === e)) { throw new Error('ERROR: Found non-interrupting event which is not attached to a subprocess in the main process path'); } let [localNodeList, localEdgeList] = dfs([eventId]); if (mainPathNodeList.filter((nodeId: string) => localNodeList.indexOf(nodeId) >= 0).length > 0) throw new Error('ERROR: Non-interrupting event outgoing path is not synchronized and merges with main process path'); // Let us remove all source elements from the node list localNodeList = localNodeList.filter((node: string) => sources.indexOf(node) < 0); let childControlFlowInfo = new ControlFlowInfo(event, localNodeList, localEdgeList, [eventId], []); childControlFlowInfo.parent = proc; globalControlFlowInfo.push(childControlFlowInfo); } } else { controlFlowInfo = new ControlFlowInfo(proc, nodeList, edgeList, sources, boundaryEvents); globalControlFlowInfo.push(controlFlowInfo); } for (let subprocess of proc.flowElements.filter((e) => is(e, "bpmn:SubProcess"))) { let subprocessControlFlowInfo = collectControlFlowInfo(subprocess, globalNodeMap, globalControlFlowInfo); subprocessControlFlowInfo.parent = proc; if (!(subprocess.loopCharacteristics && subprocess.loopCharacteristics.$type === 'bpmn:MultiInstanceLoopCharacteristics')) { // Subprocess is embedded ... then copy all nodes and edges to the parent process subprocessControlFlowInfo.isEmbedded = true; controlFlowInfo.nodeList = controlFlowInfo.nodeList.concat(subprocessControlFlowInfo.nodeList); controlFlowInfo.edgeList = controlFlowInfo.edgeList.concat(subprocessControlFlowInfo.edgeList); } } if (proc.documentation) { controlFlowInfo.globalParameters = proc.documentation[0].text; } return controlFlowInfo; }; let extractParameters = (cad, nodeId, controlFlowInfo) => { // Extracting Information of Oracle from Service Tasks (if aplicable) var oracle_Data = ''; for (let j = 0, first = false; j < cad.length; j++) { if (cad.charAt(j) === '(') { if (!first) first = true; else { cad = cad.substr(j); break; } } if (cad.charAt(j) === ':') { oracle_Data = ''; break; } oracle_Data += cad.charAt(j); } // Processing Information of function parameters (both service and user tasks) cad = cad.replace("(", " ").replace(")", " ").trim(); cad = cad.replace("(", " ").replace(")", " ").trim(); var firstSplit = cad.split(":"); var secondSplit = firstSplit[firstSplit.length - 1].trim().split("->"); var resMap: Map<string, Array<string>> = new Map(); var inputOutput = [firstSplit[0].trim(), secondSplit[0].trim()]; var parameterType = ['input', 'output']; var bodyString = secondSplit[secondSplit.length - 1].trim(); resMap.set('body', [secondSplit[secondSplit.length - 1].trim()]); for (let i = 0; i < inputOutput.length; i++) { var temp = inputOutput[i].split(","); var res = []; temp.forEach(subCad => { var aux = subCad.trim().split(" "); if (aux[0].trim().length > 0) { res.push(aux[0].trim()); res.push(aux[aux.length - 1].trim()); } }) resMap.set(parameterType[i], res); } // Updating Information of Oracle in controlFlowInfo if (controlFlowInfo != null) { let parameters: Array<ParameterInfo> = new Array(); var toIterate = resMap.get('input'); for (let i = 0; i < toIterate.length; i += 2) parameters.push(new ParameterInfo(toIterate[i], toIterate[i + 1])); if (oracle_Data.length > 0) { oracle_Data = oracle_Data = oracle_Data.trim().replace(" ", "_"); oracle_Data = oracle_Data.replace("(", " ").replace(").", " ").trim(); var splitResult = oracle_Data.split(" "); if (!controlFlowInfo.oracleInfo.has(splitResult[0])) { controlFlowInfo.oracleInfo.set(splitResult[0], new OracleInfo(splitResult[0])); } controlFlowInfo.oracleTaskMap.set(nodeId, splitResult[0]); var localOracle = controlFlowInfo.oracleInfo.get(splitResult[0]); localOracle.address = splitResult[1]; localOracle.functionName = splitResult[2]; localOracle.functionParameters = parameters; } else controlFlowInfo.localParameters.set(nodeId, parameters); } return resMap; }; let getNodeName = (node: any) => node.name ? node.name.replace(/\s+/g, '_') : node.id; export let parseModel = (modelInfo: ModelInfo) => new Promise((resolve, reject) => { parseBpmn(modelInfo.bpmn).then((definitions: any) => { modelInfo.solidity = 'pragma solidity ^0.4.14;\n'; modelInfo.controlFlowInfoMap = new Map(); // Sanity checks if (!definitions.diagrams || definitions.diagrams.length == 0) throw new Error('ERROR: No diagram found in BPMN file'); let proc = definitions.diagrams[0].plane.bpmnElement; if (proc.$type !== 'bpmn:Process') throw new Error('ERROR: No root process model found'); // BPMN to Solidity parsing let globalNodeMap: Map<string, any> = new Map(), globalNodeIndexMap: Map<string, number> = new Map(), globalEdgeIndexMap: Map<string, number> = new Map(), globalControlFlowInfo: Array<ControlFlowInfo> = new Array(); globalNodeMap.set(proc.id, proc); let mainControlFlowInfo = collectControlFlowInfo(proc, globalNodeMap, globalControlFlowInfo); let globalControlFlowInfoMap: Map<string, ControlFlowInfo> = new Map(); globalControlFlowInfo.forEach(controlFlowInfo => globalControlFlowInfoMap.set(controlFlowInfo.self.id, controlFlowInfo)); // Event sub-processes appear in the source list, and not in the nodeList // In addition, all the elements of a non interrupting subprocess event appears embedded on its parent process for (let controlFlowInfo of globalControlFlowInfo) { var indexesToRemove = []; controlFlowInfo.sources.forEach(nodeId => { if (globalNodeMap.get(nodeId).triggeredByEvent) { controlFlowInfo.nodeList.push(nodeId); indexesToRemove.push(controlFlowInfo.sources.indexOf(nodeId)); var nodeInfo = globalControlFlowInfoMap.get(nodeId); if (!globalNodeMap.get(nodeInfo.sources[0]).isInterrupting) nodeInfo.nodeList.forEach(childId => { var index = controlFlowInfo.nodeList.indexOf(childId); if (index >= 0) controlFlowInfo.nodeList.splice(index, 1); }) } }) indexesToRemove.sort((ind1, ind2) => { return ind2 - ind1; }); indexesToRemove.forEach(index => { controlFlowInfo.sources.splice(index, 1); }) if (is(globalNodeMap.get(controlFlowInfo.self.id), "bpmn:SubProcess") && controlFlowInfo.self.triggeredByEvent && globalNodeMap.get(controlFlowInfo.sources[0]).isInterrupting == false) { controlFlowInfo.isEmbedded = false; } } let hasExternalCall = (nodeId) => { var node = globalNodeMap.get(nodeId); return is(node, 'bpmn:UserTask') || is(node, 'bpmn:ServiceTask') || is(node, 'bpmn:ReceiveTask') || (node.eventDefinitions && is(node.eventDefinitions[0], "bpmn:MessageEventDefinition") && !is(node, 'bpmn:IntermediateThrowEvent') && !is(node, 'bpmn:EndEvent')); } for (let controlFlowInfo of globalControlFlowInfo) { controlFlowInfo.activeMessages = []; if (!controlFlowInfo.isEmbedded) { var multiinstanceActivities = [], callActivities = [], nonInterruptingEvents = [], catchingMessages = []; controlFlowInfo.nodeList.map(nodeId => globalNodeMap.get(nodeId)) .forEach(e => { if (((is(e, "bpmn:Task") || is(e, "bpmn:SubProcess")) && e.loopCharacteristics && e.loopCharacteristics.$type === 'bpmn:MultiInstanceLoopCharacteristics')) { controlFlowInfo.multiinstanceActivities.set(e.id, modelInfo.name + ':' + getNodeName(e) + '_Contract'); multiinstanceActivities.push(e.id); if (is(e, "bpmn:SubProcess")) controlFlowInfo.childSubprocesses.set(e.id, modelInfo.name + ':' + getNodeName(e) + '_Contract'); } else if (is(e, "bpmn:CallActivity")) { controlFlowInfo.callActivities.set(e.id, getNodeName(e)); callActivities.push(e.id); } else if (is(e, 'bpmn:IntermediateCatchEvent') && is(e.eventDefinitions[0], "bpmn:MessageEventDefinition")) catchingMessages.push(e.id); else if (is(e, 'bpmn:StartEvent') && is(e.eventDefinitions[0], "bpmn:MessageEventDefinition")) catchingMessages.push(e.id); }); // It is also necessary to add boundary events of embedded sub-processes controlFlowInfo.sources.forEach(nodeId => { var start = globalNodeMap.get(nodeId); if (start.eventDefinitions && start.eventDefinitions[0] && is(start.eventDefinitions[0], "bpmn:MessageEventDefinition") && controlFlowInfo.nodeList.indexOf(nodeId) < 0) { controlFlowInfo.nodeList.push(nodeId); if (catchingMessages.indexOf(nodeId) < 0) catchingMessages.push(nodeId); } }) controlFlowInfo.boundaryEvents.forEach(nodeId => { let node = globalNodeMap.get(nodeId); if (node.outgoing) for (let outgoing of node.outgoing) controlFlowInfo.edgeList.push(outgoing.id); if (!node.cancelActivity) { controlFlowInfo.nonInterruptingEvents.set(node.id, modelInfo.name + ':' + getNodeName(node) + '_Contract'); nonInterruptingEvents.push(node.id); controlFlowInfo.nodeList.push(nodeId); // Eager reinsertion if (node.eventDefinitions[0] && is(node.eventDefinitions[0], "bpmn:MessageEventDefinition")) { if (controlFlowInfo.activeMessages.indexOf(nodeId) < 0) controlFlowInfo.activeMessages.push(nodeId); if (catchingMessages.indexOf(nodeId) < 0) catchingMessages.push(nodeId); } } else if (node.eventDefinitions && is(node.eventDefinitions[0], "bpmn:MessageEventDefinition")) { if (controlFlowInfo.nodeList.indexOf(nodeId) < 0) controlFlowInfo.nodeList.push(nodeId); if (catchingMessages.indexOf(nodeId) < 0) catchingMessages.push(nodeId); } }); globalNodeMap.forEach(node => { if (is(node, 'bpmn:SubProcess') && node.triggeredByEvent && controlFlowInfo.self.id === node.$parent.id) { for (let start of node.flowElements.filter((e) => is(e, "bpmn:FlowNode") && is(e, "bpmn:StartEvent"))) { if (start.isInterrupting == false) { var parent = globalNodeMap.get(start.$parent.id); controlFlowInfo.nonInterruptingEvents.set(start.id, modelInfo.name + ':' + getNodeName(parent) + '_Contract'); nonInterruptingEvents.push(start.id); controlFlowInfo.nodeList.push(start.id); if (start.eventDefinitions[0] && is(start.eventDefinitions[0], "bpmn:MessageEventDefinition")) { if (controlFlowInfo.activeMessages.indexOf(start.id) < 0) controlFlowInfo.activeMessages.push(start.id); if (catchingMessages.indexOf(start.id) < 0) catchingMessages.push(start.id); } } if (start.eventDefinitions[0] && is(start.eventDefinitions[0], "bpmn:MessageEventDefinition")) { if (controlFlowInfo.nodeList.indexOf(start.id) < 0) controlFlowInfo.nodeList.push(start.id); if (catchingMessages.indexOf(start.id) < 0) catchingMessages.push(start.id); } if (start.outgoing) for (let outgoing of start.outgoing) controlFlowInfo.edgeList.push(outgoing.id); } } }); let firstInd = 0, lastInd = controlFlowInfo.nodeList.length - 1; let part1: Array<string> = new Array(); let part2: Array<string> = new Array(); controlFlowInfo.nodeList.forEach(nodeId => { if(hasExternalCall(nodeId)) part1.push(nodeId); else part2.push(nodeId) }) controlFlowInfo.nodeList = part1.concat(part2); controlFlowInfo.nodeList.forEach((nodeId: string, index: number, array: string[]) => { var node = globalNodeMap.get(nodeId); controlFlowInfo.nodeIndexMap.set(nodeId, index); globalNodeIndexMap.set(nodeId, index); controlFlowInfo.nodeNameMap.set(nodeId, getNodeName(globalNodeMap.get(nodeId))); if ((node.documentation && node.documentation[0].text && node.documentation[0].text.length > 0)) extractParameters(node.documentation[0].text, node.id, controlFlowInfo); }); controlFlowInfo.edgeList.forEach((edgeId: string, index: number, array: string[]) => { controlFlowInfo.edgeIndexMap.set(edgeId, index + 1); globalEdgeIndexMap.set(edgeId, index + 1); }); let codeGenerationInfo = { nodeList: controlFlowInfo.nodeList, nodeMap: globalNodeMap, activeMessages: controlFlowInfo.activeMessages, multiinstanceActivities: multiinstanceActivities, callActivities: callActivities, nonInterruptingEvents: nonInterruptingEvents, oracleInfo: controlFlowInfo.oracleInfo, oracleTaskMap: controlFlowInfo.oracleTaskMap, catchingMessages: catchingMessages, processId: () => controlFlowInfo.self.id, nodeName: (nodeId) => getNodeName(globalNodeMap.get(nodeId)), eventType: (nodeId) => { let node = globalNodeMap.get(nodeId); if (node.eventDefinitions && node.eventDefinitions[0]) { var cad = node.eventDefinitions[0].$type; return cad.substring(5, cad.length - 15); } return 'Default'; }, allEventTypes: () => { let taken = []; globalNodeMap.forEach(node => { if (node.eventDefinitions && node.eventDefinitions[0] && !is(node.eventDefinitions[0], 'bpmn:TerminateEventDefinition') && !is(node.eventDefinitions[0], 'bpmn:MessageEventDefinition')) { var cad = node.eventDefinitions[0].$type; if (taken.indexOf(cad.substring(5, cad.length - 15)) < 0) taken.push(cad.substring(5, cad.length - 15)); } }) return taken; }, getMessages: () => { let taken = []; var candidates = controlFlowInfo.boundaryEvents; controlFlowInfo.nodeList.forEach(nodeId => { if (is(globalNodeMap.get(nodeId), "bpmn:SubProcess")) { var subP = globalControlFlowInfoMap.get(nodeId); candidates = candidates.concat(subP.boundaryEvents); subP.sources.forEach(id => { if (!is(globalNodeMap.get(id), "bpmn:Subprocess") && candidates.indexOf(id) < 0) candidates.push(id); }) } }) candidates.forEach(evtId => { var evt = globalNodeMap.get(evtId); if (evt.eventDefinitions && evt.eventDefinitions[0] && is(evt.eventDefinitions[0], 'bpmn:MessageEventDefinition')) taken.push(evt); }) return taken; }, getThrowingMessages: () => { var res = []; controlFlowInfo.nodeList.forEach(nodeId => { var node = globalNodeMap.get(nodeId); if ((is(node, "bpmn:EndEvent") || is(node, "bpmn:IntermediateThrowEvent")) && node.eventDefinitions && node.eventDefinitions[0] && is(node.eventDefinitions[0], 'bpmn:MessageEventDefinition')) res.push(nodeId); }) return res; }, getThrowingEvents: (subprocId, evType) => { let res = []; globalNodeMap.forEach(node => { if (node.eventDefinitions && node.eventDefinitions[0]) { var cad = node.eventDefinitions[0].$type; if (cad.substring(5, cad.length - 15) === evType) { if ((is(node, 'bpmn:EndEvent') || is(node, "bpmn:IntermediateThrowEvent")) && (node.$parent.id === subprocId || controlFlowInfo.nodeList.indexOf(node.id) >= 0)) { res.push(node.id); } } } }) return res; }, getCatchingEvents: (subprocId, evType) => { let res = []; globalNodeMap.forEach(node => { if (node.eventDefinitions && node.eventDefinitions[0]) { var cad = node.eventDefinitions[0].$type; if (cad.substring(5, cad.length - 15) === evType) { if (is(node, 'bpmn:StartEvent')) { var parent = globalNodeMap.get(node.$parent.id); if (parent.triggeredByEvent && parent.$parent.id === subprocId) res.unshift(node.id); else if (!parent.triggeredByEvent && parent.id === subprocId) res.push(node.id); } else if (is(node, 'bpmn:BoundaryEvent') || is(node, 'bpmn:IntermediateCatchEvent')) { if (node.$parent.id === subprocId) res.push(node.id); } } } }) return res; }, getContracts2Call: () => { var res = callActivities.concat(multiinstanceActivities); nonInterruptingEvents.forEach(evtId => { var node = globalNodeMap.get(evtId); res.push(is(node, "bpmn:StartEvent") ? node.$parent.id : evtId); }) return res; }, getCountExternalTasks: () => { var res = 0; controlFlowInfo.nodeList.forEach(nodeId => { if(hasExternalCall(nodeId)) res++; }) return res; }, getStartedMessages: (processId) => { var res = []; controlFlowInfo.nodeList.forEach(nodeId => { var node = globalNodeMap.get(nodeId); if (is(node, 'bpmn:StartEvent') && node.$parent.id === processId && node.eventDefinitions && is(node.eventDefinitions[0], 'bpmn:MessageEventDefinition') && globalNodeMap.get(node.$parent.id).triggeredByEvent) res.push(nodeId); }) return res; }, getParent: (nodeId) => { // Retrieves the id of the parent var node = globalNodeMap.get(nodeId); if (is(node, "bpmn:StartEvent") && node.$parent && globalNodeMap.get(node.$parent.id).triggeredByEvent) return globalNodeMap.get(node.$parent.id).$parent.id; if (is(node, "bpmn:BoundaryEvent") && node.cancelActivity) return node.attachedToRef.id; return node.$parent ? node.$parent.id : nodeId; }, getContractName: (nodeId) => { // Retrieves the contract name related to the node. var node = globalNodeMap.get(nodeId); if (is(node, "bpmn:StartEvent") && node.$parent && globalNodeMap.get(node.$parent.id).triggeredByEvent) return node.$parent.id; if (is(node, "bpmn:BoundaryEvent")) return node.id; return controlFlowInfo.self.id; }, getAllChildren: (subprocId, direct) => { let taken = direct ? [] : [subprocId]; controlFlowInfo.nodeList.map(nodeId => globalNodeMap.get(nodeId)) .forEach(e => { if (is(e, "bpmn:SubProcess") || callActivities.indexOf(e.id) >= 0 || (nonInterruptingEvents.indexOf(e.id) >= 0 && !is(e, "bpmn:StartEvent"))) if (((direct && subprocId !== e.id && e.$parent.id === subprocId) || !direct) && taken.indexOf(e.id) < 0) taken.push(e.id); }); return taken; }, isStartingContractEvent: (eventId, processId) => { var evt = globalNodeMap.get(eventId); if (is(evt, "bpmn:StartEvent")) { if (globalNodeMap.get(evt.$parent.id).triggeredByEvent) return evt.$parent.id !== processId; if (is(evt.eventDefinitions[0], 'bpmn:MessageEventDefinition')) return true; } else if (is(evt, "bpmn:BoundaryEvent")) { return eventId !== processId; } else if (is(evt, 'bpmn:IntermediateCatchEvent') && is(evt.eventDefinitions[0], 'bpmn:MessageEventDefinition')) return true; return false; }, isInterrupting: (eventId) => { // True if an event is interrupting var node = globalNodeMap.get(eventId); if (is(node, "bpmn:StartEvent") && node.$parent && globalNodeMap.get(node.$parent.id).triggeredByEvent) return node.isInterrupting != false; if (is(node, "bpmn:BoundaryEvent")) return node.cancelActivity != false; return false; }, isEmbeddedSubprocess: (subprocessId) => { return globalControlFlowInfoMap.get(subprocessId).isEmbedded; }, isBoundaryEvent: (evtId) => { return controlFlowInfo.boundaryEvents.indexOf(evtId) >= 0; }, preMarking: (nodeId) => { let node = globalNodeMap.get(nodeId); var bitarray = []; if (node.incoming) for (let incoming of node.incoming) bitarray[controlFlowInfo.edgeIndexMap.get(incoming.id)] = 1; else bitarray[0] = 1; var result = '0b'; for (let i = bitarray.length - 1; i >= 0; i--) result += bitarray[i] ? '1' : '0'; return new BigNumber(result).toFixed(); }, postMarking: (nodeId) => { let node = globalNodeMap.get(nodeId); var bitarray = []; var result = '0b'; if (node.outgoing) for (let outgoing of node.outgoing) { bitarray[controlFlowInfo.edgeIndexMap.get(outgoing.id)] = 1; } else result = '0'; for (let i = bitarray.length - 1; i >= 0; i--) result += bitarray[i] ? '1' : '0'; return new BigNumber(result).toFixed(); }, subprocessNodeMarking: (subprocessId) => { var bitarray = []; globalNodeMap.forEach(node => { if (node.$parent && node.$parent.id === subprocessId) { if (is(node, 'bpmn:Task')) bitarray[globalNodeIndexMap.get(node.id)] = 1; else if (!globalNodeMap.get(subprocessId).triggeredByEvent && node.eventDefinitions && node.eventDefinitions[0] && is(node.eventDefinitions[0], 'bpmn:MessageEventDefinition')) bitarray[globalNodeIndexMap.get(node.id)] = 1; } }) var result = bitarray.length > 0 ? '0b' : 0; for (let i = bitarray.length - 1; i >= 0; i--) result += bitarray[i] ? '1' : '0'; return new BigNumber(result).toFixed(); }, subprocessStartMarking: (subprocessId) => { var toSearch = globalNodeMap.get(subprocessId); var bitarray = []; var result = '0b'; if (is(toSearch, 'bpmn:BoundaryEvent')) { for (let outgoing of toSearch.outgoing) bitarray[controlFlowInfo.edgeIndexMap.get(outgoing.id)] = 1; } else { for (let node of toSearch.flowElements.filter((e) => is(e, "bpmn:FlowNode") && is(e, "bpmn:StartEvent"))) { if (node.$parent.id === subprocessId) if (!globalNodeMap.get(node.$parent.id).triggeredByEvent && node.eventDefinitions && node.eventDefinitions[0] && is(node.eventDefinitions[0], 'bpmn:MessageEventDefinition')) bitarray[0] = 1; else if (node.outgoing) for (let outgoing of node.outgoing) bitarray[controlFlowInfo.edgeIndexMap.get(outgoing.id)] = 1; } } for (let i = bitarray.length - 1; i >= 0; i--) result += bitarray[i] ? '1' : '0'; return new BigNumber(result).toFixed(); }, subprocessMarking: (subprocessId) => { var bitarray = []; var result = '0b'; var localInfo = globalControlFlowInfoMap.get(subprocessId); if (is(globalNodeMap.get(controlFlowInfo.self.id), "bpmn:BoundaryEvent") && multiinstanceActivities.indexOf(subprocessId) < 0) { var parentInfo = globalControlFlowInfoMap.get(controlFlowInfo.self.$parent.id); localInfo.edgeList.forEach(edgeId => { bitarray[parentInfo.edgeIndexMap.get(edgeId)] = 1; }) } else { localInfo.edgeList.forEach(edgeId => { bitarray[controlFlowInfo.edgeIndexMap.get(edgeId)] = 1; }) } for (let i = bitarray.length - 1; i >= 0; i--) result += bitarray[i] ? '1' : '0'; return new BigNumber(result).toFixed(); }, extendedSubprocessMarking: (subprocessId, orCondition) => { var candidates = callActivities.concat(multiinstanceActivities.concat(nonInterruptingEvents)); var res = orCondition ? "|| (" : "\u0026" + "\u0026" + "("; candidates.forEach(nodeId => { var node = globalNodeMap.get(nodeId); if (node.$parent.id === subprocessId) { res += getNodeName(node) + "_activeInstances != 0 || "; } }) return res.length < 10 ? '' : res.substring(0, res.length - 4) + ")"; }, flowEdgeIndex: (flowEdgeId) => { var bitarray = []; bitarray[controlFlowInfo.edgeIndexMap.get(flowEdgeId)] = 1; var result = '0b'; for (let i = bitarray.length - 1; i >= 0; i--) result += bitarray[i] ? '1' : '0'; return new BigNumber(result).toFixed(); }, flowNodeIndex: (flowNodeId) => { var bitarray = []; bitarray[globalNodeIndexMap.get(flowNodeId)] = 1; var result = '0b'; for (let i = bitarray.length - 1; i >= 0; i--) result += bitarray[i] ? '1' : '0'; return new BigNumber(result).toFixed(); }, nodeRealIndex: (nodeId) => { return globalNodeIndexMap.get(nodeId); }, isPartOfDeferredChoice: (eventId) => { let event = globalNodeMap.get(eventId); if (event.incoming) { let node = event.incoming[0].sourceRef; return is(node, 'bpmn:EventBasedGateway'); } return false; }, getDeferredChoiceElements: (nodeId) => { let event = globalNodeMap.get(nodeId); let res = []; if (event.incoming) { let node = event.incoming[0].sourceRef; if (is(node, 'bpmn:EventBasedGateway')) { for (let outgoing of node.outgoing) { if (outgoing.targetRef.id !== nodeId) res.push(outgoing.targetRef.id); } } } console.log(res); return res; }, deferredChoiceMarking: (eventId) => { let event = globalNodeMap.get(eventId); let node = event.incoming[0].sourceRef; var bitarray = []; var result = '0b'; if (node.outgoing) for (let outgoing of node.outgoing) { bitarray[controlFlowInfo.edgeIndexMap.get(outgoing.id)] = 1; } else result = '0'; for (let i = bitarray.length - 1; i >= 0; i--) result += bitarray[i] ? '1' : '0'; return new BigNumber(result).toFixed(); }, globalDeclarations: () => { if (controlFlowInfo.globalParameters.length > 0) return controlFlowInfo.globalParameters; else return ''; }, getOracleFunction: (nodeId) => { if(controlFlowInfo.oracleTaskMap.has(nodeId)) return controlFlowInfo.oracleInfo.get(controlFlowInfo.oracleTaskMap.get(nodeId)).functionName; return ""; }, nodeParameters: (nodeId) => { var node = globalNodeMap.get(nodeId); if ((node.documentation && node.documentation[0].text && node.documentation[0].text.length > 0)) { if (extractParameters(node.documentation[0].text, nodeId, null).get('input').length > 0) return true; return false; } return false; }, typeParameters: (nodeId, isInput, hasPreviousParameter) => { var node = globalNodeMap.get(nodeId); var res = ""; if (node.documentation && node.documentation[0].text && node.documentation[0].text.length > 0) { var localParams = isInput ? extractParameters(node.documentation[0].text, nodeId, null).get('input') : extractParameters(node.documentation[0].text, nodeId, null).get('output'); if (localParams.length > 0) { res = localParams[0]; for (let i = 2; i < localParams.length; i += 2) res += ', ' + (localParams[i]); } } return hasPreviousParameter && res.length > 0 ? ', ' + res : res; }, concatParameters: (nodeId, isInput, hasType, hasPreviousParameter) => { var node = globalNodeMap.get(nodeId); var res = ""; if (node.documentation && node.documentation[0].text && node.documentation[0].text.length > 0) { var localParams = isInput ? extractParameters(node.documentation[0].text, nodeId, null).get('input') : extractParameters(node.documentation[0].text, nodeId, null).get('output'); if (localParams.length > 0) { res = hasType ? localParams[0] + " " + localParams[1] : localParams[1]; for (let i = 2; i < localParams.length; i += 2) res += ',' + (hasType ? localParams[i] + " " + localParams[i + 1] : localParams[i + 1]); } } return hasPreviousParameter && res.length > 0 ? ', ' + res : res; }, nodeFunctionBody: (nodeId) => { let node = globalNodeMap.get(nodeId); if (node.script) { return node.script.split('->'); } else if (node.documentation && node.documentation[0].text && node.documentation[0].text.length > 0) { return extractParameters(node.documentation[0].text, nodeId, null).get('body'); } else return ''; }, getCondition: (flowEdge) => flowEdge.conditionExpression ? flowEdge.conditionExpression.body : flowEdge.name ? flowEdge.name : flowEdge.id, is: is }; let localSolidity = bpmn2solTemplate(codeGenerationInfo); // Code for using the WorkList template var userTaskList = []; var parameterInfo: Map<string, Array<ParameterInfo>> = new Map(); var hasDefault = false; controlFlowInfo.nodeList.forEach(nodeId => { var node = globalNodeMap.get(nodeId); if (is(node, 'bpmn:Task') && !is(node, 'bpmn:ServiceTask') && !is(node, 'bpmn:ScriptTask')) { if (controlFlowInfo.localParameters.has(nodeId) && controlFlowInfo.localParameters.get(nodeId).length > 0) { userTaskList.push(nodeId); parameterInfo.set(nodeId, controlFlowInfo.localParameters.get(nodeId)); } else hasDefault = true; } }) if (hasDefault || userTaskList.length == 0) userTaskList.push('defaultId'); let workListGenerationInfo = { nodeList: userTaskList, parameterInfo: parameterInfo, nodeMap: globalNodeMap, processId: () => controlFlowInfo.self.id, nodeName: (nodeId) => { if (nodeId === 'defaultId') return 'DefaultTask'; return getNodeName(globalNodeMap.get(nodeId)) }, getParameterType: (nodeId, isType) => { var res = ""; var localParams = parameterInfo.get(nodeId); if (localParams && localParams.length > 0) { res = isType ? localParams[0].type : localParams[0].name; for (let i = 1; i < localParams.length; i++) res += isType ? ", " + localParams[i].type : ", " + localParams[i].name; } return res.length > 0 ? ', ' + res : res; }, getParameters: (nodeId, hasType) => { var res = ""; var localParams = parameterInfo.get(nodeId); if (localParams && localParams.length > 0) { res = hasType ? localParams[0].type + " " + localParams[0].name : localParams[0].name; for (let i = 1; i < localParams.length; i++) res += hasType ? ", " + localParams[i].type + " " + localParams[i].name : ", " + localParams[i].name; } return res.length > 0 ? ', ' + res : res; }, is: is } let workListSolidity = workList2solTemplate(workListGenerationInfo); modelInfo.solidity += localSolidity; modelInfo.solidity += workListSolidity; modelInfo.controlFlowInfoMap.set(getNodeName(controlFlowInfo.self), controlFlowInfo); } else { controlFlowInfo.nodeList.forEach(nodeId => controlFlowInfo.nodeIndexMap.set(nodeId, globalNodeIndexMap.get(nodeId))); controlFlowInfo.edgeList.forEach(edgeId => controlFlowInfo.edgeIndexMap.set(edgeId, globalEdgeIndexMap.get(edgeId))); } } ////////////////////////////////////////////////////////////////////////////////// let entryContractName = modelInfo.name + ':' + (proc.name ? proc.name.replace(/\s+/g, '_') : proc.id) + '_Contract'; modelInfo.entryContractName = entryContractName; resolve(); }).catch(err => { throw new Error(err); }); });
the_stack
import { Injectable } from '@angular/core'; import { Store } from '@ngrx/store'; import { B2BUser, B2BUserRole, EntitiesModel, SearchConfig, StateUtils, UserIdService, } from '@spartacus/core'; import { Observable, queueScheduler, using } from 'rxjs'; import { auditTime, filter, map, observeOn, tap } from 'rxjs/operators'; import { OrganizationItemStatus } from '../model/organization-item-status'; import { Permission } from '../model/permission.model'; import { UserGroup } from '../model/user-group.model'; import { B2BUserActions } from '../store/actions/index'; import { StateWithOrganization } from '../store/organization-state'; import { getB2BUserApprovers, getB2BUserPermissions, getB2BUserState, getB2BUserUserGroups, getB2BUserValue, getUserList, } from '../store/selectors/b2b-user.selector'; import { getItemStatus } from '../utils/get-item-status'; @Injectable({ providedIn: 'root' }) export class B2BUserService { constructor( protected store: Store<StateWithOrganization>, protected userIdService: UserIdService ) {} load(orgCustomerId: string) { this.userIdService.takeUserId(true).subscribe( (userId) => this.store.dispatch( new B2BUserActions.LoadB2BUser({ userId, orgCustomerId, }) ), () => { // TODO: for future releases, refactor this part to thrown errors } ); } loadList(params: SearchConfig): void { this.userIdService.takeUserId(true).subscribe( (userId) => this.store.dispatch( new B2BUserActions.LoadB2BUsers({ userId, params }) ), () => { // TODO: for future releases, refactor this part to thrown errors } ); } private getB2BUserValue(orgCustomerId: string): Observable<B2BUser> { return this.store .select(getB2BUserValue(orgCustomerId)) .pipe(filter((b2bUser) => Boolean(b2bUser))); } get(orgCustomerId: string): Observable<B2BUser> { const loading$ = this.getB2BUserState(orgCustomerId).pipe( auditTime(0), tap((state) => { if (!(state.loading || state.success || state.error)) { this.load(orgCustomerId); } }) ); return using( () => loading$.subscribe(), () => this.getB2BUserValue(orgCustomerId) ); } getList( params: SearchConfig ): Observable<EntitiesModel<B2BUser> | undefined> { return this.getUserList(params).pipe( observeOn(queueScheduler), tap((process: StateUtils.LoaderState<EntitiesModel<B2BUser>>) => { if (!(process.loading || process.success || process.error)) { this.loadList(params); } }), filter((process: StateUtils.LoaderState<EntitiesModel<B2BUser>>) => Boolean(process.success || process.error) ), map((result) => result.value) ); } getErrorState(orgCustomerId: string): Observable<boolean> { return this.getB2BUserState(orgCustomerId).pipe( map((state) => state.error ?? false) ); } create(orgCustomer: B2BUser): void { this.userIdService.takeUserId(true).subscribe( (userId) => this.store.dispatch( new B2BUserActions.CreateB2BUser({ userId, orgCustomer, }) ), () => { // TODO: for future releases, refactor this part to thrown errors } ); } update(orgCustomerId: string, orgCustomer: B2BUser): void { this.userIdService.takeUserId(true).subscribe( (userId) => this.store.dispatch( new B2BUserActions.UpdateB2BUser({ userId, orgCustomerId, orgCustomer, }) ), () => { // TODO: for future releases, refactor this part to thrown errors } ); } getLoadingStatus( orgCustomerId: string ): Observable<OrganizationItemStatus<B2BUser>> { return getItemStatus(this.getB2BUserState(orgCustomerId)); } loadApprovers(orgCustomerId: string, params: SearchConfig): void { this.userIdService.takeUserId(true).subscribe( (userId) => this.store.dispatch( new B2BUserActions.LoadB2BUserApprovers({ userId, orgCustomerId, params, }) ), () => { // TODO: for future releases, refactor this part to thrown errors } ); } getApprovers( orgCustomerId: string, params: SearchConfig ): Observable<EntitiesModel<B2BUser> | undefined> { return this.getB2BUserApproverList(orgCustomerId, params).pipe( observeOn(queueScheduler), tap((process: StateUtils.LoaderState<EntitiesModel<B2BUser>>) => { if (!(process.loading || process.success || process.error)) { this.loadApprovers(orgCustomerId, params); } }), filter((process: StateUtils.LoaderState<EntitiesModel<B2BUser>>) => Boolean(process.success || process.error) ), map((result) => result.value) ); } assignApprover(orgCustomerId: string, approverId: string): void { this.userIdService.takeUserId(true).subscribe( (userId) => this.store.dispatch( new B2BUserActions.AssignB2BUserApprover({ userId, orgCustomerId, approverId, }) ), () => { // TODO: for future releases, refactor this part to thrown errors } ); } unassignApprover(orgCustomerId: string, approverId: string): void { this.userIdService.takeUserId(true).subscribe( (userId) => this.store.dispatch( new B2BUserActions.UnassignB2BUserApprover({ userId, orgCustomerId, approverId, }) ), () => { // TODO: for future releases, refactor this part to thrown errors } ); } loadPermissions(orgCustomerId: string, params: SearchConfig): void { this.userIdService.takeUserId(true).subscribe( (userId) => this.store.dispatch( new B2BUserActions.LoadB2BUserPermissions({ userId, orgCustomerId, params, }) ), () => { // TODO: for future releases, refactor this part to thrown errors } ); } getPermissions( orgCustomerId: string, params: SearchConfig ): Observable<EntitiesModel<Permission> | undefined> { return this.getB2BUserPermissionList(orgCustomerId, params).pipe( observeOn(queueScheduler), tap((process: StateUtils.LoaderState<EntitiesModel<Permission>>) => { if (!(process.loading || process.success || process.error)) { this.loadPermissions(orgCustomerId, params); } }), filter((process: StateUtils.LoaderState<EntitiesModel<Permission>>) => Boolean(process.success || process.error) ), map((result) => result.value) ); } assignPermission(orgCustomerId: string, permissionId: string): void { this.userIdService.takeUserId(true).subscribe( (userId) => this.store.dispatch( new B2BUserActions.AssignB2BUserPermission({ userId, orgCustomerId, permissionId, }) ), () => { // TODO: for future releases, refactor this part to thrown errors } ); } unassignPermission(orgCustomerId: string, permissionId: string): void { this.userIdService.takeUserId(true).subscribe( (userId) => this.store.dispatch( new B2BUserActions.UnassignB2BUserPermission({ userId, orgCustomerId, permissionId, }) ), () => { // TODO: for future releases, refactor this part to thrown errors } ); } loadUserGroups(orgCustomerId: string, params: SearchConfig): void { this.userIdService.takeUserId(true).subscribe( (userId) => this.store.dispatch( new B2BUserActions.LoadB2BUserUserGroups({ userId, orgCustomerId, params, }) ), () => { // TODO: for future releases, refactor this part to thrown errors } ); } getUserGroups( orgCustomerId: string, params: SearchConfig ): Observable<EntitiesModel<UserGroup> | undefined> { return this.getB2BUserUserGroupList(orgCustomerId, params).pipe( observeOn(queueScheduler), tap((process: StateUtils.LoaderState<EntitiesModel<UserGroup>>) => { if (!(process.loading || process.success || process.error)) { this.loadUserGroups(orgCustomerId, params); } }), filter((process: StateUtils.LoaderState<EntitiesModel<UserGroup>>) => Boolean(process.success || process.error) ), map((result) => result.value) ); } assignUserGroup(orgCustomerId: string, userGroupId: string): void { this.userIdService.takeUserId(true).subscribe( (userId) => this.store.dispatch( new B2BUserActions.AssignB2BUserUserGroup({ userId, orgCustomerId, userGroupId, }) ), () => { // TODO: for future releases, refactor this part to thrown errors } ); } unassignUserGroup(orgCustomerId: string, userGroupId: string): void { this.userIdService.takeUserId(true).subscribe( (userId) => this.store.dispatch( new B2BUserActions.UnassignB2BUserUserGroup({ userId, orgCustomerId, userGroupId, }) ), () => { // TODO: for future releases, refactor this part to thrown errors } ); } /** * Get list of all roles for B2BUser sorted by increasing privileges. * * This list is not driven by the backend (lack of API), but reflects roles * from the backend: `b2badmingroup`, `b2bcustomergroup`, `b2bmanagergroup` and `b2bapprovergroup`. * * If you reconfigure those roles in the backend or extend the list, you should change * this implementation accordingly. */ getAllRoles(): B2BUserRole[] { return [ B2BUserRole.CUSTOMER, B2BUserRole.MANAGER, B2BUserRole.APPROVER, B2BUserRole.ADMIN, ]; } private getB2BUserApproverList( orgCustomerId: string, params: SearchConfig ): Observable<StateUtils.LoaderState<EntitiesModel<B2BUser>>> { return this.store.select(getB2BUserApprovers(orgCustomerId, params)); } private getB2BUserPermissionList( orgCustomerId: string, params: SearchConfig ): Observable<StateUtils.LoaderState<EntitiesModel<Permission>>> { return this.store.select(getB2BUserPermissions(orgCustomerId, params)); } private getB2BUserUserGroupList( orgCustomerId: string, params: SearchConfig ): Observable<StateUtils.LoaderState<EntitiesModel<UserGroup>>> { return this.store.select(getB2BUserUserGroups(orgCustomerId, params)); } private getB2BUserState( orgCustomerId: string ): Observable<StateUtils.LoaderState<B2BUser>> { return this.store.select(getB2BUserState(orgCustomerId)); } private getUserList( params: SearchConfig ): Observable<StateUtils.LoaderState<EntitiesModel<B2BUser>>> { return this.store.select(getUserList(params)); } }
the_stack
import { createStore, createEvent, createEffect, sample, Store, Event, guard, } from 'effector' const typecheck = '{global}' /** * Please note, that some tests may seem duplicating, having the same target sets but * in different order. This is crucial for testing the correctness of conditional tuple * iteration algorithms as they rely on order in some situations. */ describe('basic cases (should pass)', () => { test('{ source: number, clock: any, target: [number] } (should pass)', () => { const num = createEvent<number>() const anyt = createEvent<any>() sample({source: num, clock: anyt, target: [num]}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('{ source: number, clock: any, target: [numberString, number] } (should pass)', () => { const numberString = createEvent<number | string>() const num = createEvent<number>() const anyt = createEvent<any>() sample({source: num, clock: anyt, target: [numberString, num]}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('{ source: number, clock: any, target: [void] } (should pass)', () => { const num = createEvent<number>() const anyt = createEvent<any>() const voidt = createEvent<void>() sample({source: num, clock: anyt, target: [voidt]}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('{ source: number, clock: any, target: [number, void] } (should pass)', () => { const num = createEvent<number>() const anyt = createEvent<any>() const voidt = createEvent<void>() sample({source: num, clock: anyt, target: [num, voidt]}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('{ source: number, clock: any, target: [void, number] } (should pass)', () => { const num = createEvent<number>() const anyt = createEvent<any>() const voidt = createEvent<void>() sample({source: num, clock: anyt, target: [voidt, num]}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) describe('basic cases', () => { test('{ source: number, clock: any, target: [] } (?)', () => { const num = createEvent<number>() const anyt = createEvent<any>() sample({source: num, clock: anyt, target: []}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('{ source: number, clock: any, target: [string] } (should fail)', () => { const str = createEvent<string>() const num = createEvent<number>() const anyt = createEvent<any>() //@ts-expect-error sample({source: num, clock: anyt, target: [str]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; clock: Event<any>; target: Event<string>[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: number; targetType: string; }]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: number; targetType: string; }]; }'. " `) }) test('{ source: number, clock: any, target: [number, string] } (should fail)', () => { const str = createEvent<string>() const num = createEvent<number>() const anyt = createEvent<any>() //@ts-expect-error sample({source: num, clock: anyt, target: [num, str]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; clock: Event<any>; target: (Event<number> | Event<string>)[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [Event<number>, { sourceType: number; targetType: string; }]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [Event<number>, { sourceType: number; targetType: string; }]; }'. " `) }) test('{ source: number, clock: any, target: [string, number] } (should fail)', () => { const str = createEvent<string>() const num = createEvent<number>() const anyt = createEvent<any>() //@ts-expect-error sample({source: num, clock: anyt, target: [str, num]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; clock: Event<any>; target: (Event<number> | Event<string>)[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: number; targetType: string; }, Event<number>]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: number; targetType: string; }, Event<number>]; }'. " `) }) test('{ source: number, clock: any, target: [numberString, string] } (should fail)', () => { const numberString = createEvent<number | string>() const str = createEvent<string>() const num = createEvent<number>() const anyt = createEvent<any>() //@ts-expect-error sample({source: num, clock: anyt, target: [numberString, str]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; clock: Event<any>; target: (Event<string> | Event<string | number>)[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [Event<string | number>, { sourceType: number; targetType: string; }]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [Event<string | number>, { sourceType: number; targetType: string; }]; }'. " `) }) test('{ source: number, clock: any, target: [string, numberString] } (should fail)', () => { const numberString = createEvent<number | string>() const str = createEvent<string>() const num = createEvent<number>() const anyt = createEvent<any>() //@ts-expect-error sample({source: num, clock: anyt, target: [str, numberString]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; clock: Event<any>; target: (Event<string> | Event<string | number>)[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: number; targetType: string; }, Event<string | number>]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: number; targetType: string; }, Event<string | number>]; }'. " `) }) test('{ source: number, clock: any, target: [number, stringBoolean] } (should fail)', () => { const stringBoolean = createEvent<string | boolean>() const num = createEvent<number>() const anyt = createEvent<any>() //@ts-expect-error sample({source: num, clock: anyt, target: [num, stringBoolean]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; clock: Event<any>; target: (Event<number> | Event<string | boolean>)[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [Event<number>, { sourceType: number; targetType: string | boolean; }]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [Event<number>, { sourceType: number; targetType: string | boolean; }]; }'. " `) }) test('{ source: number, clock: any, target: [stringBoolean, number] } (should fail)', () => { const stringBoolean = createEvent<string | boolean>() const num = createEvent<number>() const anyt = createEvent<any>() //@ts-expect-error sample({source: num, clock: anyt, target: [stringBoolean, num]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; clock: Event<any>; target: (Event<number> | Event<string | boolean>)[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: number; targetType: string | boolean; }, Event<number>]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: number; targetType: string | boolean; }, Event<number>]; }'. " `) }) test('{ source: number, clock: any, target: [void, string] } (should fail)', () => { const str = createEvent<string>() const num = createEvent<number>() const anyt = createEvent<any>() const voidt = createEvent<void>() //@ts-expect-error sample({source: num, clock: anyt, target: [voidt, str]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; clock: Event<any>; target: (Event<void> | Event<string>)[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [Event<void>, { sourceType: number; targetType: string; }]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [Event<void>, { sourceType: number; targetType: string; }]; }'. " `) }) test('{ source: number, clock: any, target: [string, void] } (should fail)', () => { const str = createEvent<string>() const num = createEvent<number>() const anyt = createEvent<any>() const voidt = createEvent<void>() //@ts-expect-error sample({source: num, clock: anyt, target: [str, voidt]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; clock: Event<any>; target: (Event<void> | Event<string>)[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: number; targetType: string; }, Event<void>]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: number; targetType: string; }, Event<void>]; }'. " `) }) test('{ source: number, clock: any, target: [any, string] } (should fail)', () => { const str = createEvent<string>() const num = createEvent<number>() const anyt = createEvent<any>() //@ts-expect-error sample({source: num, clock: anyt, target: [anyt, str]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; clock: Event<any>; target: (Event<any> | Event<string>)[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [Event<any>, { sourceType: number; targetType: string; }]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [Event<any>, { sourceType: number; targetType: string; }]; }'. " `) }) test('{ source: number, clock: any, target: [string, any] } (should fail)', () => { const str = createEvent<string>() const num = createEvent<number>() const anyt = createEvent<any>() //@ts-expect-error sample({source: num, clock: anyt, target: [str, anyt]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; clock: Event<any>; target: (Event<any> | Event<string>)[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: number; targetType: string; }, Event<any>]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: number; targetType: string; }, Event<any>]; }'. " `) }) }) describe('source & clock mapping (should pass)', () => { test('{ source: number, clock: number, fn: (s, c) => s + c, target: [number] } (should pass)', () => { const num = createEvent<number>() sample({ source: num, clock: num, fn: (s, c) => s + c, target: [num], }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('{ source: number, clock: number, fn: (s, c) => s + c, target: [numberString, number] } (should pass)', () => { const numberString = createEvent<number | string>() const num = createEvent<number>() sample({ source: num, clock: num, fn: (s, c) => s + c, target: [numberString, num], }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) describe('combinable source object (should pass)', () => { test('{ source: { a: $num }, clock: any, target: [a_num] } (should pass)', () => { const $num = createStore<number>(0) const a_num = createEvent<{a: number}>() const anyt = createEvent<any>() sample({source: {a: $num}, clock: anyt, target: [a_num]}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('{ source: { a: $num, b: $num }, clock: any, target: [a_num] } (should pass)', () => { const $num = createStore<number>(0) const a_num = createEvent<{a: number}>() const anyt = createEvent<any>() sample({source: {a: $num, b: $num}, clock: anyt, target: [a_num]}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('{ source: { a: $num, b: $num }, clock: any, target: [a_num_b_num] } (should pass)', () => { const $num = createStore<number>(0) const a_num_b_num = createEvent<{a: number; b: number}>() const anyt = createEvent<any>() sample({ source: {a: $num, b: $num}, clock: anyt, target: [a_num_b_num], }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) describe('combinable source object (should fail)', () => { test('{ source: { a: $num }, clock: any, target: [a_str] } (should fail)', () => { const $num = createStore<number>(0) const a_str = createEvent<{a: string}>() const anyt = createEvent<any>() //@ts-expect-error sample({source: {a: $num}, clock: anyt, target: [a_str]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: { a: Store<number>; }; clock: Event<any>; target: Event<{ a: string; }>[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: { a: number; }; targetType: { a: string; }; }]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: { a: number; }; targetType: { a: string; }; }]; }'. " `) }) test('{ source: { a: $num }, clock: any, target: [a_num, a_str] } (should fail)', () => { const $num = createStore<number>(0) const a_str = createEvent<{a: string}>() const a_num = createEvent<{a: number}>() const anyt = createEvent<any>() //@ts-expect-error sample({source: {a: $num}, clock: anyt, target: [a_num, a_str]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: { a: Store<number>; }; clock: Event<any>; target: (Event<{ a: string; }> | Event<{ a: number; }>)[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [Event<{ a: number; }>, { sourceType: { a: number; }; targetType: { a: string; }; }]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [Event<{ a: number; }>, { sourceType: { a: number; }; targetType: { a: string; }; }]; }'. " `) }) test('{ source: { a: $num }, clock: any, target: [a_num_b_str] } (should fail)', () => { const $num = createStore<number>(0) const a_num_b_str = createEvent<{a: number; b: string}>() const anyt = createEvent<any>() //@ts-expect-error sample({source: {a: $num}, clock: anyt, target: [a_num_b_str]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: { a: Store<number>; }; clock: Event<any>; target: Event<{ a: number; b: string; }>[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: { a: number; }; targetType: { a: number; b: string; }; }]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: { a: number; }; targetType: { a: number; b: string; }; }]; }'. " `) }) test('{ source: { a: $num }, clock: any, target: [a_num_b_num, a_num] } (should fail)', () => { const $num = createStore<number>(0) const a_num_b_num = createEvent<{a: number; b: number}>() const a_num = createEvent<{a: number}>() const anyt = createEvent<any>() //@ts-expect-error sample({source: {a: $num}, clock: anyt, target: [a_num_b_num, a_num]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: { a: Store<number>; }; clock: Event<any>; target: (Event<{ a: number; b: number; }> | Event<{ a: number; }>)[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: { a: number; }; targetType: { a: number; b: number; }; }, Event<{ a: number; }>]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: { a: number; }; targetType: { a: number; b: number; }; }, Event<{ a: number; }>]; }'. " `) }) }) describe('combinable source object & clock mapping (should pass)', () => { test('{ source: { a: $num, b: $num }, clock: number, fn: (s, c) => s.a + s.b + c, target: [number] } (should pass)', () => { const $num = createStore<number>(0) const num = createEvent<number>() sample({ source: {a: $num, b: $num}, clock: num, fn: (s, c) => s.a + s.b + c, target: [num], }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('{ source: { a: $num, b: $num }, clock: number, fn: (s, c) => s.a + s.b + c, target: [numberString, number] } (should pass)', () => { const $num = createStore<number>(0) const numberString = createEvent<number | string>() const num = createEvent<number>() sample({ source: {a: $num, b: $num}, clock: num, fn: (s, c) => s.a + s.b + c, target: [numberString, num], }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) describe('combinable source list (should pass)', () => { test('{ source: [$num], clock: any, target: [l_num] } (should pass)', () => { const $num = createStore<number>(0) const l_num = createEvent<[number]>() const anyt = createEvent<any>() sample({source: [$num], clock: anyt, target: [l_num]}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('{ source: [$num, $num], clock: any, target: [l_num_num] } (should pass)', () => { const $num = createStore<number>(0) const l_num_num = createEvent<[number, number]>() const anyt = createEvent<any>() sample({ source: [$num, $num], clock: anyt, target: [l_num_num], }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) describe('combinable source list (should fail)', () => { test('{ source: [$num], clock: any, target: [l_str] } (should fail)', () => { const $num = createStore<number>(0) const l_str = createEvent<[string]>() const anyt = createEvent<any>() //@ts-expect-error sample({source: [$num], clock: anyt, target: [l_str]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Store<number>[]; clock: Event<any>; target: Event<[string]>[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: [number]; targetType: [string]; }]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [{ sourceType: [number]; targetType: [string]; }]; }'. " `) }) test('{ source: [$num], clock: any, target: [l_num, l_str] } (should fail)', () => { const $num = createStore<number>(0) const l_str = createEvent<[string]>() const l_num = createEvent<[number]>() const anyt = createEvent<any>() //@ts-expect-error sample({source: [$num], clock: anyt, target: [l_num, l_str]}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Store<number>[]; clock: Event<any>; target: (Event<[number]> | Event<[string]>)[]; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: [Event<[number]>, { sourceType: [number]; targetType: [string]; }]; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: [Event<[number]>, { sourceType: [number]; targetType: [string]; }]; }'. " `) }) }) describe('combinable source list & clock mapping (should pass)', () => { test('{ source: [$num, $num], clock: number, fn: ([a, b], c) => a + b + c, target: [number] } (should pass)', () => { const $num = createStore<number>(0) const num = createEvent<number>() sample({ source: [$num, $num], clock: num, fn: ([a, b], c) => a + b + c, target: [num], }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('{ source: [$num, $num], clock: number, fn: ([a, b], c) => a + b + c, target: [numberString, number] } (should pass)', () => { const $num = createStore<number>(0) const numberString = createEvent<number | string>() const num = createEvent<number>() sample({ source: [$num, $num], clock: num, fn: ([a, b], c) => a + b + c, target: [numberString, num], }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) })
the_stack
declare module "openrecord/store/mysql" { interface StoreConfig { /** Hostname or IP of the server running your database (postgres, mysql and oracle only) */ host: string /** The database name (postgres, mysql and oracle only) */ database: string /** Username for your database (postgres, mysql, oracle, ldap/activedirectory only) */ user: string /** Password for your database (postgres, mysql, oracle, ldap/activedirectory only) */ password: string /** Set to false if you don't want to connect to your database immediately (sqlite3, postgres, mysql and oracle only) */ autoConnect?: boolean /** Set to false if you don't want to automatically define your model attributes via your database tables (sqlite3, postgres, mysql and oracle only) */ autoAttributes?: boolean /** Set to true if you want all your models automatically created from your database tables (sqlite3, postgres, mysql and oracle only) * With a postgres database it will take the public schema by default to get your tables. If you want to change that, set autoLoad to the schema name instead of true. */ autoLoad?: boolean /** The name of the store. Only needed if you use multiple stores and relations between them. */ name?: string /** Set to true if you want your Models defined in the global scope (not recommended). */ global?: boolean /** Add a prefix to your model name (in combination with global only). */ globalPrefix?: string /** Set the default value for autoSave on all relations */ autoSave?: boolean /** OPENRECORD will take your model name and pluralizes it to get e.g. the table name with the help of the inflection module * If you want to overwrite certain names, pass an object with the format {'wrong name': 'right name'}. */ inflection?: object /** Array of plugins (See Plugins) */ plugins?: ReadonlyArray<object> | ReadonlyArray<string> /** Array of models (See Definition) */ models?: ReadonlyArray<object> | ReadonlyArray<string> /** Array of migrations (See Migrations) */ migrations?: ReadonlyArray<object> | ReadonlyArray<string> } type Condition = (string|[string, any[]]|{ [name: string]: any }) class Model { constructor() /** * Initialize a new Record. * You could either use * ```js * var records = new Model(); * // or via * var records = Model.new(); * ``` * @param data The records attributes */ static new(data?: object, castType?: string): Model /** * Creates a new record and saves it * @param data The data of the new record */ static create(data: object): Promise<Model> static chain(options?: { clone?: boolean exclude?: string[] }): typeof Collection static clone(options?: { clone?: boolean exclude?: string[] }): typeof Collection /** * `exec()` will return raw JSON instead of records */ static asJson(): typeof Collection /** * `exec()` will return the raw store output * Be aware, that no `afterFind` hook will be fired if you use `asRaw()`. */ static asRaw(): typeof Collection /** * Find one or multiple records by their primary key * @param id The records primary key */ static find(id: number): typeof Collection static find(id: number[]): typeof Collection static find(id: string): typeof Collection static find(id: string[]): typeof Collection /** * Similar to `find`, but it will throw an error if there are no results * @param id The records primary key */ static get(id: number): typeof Collection static get(id: number[]): typeof Collection static get(id: string): typeof Collection static get(id: string[]): typeof Collection /** * Set some conditions * @param conditions every key-value pair will be translated into a condition */ static where(condition: Condition): typeof Collection /** * Adds a context object to your Model which could be used by your Hooks, Validation or Events via `this.context` * This is especially usefull need to differentiate things based on e.g. the cookie. Just set the context to the current request (`Model.setContext(req).create(params))` and use `this.context` inside your `beforeCreate()` hook. * The `context` Variable is available on your Model an all it's Records. * @param context Your context object */ static setContext(context: any): typeof Collection /** * Executes the find */ static exec(): Promise<Collection> static then(resolve: (result: (Collection|Model)) => (Promise<any>|void), reject?: () => any): (Collection|Model) /** * When called, it will throw an error if the resultset is empty */ static expectResult(): typeof Collection /** * Include relations into the result * @param includes array or nested object of relation names to include */ static include(includes: string): typeof Collection static include(includes: string[]): typeof Collection static include(includes: object): typeof Collection static include(includes: object[]): typeof Collection static callInterceptors(name: string, scope: any, args: any, options?: { executeInParallel: boolean }): Promise<any> /** * Limit the resultset to `n` records * @param limit The limit as a number. * @param offset Optional offset. */ static limit(limit: number, offset?: number): typeof Collection static first(limit?: boolean): typeof Collection static singleResult(limit?: boolean): typeof Collection /** * Sets only the offset * @param offset The offset. */ static offset(offset: number): typeof Collection static callParent(...args: any[]): any //GRAPHQL /** * returns a string represing the model as a graphql type * @param options Optional options */ static toGraphQLType(options?: { /** * Overwrite the type name (Default: Model name) */ name?: string, /** * Set a description for the type */ description?: string, /** * Array of fields to exclude */ exclude?: string[] }): string // SQL /** * Count the number of records in the database (SQL: `COUNT()`) * @param field Optional field name. (Default: `*`) * @param distinct Optional: DISTINCT(field). (Default: false) */ static count(field?: string, distinct?: boolean): typeof Collection /** * Calculates the sum of a certain field (SQL: `SUM()`) * @param field The field name. */ static sum(field: string): typeof Collection /** * Calculates the maximum value of a certain field (SQL: `MAX()`) * @param field The field name. */ static max(field: string): typeof Collection /** * Calculates the minimum value of a certain field (SQL: `MAX()`) * @param field The field name. */ static min(field: string): typeof Collection /** * Calculates the average value of a certain field (SQL: `MAX()`) * @param field The field name. */ static avg(field: string): typeof Collection static toSQL(): Promise<string> /** * Specify SQL group fields. * @param fields The field names */ static group(fields: string[]): typeof Collection /** * SQL Having conditions * @param condition every key-value pair will be translated into a condition */ static having(condition: Condition): typeof Collection /** * Joins one or multiple relations with the current model * @param relation The relation name which should be joined. * @param type Optional join type (Allowed are `left`, `inner`, `outer` and `right`). */ static join(relation: string, type?: string): typeof Collection static join(relation: string[], type?: string): typeof Collection static join(relation: object, type?: string): typeof Collection static join(... relation: string[]): typeof Collection /** * Left joins one or multiple relations with the current model * @param relation The relation name which should be joined. */ static leftJoin(relation: string, type?: string): typeof Collection static leftJoin(relation: string[], type?: string): typeof Collection static leftJoin(relation: object, type?: string): typeof Collection /** * Right joins one or multiple relations with the current model * @param relation The relation name which should be joined. */ static rightJoin(relation: string, type?: string): typeof Collection static rightJoin(relation: string[], type?: string): typeof Collection static rightJoin(relation: object, type?: string): typeof Collection /** * Inner joins one or multiple relations with the current model * @param relation The relation name which should be joined. */ static innerJoin(relation: string, type?: string): typeof Collection static innerJoin(relation: string[], type?: string): typeof Collection static innerJoin(relation: object, type?: string): typeof Collection /** * Outer joins one or multiple relations with the current model * @param relation The relation name which should be joined. */ static outerJoin(relation: string, type?: string): typeof Collection static outerJoin(relation: string[], type?: string): typeof Collection static outerJoin(relation: object, type?: string): typeof Collection /** * Set a sort order * @param columns Array of field names. * @param desc Optional: Set to `true` to order descent */ static order(columns: string, desc: boolean): typeof Collection static order(columns: string[], desc: boolean): typeof Collection /** * execute raw sql * @param sql The raw sql query. * @param attrs Query attributes. */ static raw(sql: string, attrs: any[]): Promise<any> /** * Updates all records which match the conditions. beforeSave, afterSave, beforeUpdate and afterUpdate want be called! */ static update(attributes: object, options?: { transaction?: any }): Promise<void> static updateAll(attributes: object, options?: { transaction?: any }): Promise<void> /** * Deletes all records which match the conditions. beforeDestroy and afterDestroy want be called! * Be careful with relations: The `dependent` option is not honored */ static delete(): Promise<void> static deleteAll(): Promise<void> /** * Loads all records at first and calls destroy on every single record. All hooks are fired and relations will be deleted if configured via options `dependent` */ static destroy(): Promise<void> static destroyAll(): Promise<void> /** * Specify SQL select fields. Default: * * @param fields The field names */ static select(fields: string): typeof Collection static select(fields: string[]): typeof Collection /** * Add the current query into a transaction * @param transaction The transaction object */ static useTransaction(transaction: any): typeof Collection // ======= // MODEL // ======= /** * Set one or multiple attributes of a Record. * @param name - The attributes name * @param value - The attributes value */ set(name: string, value: any): this set(value: object): this /** * Get an attributes. * @param name - The attributes name */ get(name: string): any /** * Returns `true` if there are any changed values in that record */ hasChanges(): boolean /** * Returns `true` if the given attributes has changed * @param name - The attributes name */ hasChanged(name: string): boolean /** * Returns an object with all the changes. One attribute will always include the original and current value */ getChanges(): object /** * Returns an object with all changed values */ getChangedValues(): object /** * Resets all changes to the original values */ resetChanges(): this /** * Include relations into the result * @param includes array or nested object of relation names to include */ include(includes: string): typeof Collection include(includes: string[]): typeof Collection include(includes: object): typeof Collection include(includes: object[]): typeof Collection inspect(indent: number, nested:boolean): string callInterceptors(name: string, scope: any, args: any, options?: { executeInParallel: boolean }): Promise<any> /** * Returns an object which represent the record in plain json */ toJson(): object callParent(...args: any[]): any clearRelations(): this /** * Save the current record */ save(): Promise<Model> /** * validates the record */ validate(): Promise<Model> /** * validates the record and returns true or false */ isValid(): Promise<boolean> /** * Destroy a record */ destroy(): Promise<void> /** * Deletes the record. beforeDestroy and afterDestroy want be called! * Be careful with relations: The `dependent` option is not honored */ delete(): Promise<void> } class Collection extends Model{ /** * Adds new Records to the collection * @param records - Either an object which will be transformed into a new Record, or an existing Record */ static add(records: Model): typeof Collection static add(records: object): typeof Collection static add(records: Model[]): typeof Collection static add(records: object[]): typeof Collection /** * Removes a Record from the Collection * @param item - Removes the record on the given index or record */ static remove(item: Model): typeof Collection static remove(item: number): typeof Collection static clear(): typeof Collection static temporaryDefinition(fn?: (this: Definition) => void): Definition /** * Returns an array of objects which represent the records in plain json */ static toJSON(): string static save(): Promise<typeof Collection> } interface RelationOptions{ /** The target model name as a string */ model?: string /** Optional store name. Only needed for cross store relations! */ store?: string /** The name of the field of the current model */ from?: string /** The name of the field of the target model */ to?: string /** The relation name of the current model you want to go through */ through?: (string | string[]) /** The relation name of the target model. Use only in conjunction with through. Default is the name of your relation */ relation?: string /** Set the <polymorhic name>. See belongsToPolymorphic() */ as?: string /** Optional conditions object (See Query) */ conditions?: Condition /** Optional name of a scope of the target model */ scope?: string /** What should happen with the related record after a record of this model will be deleted. Valid values are: destroy, delete, nullify or null. (Default: null) */ dependent?: string /** Automatically save loaded or new related records (See save and setup) */ autoSave?: boolean /** Set to false to disable autom. bulk fetching of relational data (Default: true) */ bulkFetch?: boolean /** Graphql Options */ graphql?: object } interface RawRelationOptions extends RelationOptions{ type: string preInitialize?: () => void initialize?: () => void loadWithCollection?: (collection: Collection) => void loadFromRecord?: (parentRecord: Model, include: object) => any collection?: (parentRecord: Model) => Collection getter?: () => any rawGetter?: () => any setter?: (value: any) => any } interface ValidatesFormatOfOptions{ /** Skip validation if value is null */ allow_null?: boolean } interface ValidatesNumericalityOfOptions{ // Skip validation if value is null allow_null?: boolean // value need to be equal `eq` eq?: number // value need to be greater than `gt` gt?: number // value need to be greater than or equal `gte` gte?: number // value need to be lower than `lt` lt?: number // value need to be lower than or equal `lte` lte?: number // value need to be even even?: boolean // value need to be odd off?: boolean } interface Definition { getName(): string include(mixin: object): void /** * Add a new attribute to your Model * @param name The attribute name * @param type The attribute type (e.g. `text`, `integer`, or sql language specific. e.g. `blob`) * @param options Optional options */ attribute(name: string, type: string, options?: { /** * make it writeable (Default: true) */ writable?: boolean /** * make it readable (Default: true) */ readable?: boolean /** * Default value */ default?: any /** * emit change events `name_changed` (Default: false) */ emit_events?: boolean }): this cast(attribute: string, value: any, castName?: string, record?: Model): any /** * Add a custom getter to your record * @param name The getter name * @param fn The method to call */ getter(name: string, fn: (this: Model) => any): this /** * Add a custom setter to your record * @param name The setter name * @param fn The method to call */ setter(name: string, fn: (this: Model, value: any) => void): this /** * Add a variant method to the specified attribute * @param name The attribute name * @param fn The method to call */ variant(name: string, fn: (this: Model, value: any, args: any) => any): this /** * add a special convert function to manipulate the input (e.g. via `set()`) value of an attribute * @param attribute The attribute name * @param fn The convert function * @param forceType Default: `true`. If set to `false` it will leave your return value untouched. Otherwiese it will cast it to the original value type. */ convertInput(attribute: string, fn: (this: Model, value: any) => any, forceType: boolean): this /** * add a special convert function to manipulate the output (`toJson()`) value of an attribute * @param attribute The attribute name * @param fn The convert function * @param forceType Default: `true`. If set to `false` it will leave your return value untouched. Otherwiese it will cast it to the original value type. */ convertOutput(attribute: string, fn: (this: Model, value: any) => any, forceType: boolean): this /** * add a special convert function to manipulate the read (`exec()`) value of an attribute * @param attribute The attribute name * @param fn The convert function * @param forceType Default: `true`. If set to `false` it will leave your return value untouched. Otherwiese it will cast it to the original value type. */ convertRead(attribute: string, fn: (this: Model, value: any) => any, forceType: boolean): this /** * add a special convert function to manipulate the write (`save()`) value of an attribute * @param attribute The attribute name * @param fn The convert function * @param forceType Default: `true`. If set to `false` it will leave your return value untouched. Otherwiese it will cast it to the original value type. */ convertWrite(attribute: string, fn: (this: Model, value: any) => any, forceType: boolean): this addInterceptor(name: string, fn: (...args: any[]) => Promise<any>, priority?: number): this callInterceptors(name: string, scope: any, args: any, options?: { executeInParallel: boolean }): Promise<any> /** * Adds a new method to the record * @param name The name of the method * @param fn The function */ method(name: string, fn: (this: Model, ...args: any[]) => any): this /** * Adds a new method to the class * @param name The name of the method * @param fn The function */ staticMethod(name: string, fn: (this: typeof Model, ...args: any[]) => any): this /** * mixin a module to extend your model definition. * The module needs to export either a function, which will be called with the definition scope * or an objects which will be mixed into the defintion object. * @param module the module */ mixin(module: (this: Definition) => void): this mixin(module: object): this callParent(...args: any[]): any belongsToMany(name: string, options?: RelationOptions): this belongsToPolymorphic(name: string, options?: RelationOptions): this belongsTo(name: string, options?: RelationOptions): this hasMany(name: string, options?: RelationOptions): this has(name: string, options?: RawRelationOptions): this /** * Creates a custom chained Model method * @param name The name of the scope * @param fn The scope function */ scope(name:string, fn:(this: Model, ...args:any[]) => any):this /** * Adds a default scope * @param name The name of the scope */ defaultScope(name: string): this /** * Validate any field with a custom function. * Synchronous: just return `true` or `false` * Asynchronous: put a `done` parameter into your callback and call `done()` when finished. * @param fields The fields to validate * @param fn The validation callback */ validates(fields: string[], fn: (this: Model) => (boolean | Promise<boolean>)): this validates(fields: string, fn: (this: Model) => (boolean | Promise<boolean>)): this /** * This validator checks the given field`s value is not null. * @param fields The fields to validate */ validatesPresenceOf(fields: string[]): this validatesPresenceOf(fields: string): this /** * This validator checks if the given field`s value and <field_name>_confirmation are the same. * @param fields The fields to validate */ validatesConfirmationOf(fields: string[]): this validatesConfirmationOf(fields: string): this /** * This validator checks the format of a field. * Valid format types are: * * `email` * * `url` * * `ip` * * `uuid` * * `date` * * null * * Regular expression * @param fields The fields to validate * @param format The format type * @param options The options hash * @param options.allow_null Skip validation if value is null */ validatesFormatOf(field: string, format: string, options?: ValidatesFormatOfOptions): this validatesFormatOf(field: string[], format: string, options?: ValidatesFormatOfOptions): this validatesFormatOf(field: string, format: RegExp, options?: ValidatesFormatOfOptions): this validatesFormatOf(field: string[], format: RegExp, options?: ValidatesFormatOfOptions): this validatesFormatOf(field: string, format: null, options?: ValidatesFormatOfOptions): this validatesFormatOf(field: string[], format: null, options?: ValidatesFormatOfOptions): this /** * This validator checks if the given field`s values length is lesss than or equal `length`. * @param field The field to validate * @param length The maximum length */ validatesLengthOf(field: string, length: number): this validatesLengthOf(field: string[], length: number): this /** * This validator checks if the given field`s values is an allowed value * @param field The field to validate * @param allowedValues The array of allowed values */ validatesInclusionOf(field: string, allowedValues: any[]): this validatesInclusionOf(field: string[], allowedValues: any[]): this /** * This validator checks the given field`s values against some rules. * @param field The field to validate * @param options The options */ validatesNumericalityOf(field: string, options: ValidatesNumericalityOfOptions): this validatesNumericalityOf(field: string[], options: ValidatesNumericalityOfOptions): this // GRAPHQL PLUGIN graphQLDescription(description: string): this graphQLField(schema: string): this graphQLExclude(): this graphQLExcludeField(field: string): this graphQLQuery(schema: string): this graphQLMutation(schema: string): this graphQL(schema: string): this graphQL(schema: () => any, name: string): this graphQLResolver(resolver: object): this graphQLTypeResolver(resolver: object): this graphQLQueryResolver(resolver: object): this graphQLMutationResolver(resolver: object): this // SQL /** * Enable automatic joins on tables referenced in conditions * @param options Optional configuration options */ autoJoin(options?: { relations?: string[] }): this /** * This validator checks the uniqness of the given field`s value before save. * @param {array} fields The fields to validate * @or * @param {string} fields The field to validate * @param {object} options Optional: Options hash * * @options * @param {string} scope Set a scope column * * @return {Definition} */ validatesUniquenessOf(field: string, options?: { scope: string }): this validatesUniquenessOf(field: string[], options?: { scope: string }): this //SQL PLUGIN nestedSet(): this paranoid(): this serialize(attribute: string, serializer: { parse: (value: string) => object stringify: (value: object) => string }): this sortedList(options?: { scope: string insert: string }): this stampable(): this } type StaticModel = typeof Model // for es6 classes interface BaseModel extends StaticModel{ definition(this: Definition): void } class Store { constructor(config: StoreConfig) ready(next?: () => void): Promise<void> Model(name: string, fn: (this: Definition) => void): void Model(name: string): typeof Model static BaseModel: BaseModel } export = Store }
the_stack
import { emptyArray } from "../platform.js"; /** * Represents a set of splice-based changes against an Array. * @public */ export interface Splice { /** * The index that the splice occurs at. */ index: number; /** * The items that were removed. */ removed: any[]; /** * The number of items that were added. */ addedCount: number; } /** @internal */ export function newSplice(index: number, removed: any[], addedCount: number): Splice { return { index: index, removed: removed, addedCount: addedCount, }; } const EDIT_LEAVE = 0; const EDIT_UPDATE = 1; const EDIT_ADD = 2; const EDIT_DELETE = 3; // Note: This function is *based* on the computation of the Levenshtein // "edit" distance. The one change is that "updates" are treated as two // edits - not one. With Array splices, an update is really a delete // followed by an add. By retaining this, we optimize for "keeping" the // maximum array items in the original array. For example: // // 'xxxx123' -> '123yyyy' // // With 1-edit updates, the shortest path would be just to update all seven // characters. With 2-edit updates, we delete 4, leave 3, and add 4. This // leaves the substring '123' intact. function calcEditDistances( current: any[], currentStart: number, currentEnd: number, old: any[], oldStart: number, oldEnd: number ): any[] { // "Deletion" columns const rowCount = oldEnd - oldStart + 1; const columnCount = currentEnd - currentStart + 1; const distances = new Array(rowCount); let north; let west; // "Addition" rows. Initialize null column. for (let i = 0; i < rowCount; ++i) { distances[i] = new Array(columnCount); distances[i][0] = i; } // Initialize null row for (let j = 0; j < columnCount; ++j) { distances[0][j] = j; } for (let i = 1; i < rowCount; ++i) { for (let j = 1; j < columnCount; ++j) { if (current[currentStart + j - 1] === old[oldStart + i - 1]) { distances[i][j] = distances[i - 1][j - 1]; } else { north = distances[i - 1][j] + 1; west = distances[i][j - 1] + 1; distances[i][j] = north < west ? north : west; } } } return distances; } // This starts at the final weight, and walks "backward" by finding // the minimum previous weight recursively until the origin of the weight // matrix. function spliceOperationsFromEditDistances(distances: number[][]): number[] { let i = distances.length - 1; let j = distances[0].length - 1; let current = distances[i][j]; const edits: number[] = []; while (i > 0 || j > 0) { if (i === 0) { edits.push(EDIT_ADD); j--; continue; } if (j === 0) { edits.push(EDIT_DELETE); i--; continue; } const northWest = distances[i - 1][j - 1]; const west = distances[i - 1][j]; const north = distances[i][j - 1]; let min; if (west < north) { min = west < northWest ? west : northWest; } else { min = north < northWest ? north : northWest; } if (min === northWest) { if (northWest === current) { edits.push(EDIT_LEAVE); } else { edits.push(EDIT_UPDATE); current = northWest; } i--; j--; } else if (min === west) { edits.push(EDIT_DELETE); i--; current = west; } else { edits.push(EDIT_ADD); j--; current = north; } } edits.reverse(); return edits; } function sharedPrefix(current: any[], old: any[], searchLength: number): number { for (let i = 0; i < searchLength; ++i) { if (current[i] !== old[i]) { return i; } } return searchLength; } function sharedSuffix(current: any[], old: any[], searchLength: number): number { let index1 = current.length; let index2 = old.length; let count = 0; while (count < searchLength && current[--index1] === old[--index2]) { count++; } return count; } function intersect(start1: number, end1: number, start2: number, end2: number): number { // Disjoint if (end1 < start2 || end2 < start1) { return -1; } // Adjacent if (end1 === start2 || end2 === start1) { return 0; } // Non-zero intersect, span1 first if (start1 < start2) { if (end1 < end2) { return end1 - start2; // Overlap } return end2 - start2; // Contained } // Non-zero intersect, span2 first if (end2 < end1) { return end2 - start1; // Overlap } return end1 - start1; // Contained } /** * Splice Projection functions: * * A splice map is a representation of how a previous array of items * was transformed into a new array of items. Conceptually it is a list of * tuples of * * <index, removed, addedCount> * * which are kept in ascending index order of. The tuple represents that at * the |index|, |removed| sequence of items were removed, and counting forward * from |index|, |addedCount| items were added. */ /** * @internal * @remarks * Lacking individual splice mutation information, the minimal set of * splices can be synthesized given the previous state and final state of an * array. The basic approach is to calculate the edit distance matrix and * choose the shortest path through it. * * Complexity: O(l * p) * l: The length of the current array * p: The length of the old array */ export function calcSplices( current: any[], currentStart: number, currentEnd: number, old: any[], oldStart: number, oldEnd: number ): ReadonlyArray<never> | Splice[] { let prefixCount = 0; let suffixCount = 0; const minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart); if (currentStart === 0 && oldStart === 0) { prefixCount = sharedPrefix(current, old, minLength); } if (currentEnd === current.length && oldEnd === old.length) { suffixCount = sharedSuffix(current, old, minLength - prefixCount); } currentStart += prefixCount; oldStart += prefixCount; currentEnd -= suffixCount; oldEnd -= suffixCount; if (currentEnd - currentStart === 0 && oldEnd - oldStart === 0) { return emptyArray; } if (currentStart === currentEnd) { const splice = newSplice(currentStart, [], 0); while (oldStart < oldEnd) { splice.removed.push(old[oldStart++]); } return [splice]; } else if (oldStart === oldEnd) { return [newSplice(currentStart, [], currentEnd - currentStart)]; } const ops = spliceOperationsFromEditDistances( calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd) ); const splices: Splice[] = []; let splice: Splice | undefined = void 0; let index = currentStart; let oldIndex = oldStart; for (let i = 0; i < ops.length; ++i) { switch (ops[i]) { case EDIT_LEAVE: if (splice !== void 0) { splices.push(splice); splice = void 0; } index++; oldIndex++; break; case EDIT_UPDATE: if (splice === void 0) { splice = newSplice(index, [], 0); } splice.addedCount++; index++; splice.removed.push(old[oldIndex]); oldIndex++; break; case EDIT_ADD: if (splice === void 0) { splice = newSplice(index, [], 0); } splice.addedCount++; index++; break; case EDIT_DELETE: if (splice === void 0) { splice = newSplice(index, [], 0); } splice.removed.push(old[oldIndex]); oldIndex++; break; // no default } } if (splice !== void 0) { splices.push(splice); } return splices; } const $push = Array.prototype.push; function mergeSplice( splices: Splice[], index: number, removed: any[], addedCount: number ): void { const splice = newSplice(index, removed, addedCount); let inserted = false; let insertionOffset = 0; for (let i = 0; i < splices.length; i++) { const current = splices[i]; current.index += insertionOffset; if (inserted) { continue; } const intersectCount = intersect( splice.index, splice.index + splice.removed.length, current.index, current.index + current.addedCount ); if (intersectCount >= 0) { // Merge the two splices splices.splice(i, 1); i--; insertionOffset -= current.addedCount - current.removed.length; splice.addedCount += current.addedCount - intersectCount; const deleteCount = splice.removed.length + current.removed.length - intersectCount; if (!splice.addedCount && !deleteCount) { // merged splice is a noop. discard. inserted = true; } else { let currentRemoved = current.removed; if (splice.index < current.index) { // some prefix of splice.removed is prepended to current.removed. const prepend = splice.removed.slice(0, current.index - splice.index); $push.apply(prepend, currentRemoved); currentRemoved = prepend; } if ( splice.index + splice.removed.length > current.index + current.addedCount ) { // some suffix of splice.removed is appended to current.removed. const append = splice.removed.slice( current.index + current.addedCount - splice.index ); $push.apply(currentRemoved, append); } splice.removed = currentRemoved; if (current.index < splice.index) { splice.index = current.index; } } } else if (splice.index < current.index) { // Insert splice here. inserted = true; splices.splice(i, 0, splice); i++; const offset = splice.addedCount - splice.removed.length; current.index += offset; insertionOffset += offset; } } if (!inserted) { splices.push(splice); } } function createInitialSplices(changeRecords: Splice[]): Splice[] { const splices: Splice[] = []; for (let i = 0, ii = changeRecords.length; i < ii; i++) { const record = changeRecords[i]; mergeSplice(splices, record.index, record.removed, record.addedCount); } return splices; } /** @internal */ export function projectArraySplices(array: any[], changeRecords: any[]): Splice[] { let splices: Splice[] = []; const initialSplices = createInitialSplices(changeRecords); for (let i = 0, ii = initialSplices.length; i < ii; ++i) { const splice = initialSplices[i]; if (splice.addedCount === 1 && splice.removed.length === 1) { if (splice.removed[0] !== array[splice.index]) { splices.push(splice); } continue; } splices = splices.concat( calcSplices( array, splice.index, splice.index + splice.addedCount, splice.removed, 0, splice.removed.length ) ); } return splices; }
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; /** * The resource specified in your request already exists. */ export interface AlreadyExistsException extends __SmithyException, $MetadataBearer { name: "AlreadyExistsException"; $fault: "client"; Message?: string; } export namespace AlreadyExistsException { /** * @internal */ export const filterSensitiveLog = (obj: AlreadyExistsException): any => ({ ...obj, }); } /** * The input you provided is invalid. */ export interface BadRequestException extends __SmithyException, $MetadataBearer { name: "BadRequestException"; $fault: "client"; Message?: string; } export namespace BadRequestException { /** * @internal */ export const filterSensitiveLog = (obj: BadRequestException): any => ({ ...obj, }); } /** * An object that defines a message that contains text formatted using Amazon Pinpoint Voice Instructions markup. */ export interface CallInstructionsMessageType { /** * The language to use when delivering the message. For a complete list of supported languages, see the Amazon Polly Developer Guide. */ Text?: string; } export namespace CallInstructionsMessageType { /** * @internal */ export const filterSensitiveLog = (obj: CallInstructionsMessageType): any => ({ ...obj, }); } /** * An object that contains information about an event destination that sends data to Amazon CloudWatch Logs. */ export interface CloudWatchLogsDestination { /** * The Amazon Resource Name (ARN) of an Amazon Identity and Access Management (IAM) role that is able to write event data to an Amazon CloudWatch destination. */ IamRoleArn?: string; /** * The name of the Amazon CloudWatch Log Group that you want to record events in. */ LogGroupArn?: string; } export namespace CloudWatchLogsDestination { /** * @internal */ export const filterSensitiveLog = (obj: CloudWatchLogsDestination): any => ({ ...obj, }); } /** * A request to create a new configuration set. */ export interface CreateConfigurationSetRequest { /** * The name that you want to give the configuration set. */ ConfigurationSetName?: string; } export namespace CreateConfigurationSetRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateConfigurationSetRequest): any => ({ ...obj, }); } /** * An empty object that indicates that the configuration set was successfully created. */ export interface CreateConfigurationSetResponse {} export namespace CreateConfigurationSetResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateConfigurationSetResponse): any => ({ ...obj, }); } /** * The API encountered an unexpected error and couldn't complete the request. You might be able to successfully issue the request again in the future. */ export interface InternalServiceErrorException extends __SmithyException, $MetadataBearer { name: "InternalServiceErrorException"; $fault: "server"; Message?: string; } export namespace InternalServiceErrorException { /** * @internal */ export const filterSensitiveLog = (obj: InternalServiceErrorException): any => ({ ...obj, }); } /** * There are too many instances of the specified resource type. */ export interface LimitExceededException extends __SmithyException, $MetadataBearer { name: "LimitExceededException"; $fault: "client"; Message?: string; } export namespace LimitExceededException { /** * @internal */ export const filterSensitiveLog = (obj: LimitExceededException): any => ({ ...obj, }); } /** * You've issued too many requests to the resource. Wait a few minutes, and then try again. */ export interface TooManyRequestsException extends __SmithyException, $MetadataBearer { name: "TooManyRequestsException"; $fault: "client"; Message?: string; } export namespace TooManyRequestsException { /** * @internal */ export const filterSensitiveLog = (obj: TooManyRequestsException): any => ({ ...obj, }); } /** * An object that contains information about an event destination that sends data to Amazon Kinesis Data Firehose. */ export interface KinesisFirehoseDestination { /** * The Amazon Resource Name (ARN) of an IAM role that can write data to an Amazon Kinesis Data Firehose stream. */ DeliveryStreamArn?: string; /** * The Amazon Resource Name (ARN) of the Amazon Kinesis Data Firehose destination that you want to use in the event destination. */ IamRoleArn?: string; } export namespace KinesisFirehoseDestination { /** * @internal */ export const filterSensitiveLog = (obj: KinesisFirehoseDestination): any => ({ ...obj, }); } export enum EventType { ANSWERED = "ANSWERED", BUSY = "BUSY", COMPLETED_CALL = "COMPLETED_CALL", FAILED = "FAILED", INITIATED_CALL = "INITIATED_CALL", NO_ANSWER = "NO_ANSWER", RINGING = "RINGING", } /** * An object that contains information about an event destination that sends data to Amazon SNS. */ export interface SnsDestination { /** * The Amazon Resource Name (ARN) of the Amazon SNS topic that you want to publish events to. */ TopicArn?: string; } export namespace SnsDestination { /** * @internal */ export const filterSensitiveLog = (obj: SnsDestination): any => ({ ...obj, }); } /** * An object that defines a single event destination. */ export interface EventDestinationDefinition { /** * An object that contains information about an event destination that sends data to Amazon CloudWatch Logs. */ CloudWatchLogsDestination?: CloudWatchLogsDestination; /** * Indicates whether or not the event destination is enabled. If the event destination is enabled, then Amazon Pinpoint sends response data to the specified event destination. */ Enabled?: boolean; /** * An object that contains information about an event destination that sends data to Amazon Kinesis Data Firehose. */ KinesisFirehoseDestination?: KinesisFirehoseDestination; /** * An array of EventDestination objects. Each EventDestination object includes ARNs and other information that define an event destination. */ MatchingEventTypes?: (EventType | string)[]; /** * An object that contains information about an event destination that sends data to Amazon SNS. */ SnsDestination?: SnsDestination; } export namespace EventDestinationDefinition { /** * @internal */ export const filterSensitiveLog = (obj: EventDestinationDefinition): any => ({ ...obj, }); } /** * Create a new event destination in a configuration set. */ export interface CreateConfigurationSetEventDestinationRequest { /** * ConfigurationSetName */ ConfigurationSetName: string | undefined; /** * An object that defines a single event destination. */ EventDestination?: EventDestinationDefinition; /** * A name that identifies the event destination. */ EventDestinationName?: string; } export namespace CreateConfigurationSetEventDestinationRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateConfigurationSetEventDestinationRequest): any => ({ ...obj, }); } /** * An empty object that indicates that the event destination was created successfully. */ export interface CreateConfigurationSetEventDestinationResponse {} export namespace CreateConfigurationSetEventDestinationResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateConfigurationSetEventDestinationResponse): any => ({ ...obj, }); } /** * The resource you attempted to access doesn't exist. */ export interface NotFoundException extends __SmithyException, $MetadataBearer { name: "NotFoundException"; $fault: "client"; Message?: string; } export namespace NotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: NotFoundException): any => ({ ...obj, }); } export interface DeleteConfigurationSetRequest { /** * ConfigurationSetName */ ConfigurationSetName: string | undefined; } export namespace DeleteConfigurationSetRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteConfigurationSetRequest): any => ({ ...obj, }); } /** * An empty object that indicates that the configuration set was deleted successfully. */ export interface DeleteConfigurationSetResponse {} export namespace DeleteConfigurationSetResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteConfigurationSetResponse): any => ({ ...obj, }); } export interface DeleteConfigurationSetEventDestinationRequest { /** * ConfigurationSetName */ ConfigurationSetName: string | undefined; /** * EventDestinationName */ EventDestinationName: string | undefined; } export namespace DeleteConfigurationSetEventDestinationRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteConfigurationSetEventDestinationRequest): any => ({ ...obj, }); } /** * An empty object that indicates that the event destination was deleted successfully. */ export interface DeleteConfigurationSetEventDestinationResponse {} export namespace DeleteConfigurationSetEventDestinationResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteConfigurationSetEventDestinationResponse): any => ({ ...obj, }); } /** * An object that defines an event destination. */ export interface EventDestination { /** * An object that contains information about an event destination that sends data to Amazon CloudWatch Logs. */ CloudWatchLogsDestination?: CloudWatchLogsDestination; /** * Indicates whether or not the event destination is enabled. If the event destination is enabled, then Amazon Pinpoint sends response data to the specified event destination. */ Enabled?: boolean; /** * An object that contains information about an event destination that sends data to Amazon Kinesis Data Firehose. */ KinesisFirehoseDestination?: KinesisFirehoseDestination; /** * An array of EventDestination objects. Each EventDestination object includes ARNs and other information that define an event destination. */ MatchingEventTypes?: (EventType | string)[]; /** * A name that identifies the event destination configuration. */ Name?: string; /** * An object that contains information about an event destination that sends data to Amazon SNS. */ SnsDestination?: SnsDestination; } export namespace EventDestination { /** * @internal */ export const filterSensitiveLog = (obj: EventDestination): any => ({ ...obj, }); } export interface GetConfigurationSetEventDestinationsRequest { /** * ConfigurationSetName */ ConfigurationSetName: string | undefined; } export namespace GetConfigurationSetEventDestinationsRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetConfigurationSetEventDestinationsRequest): any => ({ ...obj, }); } /** * An object that contains information about an event destination. */ export interface GetConfigurationSetEventDestinationsResponse { /** * An array of EventDestination objects. Each EventDestination object includes ARNs and other information that define an event destination. */ EventDestinations?: EventDestination[]; } export namespace GetConfigurationSetEventDestinationsResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetConfigurationSetEventDestinationsResponse): any => ({ ...obj, }); } export interface ListConfigurationSetsRequest { /** * A token returned from a previous call to the API that indicates the position in the list of results. */ NextToken?: string; /** * Used to specify the number of items that should be returned in the response. */ PageSize?: string; } export namespace ListConfigurationSetsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListConfigurationSetsRequest): any => ({ ...obj, }); } /** * An object that contains information about the configuration sets for your account in the current region. */ export interface ListConfigurationSetsResponse { /** * An object that contains a list of configuration sets for your account in the current region. */ ConfigurationSets?: string[]; /** * A token returned from a previous call to ListConfigurationSets to indicate the position in the list of configuration sets. */ NextToken?: string; } export namespace ListConfigurationSetsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListConfigurationSetsResponse): any => ({ ...obj, }); } /** * An object that defines a message that contains unformatted text. */ export interface PlainTextMessageType { /** * The language to use when delivering the message. For a complete list of supported languages, see the Amazon Polly Developer Guide. */ LanguageCode?: string; /** * The plain (not SSML-formatted) text to deliver to the recipient. */ Text?: string; /** * The name of the voice that you want to use to deliver the message. For a complete list of supported voices, see the Amazon Polly Developer Guide. */ VoiceId?: string; } export namespace PlainTextMessageType { /** * @internal */ export const filterSensitiveLog = (obj: PlainTextMessageType): any => ({ ...obj, }); } /** * An object that defines a message that contains SSML-formatted text. */ export interface SSMLMessageType { /** * The language to use when delivering the message. For a complete list of supported languages, see the Amazon Polly Developer Guide. */ LanguageCode?: string; /** * The SSML-formatted text to deliver to the recipient. */ Text?: string; /** * The name of the voice that you want to use to deliver the message. For a complete list of supported voices, see the Amazon Polly Developer Guide. */ VoiceId?: string; } export namespace SSMLMessageType { /** * @internal */ export const filterSensitiveLog = (obj: SSMLMessageType): any => ({ ...obj, }); } /** * An object that contains a voice message and information about the recipient that you want to send it to. */ export interface VoiceMessageContent { /** * An object that defines a message that contains text formatted using Amazon Pinpoint Voice Instructions markup. */ CallInstructionsMessage?: CallInstructionsMessageType; /** * An object that defines a message that contains unformatted text. */ PlainTextMessage?: PlainTextMessageType; /** * An object that defines a message that contains SSML-formatted text. */ SSMLMessage?: SSMLMessageType; } export namespace VoiceMessageContent { /** * @internal */ export const filterSensitiveLog = (obj: VoiceMessageContent): any => ({ ...obj, }); } /** * SendVoiceMessageRequest */ export interface SendVoiceMessageRequest { /** * The phone number that appears on recipients' devices when they receive the message. */ CallerId?: string; /** * The name of the configuration set that you want to use to send the message. */ ConfigurationSetName?: string; /** * An object that contains a voice message and information about the recipient that you want to send it to. */ Content?: VoiceMessageContent; /** * The phone number that you want to send the voice message to. */ DestinationPhoneNumber?: string; /** * The phone number that Amazon Pinpoint should use to send the voice message. This isn't necessarily the phone number that appears on recipients' devices when they receive the message, because you can specify a CallerId parameter in the request. */ OriginationPhoneNumber?: string; } export namespace SendVoiceMessageRequest { /** * @internal */ export const filterSensitiveLog = (obj: SendVoiceMessageRequest): any => ({ ...obj, }); } /** * An object that that contains the Message ID of a Voice message that was sent successfully. */ export interface SendVoiceMessageResponse { /** * A unique identifier for the voice message. */ MessageId?: string; } export namespace SendVoiceMessageResponse { /** * @internal */ export const filterSensitiveLog = (obj: SendVoiceMessageResponse): any => ({ ...obj, }); } /** * UpdateConfigurationSetEventDestinationRequest */ export interface UpdateConfigurationSetEventDestinationRequest { /** * ConfigurationSetName */ ConfigurationSetName: string | undefined; /** * An object that defines a single event destination. */ EventDestination?: EventDestinationDefinition; /** * EventDestinationName */ EventDestinationName: string | undefined; } export namespace UpdateConfigurationSetEventDestinationRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateConfigurationSetEventDestinationRequest): any => ({ ...obj, }); } /** * An empty object that indicates that the event destination was updated successfully. */ export interface UpdateConfigurationSetEventDestinationResponse {} export namespace UpdateConfigurationSetEventDestinationResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateConfigurationSetEventDestinationResponse): any => ({ ...obj, }); }
the_stack
import {Dispatch} from 'redux'; import * as api from '../api'; import {SnowAlertRule, State} from '../reducers/types'; import {Policy, Query, Suppression, Rule} from '../store/rules'; import {Action, ActionWithPayload, createAction, GetState} from './action-helpers'; import {ActionsUnion} from './types'; // load rules export const LOAD_SNOWALERT_RULES_REQUEST = 'LOAD_SNOWALERT_RULES_REQUEST'; export const LOAD_SNOWALERT_RULES_SUCCESS = 'LOAD_SNOWALERT_RULES_SUCCESS'; export const LOAD_SNOWALERT_RULES_FAILURE = 'LOAD_SNOWALERT_RULES_FAILURE'; export type LoadRulesPayload = ReadonlyArray<SnowAlertRule>; export const LoadRulesActions = { loadSnowAlertRulesRequest: () => createAction(LOAD_SNOWALERT_RULES_REQUEST), loadSnowAlertRulesSuccess: (response: LoadRulesPayload) => createAction(LOAD_SNOWALERT_RULES_SUCCESS, response), loadSnowAlertRulesFailure: (errorMessage: string) => createAction(LOAD_SNOWALERT_RULES_FAILURE, errorMessage), }; export type LoadRulesActions = ActionsUnion<typeof LoadRulesActions>; const shouldLoadSnowAlertRules = (state: State) => { const rules = state.rules; const numRulesLoaded = rules.suppressions.length + rules.queries.length + rules.policies.length; return !rules.isFetching && numRulesLoaded === 0; }; export const loadSnowAlertRules = () => async (dispatch: Dispatch, getState: GetState) => { const state = getState(); if (shouldLoadSnowAlertRules(state)) { dispatch(LoadRulesActions.loadSnowAlertRulesRequest()); try { const response = await api.loadSnowAlertRules(); dispatch(LoadRulesActions.loadSnowAlertRulesSuccess(response.rules)); } catch (error) { dispatch(LoadRulesActions.loadSnowAlertRulesFailure(error.message)); } } }; type RuleTarget = SnowAlertRule['target']; type RuleType = SnowAlertRule['type']; // changing rule title export const UPDATE_POLICY_TITLE = 'UPDATE_POLICY_TITLE'; export type UpdatePolicyTitleAction = ActionWithPayload< typeof UPDATE_POLICY_TITLE, {viewName: string; newTitle: string} >; export const updatePolicyTitle = (viewName: string, newTitle: string) => async (dispatch: Dispatch) => { dispatch(createAction(UPDATE_POLICY_TITLE, {viewName, newTitle})); }; // changing rule description export const UPDATE_POLICY_DESCRIPTION = 'UPDATE_POLICY_DESCRIPTION'; export type UpdatePolicyDescriptionAction = ActionWithPayload< typeof UPDATE_POLICY_DESCRIPTION, {viewName: string; newDescription: string} >; export const updatePolicyDescription = (viewName: string, newDescription: string) => async (dispatch: Dispatch) => { dispatch(createAction(UPDATE_POLICY_DESCRIPTION, {viewName, newDescription})); }; // adding new rule export const NEW_RULE = 'NEW_RULE'; export type NewRuleAction = ActionWithPayload<typeof NEW_RULE, {ruleTarget: RuleTarget; ruleType: RuleType}>; export const newRule = (ruleTarget: RuleTarget, ruleType: RuleType) => async (dispatch: Dispatch) => { dispatch(createAction(NEW_RULE, {ruleTarget, ruleType})); }; // edit rule export const EDIT_RULE = 'EDIT_RULE'; export type EditRuleAction = ActionWithPayload<typeof EDIT_RULE, string>; export const editRule = (ruleTitle?: string) => async (dispatch: Dispatch) => { dispatch(createAction(EDIT_RULE, ruleTitle)); }; // update rule export const UPDATE_RULE = 'UPDATE_RULE'; export type UpdateRuleAction = ActionWithPayload<typeof UPDATE_RULE, {ruleViewName: string; rule: Query | Suppression}>; export const updateRule = (ruleViewName: string, rule: Query | Suppression) => async (dispatch: Dispatch) => { dispatch(createAction(UPDATE_RULE, {ruleViewName, rule})); }; // revert rule export const REVERT_RULE = 'REVERT_RULE'; export type RevertRuleAction = ActionWithPayload<typeof REVERT_RULE, Policy>; export const revertRule = (policy?: Policy) => async (dispatch: Dispatch) => { dispatch(createAction(REVERT_RULE, policy)); }; // delete subpolicy export const DELETE_SUBPOLICY = 'DELETE_SUBPOLICY'; export type DeleteSubpolicyAction = ActionWithPayload<typeof DELETE_SUBPOLICY, {ruleTitle: string; i: number}>; export const deleteSubpolicy = (ruleTitle: string, i: number) => async (dispatch: Dispatch) => { dispatch(createAction(DELETE_SUBPOLICY, {ruleTitle, i})); }; // edit subpolicy export const EDIT_SUBPOLICY = 'EDIT_SUBPOLICY'; export type SubpolicyChange = {title?: string; condition?: string}; export type EditSubpolicyAction = ActionWithPayload< typeof EDIT_SUBPOLICY, {ruleTitle: string; i: number; change: SubpolicyChange} >; export const editSubpolicy = (ruleTitle: string, i: number, change: SubpolicyChange) => async (dispatch: Dispatch) => { dispatch(createAction(EDIT_SUBPOLICY, {ruleTitle, i, change})); }; // add subpolicy export const ADD_POLICY = 'ADD_POLICY'; export type AddPolicyAction = Action<typeof ADD_POLICY>; export const addPolicy = () => async (dispatch: Dispatch) => { dispatch(createAction(ADD_POLICY)); }; // add subpolicy export const ADD_SUBPOLICY = 'ADD_SUBPOLICY'; export type AddSubpolicyAction = ActionWithPayload<typeof ADD_SUBPOLICY, {ruleTitle: string}>; export const addSubpolicy = (ruleTitle: string) => async (dispatch: Dispatch) => { dispatch(createAction(ADD_SUBPOLICY, {ruleTitle})); }; // changing rule selection export const CHANGE_CURRENT_RULE = 'CHANGE_CURRENT_RULE'; export type ChangeRuleAction = ActionWithPayload<typeof CHANGE_CURRENT_RULE, string>; export const changeRule = (ruleTitle?: string) => async (dispatch: Dispatch) => { dispatch(createAction(CHANGE_CURRENT_RULE, ruleTitle)); }; // updating rule body export const CHANGE_CURRENT_RULE_BODY = 'CHANGE_CURRENT_RULE_BODY'; export type ChangeRuleBodyAction = ActionWithPayload<typeof CHANGE_CURRENT_RULE_BODY, {view: string; body: string}>; export const updateRuleBody = (ruleView: string, ruleBody: string | null) => async (dispatch: Dispatch) => { dispatch(createAction(CHANGE_CURRENT_RULE_BODY, {body: ruleBody, view: ruleView})); }; // updating filter export const CHANGE_CURRENT_FILTER = 'CHANGE_CURRENT_FILTER'; export type ChangeFilterAction = ActionWithPayload<typeof CHANGE_CURRENT_FILTER, string>; export const changeFilter = (filter: string | null) => async (dispatch: Dispatch) => { dispatch(createAction(CHANGE_CURRENT_FILTER, filter)); }; // add tag filter export const ADD_TAG_FILTER = 'ADD_TAG_FILTER'; export type AddTagFilterAction = ActionWithPayload<typeof ADD_TAG_FILTER, string>; export const addTagFilter = (tag: string) => async (dispatch: Dispatch) => { dispatch(createAction(ADD_TAG_FILTER, tag)); }; // remove tag filter export const REMOVE_TAG_FILTER = 'REMOVE_TAG_FILTER'; export type RemoveTagFilterAction = ActionWithPayload<typeof REMOVE_TAG_FILTER, string>; export const removeTagFilter = (tag: string) => async (dispatch: Dispatch) => { dispatch(createAction(REMOVE_TAG_FILTER, tag)); }; // saving rule body export const SAVE_RULE_REQUEST = 'SAVE_RULE_REQUEST'; export const SAVE_RULE_SUCCESS = 'SAVE_RULE_SUCCESS'; export const SAVE_RULE_FAILURE = 'SAVE_RULE_FAILURE'; export const SaveRuleAction = { saveRuleRequest: (rule: Rule) => createAction(SAVE_RULE_REQUEST, rule), saveRuleSuccess: (response: SnowAlertRule) => createAction(SAVE_RULE_SUCCESS, response), saveRuleFailure: (error: {message: string; rule: SnowAlertRule}) => createAction(SAVE_RULE_FAILURE, error), }; export type SaveRuleActions = ActionsUnion<typeof SaveRuleAction>; export const saveRule = (rule: Rule) => async (dispatch: Dispatch) => { dispatch(createAction(SAVE_RULE_REQUEST, rule)); try { const response = await api.saveRule(rule.raw); if (response.success) { dispatch(SaveRuleAction.saveRuleSuccess(response.rule)); } else { throw response; } } catch (error) { dispatch(SaveRuleAction.saveRuleFailure(error)); } }; export const DELETE_RULE_REQUEST = 'DELETE_RULE_REQUEST'; export const DELETE_RULE_SUCCESS = 'DELETE_RULE_SUCCESS'; export const DELETE_RULE_FAILURE = 'DELETE_RULE_FAILURE'; export const DeleteRuleAction = { deleteRuleRequest: () => createAction(DELETE_RULE_REQUEST), deleteRuleSuccess: (response: string) => createAction(DELETE_RULE_SUCCESS, response), deleteRuleFailure: (error: {message: string; rule: SnowAlertRule}) => createAction(DELETE_RULE_FAILURE, error), }; export type DeleteRuleActions = ActionsUnion<typeof DeleteRuleAction>; export const deleteRule = (rule: SnowAlertRule) => async (dispatch: Dispatch) => { dispatch(createAction(DELETE_RULE_REQUEST, rule)); try { const response = await api.deleteRule(rule); if (response.success) { dispatch(DeleteRuleAction.deleteRuleSuccess(response.view_name)); } else { throw response; } } catch (error) { dispatch(DeleteRuleAction.deleteRuleFailure(error)); } }; export const RENAME_RULE_REQUEST = 'RENAME_RULE_REQUEST'; export const RENAME_RULE_SUCCESS = 'RENAME_RULE_SUCCESS'; export const RENAME_RULE_FAILURE = 'RENAME_RULE_FAILURE'; export const RenameRuleAction = { renameRuleRequest: () => createAction(RENAME_RULE_REQUEST), renameRuleSuccess: (response: SnowAlertRule) => createAction(RENAME_RULE_SUCCESS, response), renameRuleFailure: (error: {message: string; rule: SnowAlertRule}) => createAction(RENAME_RULE_FAILURE, error), }; export type RenameRuleActions = ActionsUnion<typeof RenameRuleAction>; export const renameRule = (rule: SnowAlertRule) => async (dispatch: Dispatch) => { dispatch(createAction(RENAME_RULE_REQUEST, rule)); try { const response = await api.renameRule(rule); if (response.success) { dispatch(RenameRuleAction.renameRuleSuccess(response.rule)); } else { throw response; } } catch (error) { dispatch(RenameRuleAction.renameRuleFailure(error)); } }; export type EditRulesActions = | AddPolicyAction | AddSubpolicyAction | AddTagFilterAction | EditSubpolicyAction | ChangeRuleAction | ChangeRuleBodyAction | DeleteRuleActions | DeleteSubpolicyAction | EditRuleAction | UpdateRuleAction | RenameRuleActions | RemoveTagFilterAction | RevertRuleAction | SaveRuleActions | UpdatePolicyTitleAction | UpdatePolicyDescriptionAction | LoadRulesActions;
the_stack