text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { GridListItem } from './GridListItem'; import { IGridsterOptions } from '../IGridsterOptions'; const GridCol = function(lanes) { for (let i = 0; i < lanes; i++) { this.push(null); } }; // Extend the Array prototype GridCol.prototype = []; /** * A GridList manages the two-dimensional positions from a list of items, * within a virtual matrix. * * The GridList's main function is to convert the item positions from one * grid size to another, maintaining as much of their order as possible. * * The GridList's second function is to handle collisions when moving an item * over another. * * The positioning algorithm places items in columns. Starting from left to * right, going through each column top to bottom. * * The size of an item is expressed using the number of cols and rows it * takes up within the grid (w and h) * * The position of an item is express using the col and row position within * the grid (x and y) * * An item is an object of structure: * { * w: 3, h: 1, * x: 0, y: 1 * } */ export class GridList { items: Array<GridListItem>; grid: Array<Array<GridListItem>>; options: IGridsterOptions; constructor(items: Array<GridListItem>, options: IGridsterOptions) { this.options = options; this.items = items; this.adjustSizeOfItems(); this.generateGrid(); } /** * Illustrates grid as text-based table, using a number identifier for each * item. E.g. * * #| 0 1 2 3 4 5 6 7 8 9 10 11 12 13 * -------------------------------------------- * 0| 00 02 03 04 04 06 08 08 08 12 12 13 14 16 * 1| 01 -- 03 05 05 07 09 10 11 11 -- 13 15 -- * * Warn: Does not work if items don't have a width or height specified * besides their position in the grid. */ toString() { const widthOfGrid = this.grid.length; let output = '\n #|', border = '\n --', item, i, j; // Render the table header for (i = 0; i < widthOfGrid; i++) { output += ' ' + this.padNumber(i, ' '); border += '---'; } output += border; // Render table contents row by row, as we go on the y axis for (i = 0; i < this.options.lanes; i++) { output += '\n' + this.padNumber(i, ' ') + '|'; for (j = 0; j < widthOfGrid; j++) { output += ' '; item = this.grid[j][i]; output += item ? this.padNumber(this.items.indexOf(item), '0') : '--'; } } output += '\n'; return output; } setOption(name: string, value: any) { this.options[name] = value; } /** * Build the grid structure from scratch, with the current item positions */ generateGrid() { let i; this.resetGrid(); for (i = 0; i < this.items.length; i++) { this.markItemPositionToGrid(this.items[i]); } } resizeGrid(lanes: number) { let currentColumn = 0; this.options.lanes = lanes; this.adjustSizeOfItems(); this.sortItemsByPosition(); this.resetGrid(); // The items will be sorted based on their index within the this.items array, // that is their "1d position" for (let i = 0; i < this.items.length; i++) { const item = this.items[i], position = this.getItemPosition(item); this.updateItemPosition( item, this.findPositionForItem(item, { x: currentColumn, y: 0 }) ); // New items should never be placed to the left of previous items currentColumn = Math.max(currentColumn, position.x); } this.pullItemsToLeft(); } /** * This method has two options for the position we want for the item: * - Starting from a certain row/column number and only looking for * positions to its right * - Accepting positions for a certain row number only (use-case: items * being shifted to the left/right as a result of collisions) * * @param Object item * @param Object start Position from which to start * the search. * @param number [fixedRow] If provided, we're going to try to find a * position for the new item on it. If doesn't fit there, we're going * to put it on the first row. * * @returns Array x and y. */ findPositionForItem( item: GridListItem, start: { x: number; y: number }, fixedRow?: number ): Array<number> { let x, y, position; // Start searching for a position from the horizontal position of the // rightmost item from the grid for (x = start.x; x < this.grid.length; x++) { if (fixedRow !== undefined) { position = [x, fixedRow]; if (this.itemFitsAtPosition(item, position)) { return position; } } else { for (y = start.y; y < this.options.lanes; y++) { position = [x, y]; if (this.itemFitsAtPosition(item, position)) { return position; } } } } // If we've reached this point, we need to start a new column const newCol = this.grid.length; let newRow = 0; if ( fixedRow !== undefined && this.itemFitsAtPosition(item, [newCol, fixedRow]) ) { newRow = fixedRow; } return [newCol, newRow]; } moveAndResize( item: GridListItem, newPosition: Array<number>, size: { w: number; h: number } ) { const position = this.getItemPosition({ x: newPosition[0], y: newPosition[1], w: item.w, h: item.h }); const width = size.w || item.w, height = size.h || item.h; this.updateItemPosition(item, [position.x, position.y]); this.updateItemSize(item, width, height); this.resolveCollisions(item); } moveItemToPosition(item: GridListItem, newPosition: Array<number>) { const position = this.getItemPosition({ x: newPosition[0], y: newPosition[1], w: item.w, h: item.h }); this.updateItemPosition(item, [position.x, position.y]); this.resolveCollisions(item); } /** * Resize an item and resolve collisions. * * @param Object item A reference to an item that's part of the grid. * @param Object size * @param number [size.w=item.w] The new width. * @param number [size.h=item.h] The new height. */ resizeItem(item: GridListItem, size: { w: number; h: number }) { const width = size.w || item.w, height = size.h || item.h; this.updateItemSize(item, width, height); this.pullItemsToLeft(item); } /** * Compare the current items against a previous snapshot and return only * the ones that changed their attributes in the meantime. This includes both * position (x, y) and size (w, h) * * Each item that is returned is not the GridListItem but the helper that holds GridListItem * and list of changed properties. */ getChangedItems( initialItems: Array<GridListItem>, breakpoint? ): Array<{ item: GridListItem; changes: Array<string>; isNew: boolean; }> { return this.items .map((item: GridListItem) => { const changes = []; const oldValues: { x?: number; y?: number; w?: number; h?: number; } = {}; const initItem = initialItems.find( initItm => initItm.$element === item.$element ); if (!initItem) { return { item, changes: ['x', 'y', 'w', 'h'], isNew: true }; } const oldX = initItem.getValueX(breakpoint); if (item.getValueX(breakpoint) !== oldX) { changes.push('x'); if (oldX || oldX === 0) { oldValues.x = oldX; } } const oldY = initItem.getValueY(breakpoint); if (item.getValueY(breakpoint) !== oldY) { changes.push('y'); if (oldY || oldY === 0) { oldValues.y = oldY; } } if ( item.getValueW(breakpoint) !== initItem.getValueW(breakpoint) ) { changes.push('w'); oldValues.w = initItem.w; } if ( item.getValueH(breakpoint) !== initItem.getValueH(breakpoint) ) { changes.push('h'); oldValues.h = initItem.h; } return { item, oldValues, changes, isNew: false }; }) .filter( (itemChange: { item: GridListItem; changes: Array<string>; }) => { return itemChange.changes.length; } ); } resolveCollisions(item: GridListItem) { if (!this.tryToResolveCollisionsLocally(item)) { this.pullItemsToLeft(item); } if (this.options.floating) { this.pullItemsToLeft(); } else if (this.getItemsCollidingWithItem(item).length) { this.pullItemsToLeft(); } } pushCollidingItems(fixedItem?: GridListItem) { // Start a fresh grid with the fixed item already placed inside this.sortItemsByPosition(); this.resetGrid(); this.generateGrid(); this.items .filter(item => !this.isItemFloating(item) && item !== fixedItem) .forEach(item => { if (!this.tryToResolveCollisionsLocally(item)) { this.pullItemsToLeft(item); } }); } /** * Build the grid from scratch, by using the current item positions and * pulling them as much to the left as possible, removing as space between * them as possible. * * If a "fixed item" is provided, its position will be kept intact and the * rest of the items will be layed around it. */ pullItemsToLeft(fixedItem?) { if (this.options.direction === 'none') { return; } // Start a fresh grid with the fixed item already placed inside this.sortItemsByPosition(); this.resetGrid(); // Start the grid with the fixed item as the first positioned item if (fixedItem) { const fixedPosition = this.getItemPosition(fixedItem); this.updateItemPosition(fixedItem, [ fixedPosition.x, fixedPosition.y ]); } this.items .filter((item: GridListItem) => { return !item.dragAndDrop && item !== fixedItem; }) .forEach((item: GridListItem) => { const fixedPosition = this.getItemPosition(item); this.updateItemPosition(item, [ fixedPosition.x, fixedPosition.y ]); }); for (let i = 0; i < this.items.length; i++) { const item = this.items[i], position = this.getItemPosition(item); // The fixed item keeps its exact position if ( (fixedItem && item === fixedItem) || !item.dragAndDrop || (!this.options.floating && this.isItemFloating(item) && !this.getItemsCollidingWithItem(item).length) ) { continue; } const x = this.findLeftMostPositionForItem(item), newPosition = this.findPositionForItem( item, { x: x, y: 0 }, position.y ); this.updateItemPosition(item, newPosition); } } isOverFixedArea( x: number, y: number, w: number, h: number, item: GridListItem = null ): boolean { let itemData = { x, y, w, h }; if (this.options.direction !== 'horizontal') { itemData = { x: y, y: x, w: h, h: w }; } for (let i = itemData.x; i < itemData.x + itemData.w; i++) { for (let j = itemData.y; j < itemData.y + itemData.h; j++) { if ( this.grid[i] && this.grid[i][j] && this.grid[i][j] !== item && !this.grid[i][j].dragAndDrop ) { return true; } } } return false; } checkItemAboveEmptyArea( item: GridListItem, newPosition: { x: number; y: number } ) { let itemData = { x: newPosition.x, y: newPosition.y, w: item.w, h: item.h }; if ( !item.itemPrototype && item.x === newPosition.x && item.y === newPosition.y ) { return true; } if (this.options.direction === 'horizontal') { itemData = { x: newPosition.y, y: newPosition.x, w: itemData.h, h: itemData.w }; } return !this.checkItemsInArea( itemData.y, itemData.y + itemData.h - 1, itemData.x, itemData.x + itemData.w - 1, item ); } fixItemsPositions(options: IGridsterOptions) { // items with x, y that fits gird with size of options.lanes const validItems = this.items .filter((item: GridListItem) => item.itemComponent) .filter((item: GridListItem) => this.isItemValidForGrid(item, options) ); // items that x, y must be generated const invalidItems = this.items .filter((item: GridListItem) => item.itemComponent) .filter( (item: GridListItem) => !this.isItemValidForGrid(item, options) ); const gridList = new GridList([], options); // put items with defined positions to the grid gridList.items = validItems.map((item: GridListItem) => { return item.copyForBreakpoint(options.breakpoint); }); gridList.generateGrid(); invalidItems.forEach(item => { // TODO: check if this change does not broke anything // const itemCopy = item.copy(); const itemCopy = item.copyForBreakpoint(options.breakpoint); const position = gridList.findPositionForItem(itemCopy, { x: 0, y: 0 }); gridList.items.push(itemCopy); gridList.setItemPosition(itemCopy, position); gridList.markItemPositionToGrid(itemCopy); }); gridList.pullItemsToLeft(); gridList.pushCollidingItems(); this.items.forEach((itm: GridListItem) => { const cachedItem = gridList.items.filter(cachedItm => { return cachedItm.$element === itm.$element; })[0]; itm.setValueX(cachedItem.x, options.breakpoint); itm.setValueY(cachedItem.y, options.breakpoint); itm.setValueW(cachedItem.w, options.breakpoint); itm.setValueH(cachedItem.h, options.breakpoint); itm.autoSize = cachedItem.autoSize; }); } deleteItemPositionFromGrid(item: GridListItem) { const position = this.getItemPosition(item); let x, y; for (x = position.x; x < position.x + position.w; x++) { // It can happen to try to remove an item from a position not generated // in the grid, probably when loading a persisted grid of items. No need // to create a column to be able to remove something from it, though if (!this.grid[x]) { continue; } for (y = position.y; y < position.y + position.h; y++) { // Don't clear the cell if it's been occupied by a different widget in // the meantime (e.g. when an item has been moved over this one, and // thus by continuing to clear this item's previous position you would // cancel the first item's move, leaving it without any position even) if (this.grid[x][y] === item) { this.grid[x][y] = null; } } } } private isItemFloating(item) { if (item.itemComponent && item.itemComponent.isDragging) { return false; } const position = this.getItemPosition(item); if (position.x === 0) { return false; } const rowBelowItem = this.grid[position.x - 1]; return (rowBelowItem || []) .slice(position.y, position.y + position.h) .reduce((isFloating, cellItem) => { return isFloating && !cellItem; }, true); } private isItemValidForGrid(item: GridListItem, options: IGridsterOptions) { const itemData = options.direction === 'horizontal' ? { x: item.getValueY(options.breakpoint), y: item.getValueX(options.breakpoint), w: item.getValueH(options.breakpoint), h: Math.min( item.getValueW(this.options.breakpoint), options.lanes ) } : { x: item.getValueX(options.breakpoint), y: item.getValueY(options.breakpoint), w: Math.min( item.getValueW(this.options.breakpoint), options.lanes ), h: item.getValueH(options.breakpoint) }; return ( typeof itemData.x === 'number' && typeof itemData.y === 'number' && itemData.x + itemData.w <= options.lanes ); } private findDefaultPositionHorizontal(width: number, height: number) { for (const col of this.grid) { const colIdx = this.grid.indexOf(col); let rowIdx = 0; while (rowIdx < col.length - height + 1) { if ( !this.checkItemsInArea( colIdx, colIdx + width - 1, rowIdx, rowIdx + height - 1 ) ) { return [colIdx, rowIdx]; } rowIdx++; } } return [this.grid.length, 0]; } private findDefaultPositionVertical(width: number, height: number) { for (const row of this.grid) { const rowIdx = this.grid.indexOf(row); let colIdx = 0; while (colIdx < row.length - width + 1) { if ( !this.checkItemsInArea( rowIdx, rowIdx + height - 1, colIdx, colIdx + width - 1 ) ) { return [colIdx, rowIdx]; } colIdx++; } } return [0, this.grid.length]; } private checkItemsInArea( rowStart: number, rowEnd: number, colStart: number, colEnd: number, item?: GridListItem ) { for (let i = rowStart; i <= rowEnd; i++) { for (let j = colStart; j <= colEnd; j++) { if ( this.grid[i] && this.grid[i][j] && (item ? this.grid[i][j] !== item : true) ) { return true; } } } return false; } private sortItemsByPosition() { this.items.sort((item1, item2) => { const position1 = this.getItemPosition(item1), position2 = this.getItemPosition(item2); // Try to preserve columns. if (position1.x !== position2.x) { return position1.x - position2.x; } if (position1.y !== position2.y) { return position1.y - position2.y; } // The items are placed on the same position. return 0; }); } /** * Some items can have 100% height or 100% width. Those dimmensions are * expressed as 0. We need to ensure a valid width and height for each of * those items as the number of items per lane. */ private adjustSizeOfItems() { for (let i = 0; i < this.items.length; i++) { const item = this.items[i]; // This can happen only the first time items are checked. // We need the property to have a value for all the items so that the // `cloneItems` method will merge the properties properly. If we only set // it to the items that need it then the following can happen: // // cloneItems([{id: 1, autoSize: true}, {id: 2}], // [{id: 2}, {id: 1, autoSize: true}]); // // will result in // // [{id: 1, autoSize: true}, {id: 2, autoSize: true}] if (item.autoSize === undefined) { item.autoSize = item.w === 0 || item.h === 0; } if (item.autoSize) { if (this.options.direction === 'horizontal') { item.h = this.options.lanes; } else { item.w = this.options.lanes; } } } } private resetGrid() { this.grid = []; } /** * Check that an item wouldn't overlap with another one if placed at a * certain position within the grid */ private itemFitsAtPosition(item: GridListItem, newPosition) { const position = this.getItemPosition(item); let x, y; // No coordonate can be negative if (newPosition[0] < 0 || newPosition[1] < 0) { return false; } // Make sure the item isn't larger than the entire grid if ( newPosition[1] + Math.min(position.h, this.options.lanes) > this.options.lanes ) { return false; } if (this.isOverFixedArea(item.x, item.y, item.w, item.h)) { return false; } // Make sure the position doesn't overlap with an already positioned // item. for (x = newPosition[0]; x < newPosition[0] + position.w; x++) { const col = this.grid[x]; // Surely a column that hasn't even been created yet is available if (!col) { continue; } for (y = newPosition[1]; y < newPosition[1] + position.h; y++) { // Any space occupied by an item can continue to be occupied by the // same item. if (col[y] && col[y] !== item) { return false; } } } return true; } private updateItemPosition(item: GridListItem, position: Array<any>) { if (item.x !== null && item.y !== null) { this.deleteItemPositionFromGrid(item); } this.setItemPosition(item, position); this.markItemPositionToGrid(item); } /** * @param Object item A reference to a grid item. * @param number width The new width. * @param number height The new height. */ private updateItemSize(item: GridListItem, width, height) { if (item.x !== null && item.y !== null) { this.deleteItemPositionFromGrid(item); } item.w = width; item.h = height; this.markItemPositionToGrid(item); } /** * Mark the grid cells that are occupied by an item. This prevents items * from overlapping in the grid */ private markItemPositionToGrid(item: GridListItem) { const position = this.getItemPosition(item); let x, y; // Ensure that the grid has enough columns to accomodate the current item. this.ensureColumns(position.x + position.w); for (x = position.x; x < position.x + position.w; x++) { for (y = position.y; y < position.y + position.h; y++) { this.grid[x][y] = item; } } } /** * Ensure that the grid has at least N columns available. */ private ensureColumns(N) { for (let i = 0; i < N; i++) { if (!this.grid[i]) { this.grid.push(new GridCol(this.options.lanes)); } } } private getItemsCollidingWithItem(item: GridListItem): number[] { const collidingItems = []; for (let i = 0; i < this.items.length; i++) { if ( item !== this.items[i] && this.itemsAreColliding(item, this.items[i]) ) { collidingItems.push(i); } } return collidingItems; } private itemsAreColliding(item1: GridListItem, item2: GridListItem) { const position1 = this.getItemPosition(item1), position2 = this.getItemPosition(item2); return !( position2.x >= position1.x + position1.w || position2.x + position2.w <= position1.x || position2.y >= position1.y + position1.h || position2.y + position2.h <= position1.y ); } /** * Attempt to resolve the collisions after moving an item over one or more * other items within the grid, by shifting the position of the colliding * items around the moving one. This might result in subsequent collisions, * in which case we will revert all position permutations. To be able to * revert to the initial item positions, we create a virtual grid in the * process */ private tryToResolveCollisionsLocally(item: GridListItem) { const collidingItems = this.getItemsCollidingWithItem(item); if (!collidingItems.length) { return true; } const _gridList = new GridList( this.items.map(itm => { return itm.copy(); }), this.options ); let leftOfItem; let rightOfItem; let aboveOfItem; let belowOfItem; for (let i = 0; i < collidingItems.length; i++) { const collidingItem = _gridList.items[collidingItems[i]], collidingPosition = this.getItemPosition(collidingItem); // We use a simple algorithm for moving items around when collisions occur: // In this prioritized order, we try to move a colliding item around the // moving one: // 1. to its left side // 2. above it // 3. under it // 4. to its right side const position = this.getItemPosition(item); leftOfItem = [ position.x - collidingPosition.w, collidingPosition.y ]; rightOfItem = [position.x + position.w, collidingPosition.y]; aboveOfItem = [ collidingPosition.x, position.y - collidingPosition.h ]; belowOfItem = [collidingPosition.x, position.y + position.h]; if (_gridList.itemFitsAtPosition(collidingItem, leftOfItem)) { _gridList.updateItemPosition(collidingItem, leftOfItem); } else if ( _gridList.itemFitsAtPosition(collidingItem, aboveOfItem) ) { _gridList.updateItemPosition(collidingItem, aboveOfItem); } else if ( _gridList.itemFitsAtPosition(collidingItem, belowOfItem) ) { _gridList.updateItemPosition(collidingItem, belowOfItem); } else if ( _gridList.itemFitsAtPosition(collidingItem, rightOfItem) ) { _gridList.updateItemPosition(collidingItem, rightOfItem); } else { // Collisions failed, we must use the pullItemsToLeft method to arrange // the other items around this item with fixed position. This is our // plan B for when local collision resolving fails. return false; } } // If we reached this point it means we managed to resolve the collisions // from one single iteration, just by moving the colliding items around. So // we accept this scenario and merge the branched-out grid instance into the // original one this.items.forEach((itm: GridListItem, idx: number) => { const cachedItem = _gridList.items.filter(cachedItm => { return cachedItm.$element === itm.$element; })[0]; itm.x = cachedItem.x; itm.y = cachedItem.y; itm.w = cachedItem.w; itm.h = cachedItem.h; itm.autoSize = cachedItem.autoSize; }); this.generateGrid(); return true; } /** * When pulling items to the left, we need to find the leftmost position for * an item, with two considerations in mind: * - preserving its current row * - preserving the previous horizontal order between items */ private findLeftMostPositionForItem(item) { let tail = 0; const position = this.getItemPosition(item); for (let i = 0; i < this.grid.length; i++) { for (let j = position.y; j < position.y + position.h; j++) { const otherItem = this.grid[i][j]; if (!otherItem) { continue; } const otherPosition = this.getItemPosition(otherItem); if (this.items.indexOf(otherItem) < this.items.indexOf(item)) { tail = otherPosition.x + otherPosition.w; } } } return tail; } private findItemByPosition(x: number, y: number): GridListItem { for (let i = 0; i < this.items.length; i++) { if (this.items[i].x === x && this.items[i].y === y) { return this.items[i]; } } } private getItemByAttribute(key, value) { for (let i = 0; i < this.items.length; i++) { if (this.items[i][key] === value) { return this.items[i]; } } return null; } private padNumber(nr, prefix) { // Currently works for 2-digit numbers (<100) return nr >= 10 ? nr : prefix + nr; } /** * If the direction is vertical we need to rotate the grid 90 deg to the * left. Thus, we simulate the fact that items are being pulled to the top. * * Since the items have widths and heights, if we apply the classic * counter-clockwise 90 deg rotation * * [0 -1] * [1 0] * * then the top left point of an item will become the bottom left point of * the rotated item. To adjust for this, we need to subtract from the y * position the height of the original item - the width of the rotated item. * * However, if we do this then we'll reverse some actions: resizing the * width of an item will stretch the item to the left instead of to the * right; resizing an item that doesn't fit into the grid will push the * items around it instead of going on a new row, etc. * * We found it better to do a vertical flip of the grid after rotating it. * This restores the direction of the actions and greatly simplifies the * transformations. */ private getItemPosition(item: any) { if (this.options.direction === 'horizontal') { return item; } else { return { x: item.y, y: item.x, w: item.h, h: item.w }; } } /** * See getItemPosition. */ private setItemPosition(item, position) { if (this.options.direction === 'horizontal') { item.x = position[0]; item.y = position[1]; } else { // We're supposed to subtract the rotated item's height which is actually // the non-rotated item's width. item.x = position[1]; item.y = position[0]; } } }
the_stack
import { setupDevtoolsPlugin, TimelineEvent } from '@vue/devtools-api' import { App, ComponentPublicInstance, markRaw, toRaw, unref, watch, } from 'vue-demi' import { Pinia, PiniaPluginContext } from '../rootStore' import { GettersTree, MutationType, StateTree, ActionsTree, StoreGeneric, } from '../types' import { actionGlobalCopyState, actionGlobalPasteState, actionGlobalSaveState, actionGlobalOpenStateFile, } from './actions' import { formatDisplay, formatEventData, formatMutationType, formatStoreForInspectorState, formatStoreForInspectorTree, PINIA_ROOT_ID, PINIA_ROOT_LABEL, } from './formatting' import { isPinia, toastMessage } from './utils' // timeline can be paused when directly changing the state let isTimelineActive = true const componentStateTypes: string[] = [] const MUTATIONS_LAYER_ID = 'pinia:mutations' const INSPECTOR_ID = 'pinia' /** * Gets the displayed name of a store in devtools * * @param id - id of the store * @returns a formatted string */ const getStoreType = (id: string) => '🍍 ' + id /** * Add the pinia plugin without any store. Allows displaying a Pinia plugin tab * as soon as it is added to the application. * * @param app - Vue application * @param pinia - pinia instance */ export function registerPiniaDevtools(app: App, pinia: Pinia) { setupDevtoolsPlugin( { id: 'dev.esm.pinia', label: 'Pinia 🍍', logo: 'https://pinia.esm.dev/logo.svg', packageName: 'pinia', homepage: 'https://pinia.esm.dev', componentStateTypes, app, }, (api) => { api.addTimelineLayer({ id: MUTATIONS_LAYER_ID, label: `Pinia 🍍`, color: 0xe5df88, }) api.addInspector({ id: INSPECTOR_ID, label: 'Pinia 🍍', icon: 'storage', treeFilterPlaceholder: 'Search stores', actions: [ { icon: 'content_copy', action: () => { actionGlobalCopyState(pinia) }, tooltip: 'Serialize and copy the state', }, { icon: 'content_paste', action: async () => { await actionGlobalPasteState(pinia) api.sendInspectorTree(INSPECTOR_ID) api.sendInspectorState(INSPECTOR_ID) }, tooltip: 'Replace the state with the content of your clipboard', }, { icon: 'save', action: () => { actionGlobalSaveState(pinia) }, tooltip: 'Save the state as a JSON file', }, { icon: 'folder_open', action: async () => { await actionGlobalOpenStateFile(pinia) api.sendInspectorTree(INSPECTOR_ID) api.sendInspectorState(INSPECTOR_ID) }, tooltip: 'Import the state from a JSON file', }, ], }) api.on.inspectComponent((payload, ctx) => { const proxy = (payload.componentInstance && payload.componentInstance.proxy) as | ComponentPublicInstance | undefined if (proxy && proxy._pStores) { const piniaStores = ( payload.componentInstance.proxy as ComponentPublicInstance )._pStores! Object.values(piniaStores).forEach((store) => { payload.instanceData.state.push({ type: getStoreType(store.$id), key: 'state', editable: true, value: store.$state, }) if (store._getters && store._getters.length) { payload.instanceData.state.push({ type: getStoreType(store.$id), key: 'getters', editable: false, value: store._getters.reduce((getters, key) => { getters[key] = store[key] return getters }, {} as GettersTree<StateTree>), }) } }) } }) api.on.getInspectorTree((payload) => { if (payload.app === app && payload.inspectorId === INSPECTOR_ID) { let stores: Array<StoreGeneric | Pinia> = [pinia] stores = stores.concat(Array.from(pinia._s.values())) payload.rootNodes = ( payload.filter ? stores.filter((store) => '$id' in store ? store.$id .toLowerCase() .includes(payload.filter.toLowerCase()) : PINIA_ROOT_LABEL.toLowerCase().includes( payload.filter.toLowerCase() ) ) : stores ).map(formatStoreForInspectorTree) } }) api.on.getInspectorState((payload) => { if (payload.app === app && payload.inspectorId === INSPECTOR_ID) { const inspectedStore = payload.nodeId === PINIA_ROOT_ID ? pinia : pinia._s.get(payload.nodeId) if (!inspectedStore) { // this could be the selected store restored for a different project // so it's better not to say anything here return } if (inspectedStore) { payload.state = formatStoreForInspectorState(inspectedStore) } } }) api.on.editInspectorState((payload, ctx) => { if (payload.app === app && payload.inspectorId === INSPECTOR_ID) { const inspectedStore = payload.nodeId === PINIA_ROOT_ID ? pinia : pinia._s.get(payload.nodeId) if (!inspectedStore) { return toastMessage(`store "${payload.nodeId}" not found`, 'error') } const { path } = payload if (!isPinia(inspectedStore)) { // access only the state if ( path.length !== 1 || !inspectedStore._customProperties.has(path[0]) || path[0] in inspectedStore.$state ) { path.unshift('$state') } } else { path.unshift('state', 'value') } isTimelineActive = false payload.set(inspectedStore, path, payload.state.value) isTimelineActive = true } }) api.on.editComponentState((payload) => { if (payload.type.startsWith('🍍')) { const storeId = payload.type.replace(/^🍍\s*/, '') const store = pinia._s.get(storeId) if (!store) { return toastMessage(`store "${storeId}" not found`, 'error') } const { path } = payload if (path[0] !== 'state') { return toastMessage( `Invalid path for store "${storeId}":\n${path}\nOnly state can be modified.` ) } // rewrite the first entry to be able to directly set the state as // well as any other path path[0] = '$state' isTimelineActive = false payload.set(store, path, payload.state.value) isTimelineActive = true } }) } ) } function addStoreToDevtools(app: App, store: StoreGeneric) { if (!componentStateTypes.includes(getStoreType(store.$id))) { componentStateTypes.push(getStoreType(store.$id)) } setupDevtoolsPlugin( { id: 'dev.esm.pinia', label: 'Pinia 🍍', logo: 'https://pinia.esm.dev/logo.svg', packageName: 'pinia', homepage: 'https://pinia.esm.dev', componentStateTypes, app, }, (api) => { store.$onAction(({ after, onError, name, args }) => { const groupId = runningActionId++ api.addTimelineEvent({ layerId: MUTATIONS_LAYER_ID, event: { time: Date.now(), title: '🛫 ' + name, subtitle: 'start', data: { store: formatDisplay(store.$id), action: formatDisplay(name), args, }, groupId, }, }) after((result) => { activeAction = undefined api.addTimelineEvent({ layerId: MUTATIONS_LAYER_ID, event: { time: Date.now(), title: '🛬 ' + name, subtitle: 'end', data: { store: formatDisplay(store.$id), action: formatDisplay(name), args, result, }, groupId, }, }) }) onError((error) => { activeAction = undefined api.addTimelineEvent({ layerId: MUTATIONS_LAYER_ID, event: { time: Date.now(), logType: 'error', title: '💥 ' + name, subtitle: 'end', data: { store: formatDisplay(store.$id), action: formatDisplay(name), args, error, }, groupId, }, }) }) }, true) store._customProperties.forEach((name) => { watch( () => unref(store[name]), (newValue, oldValue) => { api.notifyComponentUpdate() api.sendInspectorState(INSPECTOR_ID) if (isTimelineActive) { api.addTimelineEvent({ layerId: MUTATIONS_LAYER_ID, event: { time: Date.now(), title: 'Change', subtitle: name, data: { newValue, oldValue, }, groupId: activeAction, }, }) } }, { deep: true } ) }) store.$subscribe( ({ events, type }, state) => { api.notifyComponentUpdate() api.sendInspectorState(INSPECTOR_ID) if (!isTimelineActive) return // rootStore.state[store.id] = state const eventData: TimelineEvent = { time: Date.now(), title: formatMutationType(type), data: { store: formatDisplay(store.$id), ...formatEventData(events), }, groupId: activeAction, } // reset for the next mutation activeAction = undefined if (type === MutationType.patchFunction) { eventData.subtitle = '⤵️' } else if (type === MutationType.patchObject) { eventData.subtitle = '🧩' } else if (events && !Array.isArray(events)) { eventData.subtitle = events.type } if (events) { eventData.data['rawEvent(s)'] = { _custom: { display: 'DebuggerEvent', type: 'object', tooltip: 'raw DebuggerEvent[]', value: events, }, } } api.addTimelineEvent({ layerId: MUTATIONS_LAYER_ID, event: eventData, }) }, { detached: true, flush: 'sync' } ) const hotUpdate = store._hotUpdate store._hotUpdate = markRaw((newStore) => { hotUpdate(newStore) api.addTimelineEvent({ layerId: MUTATIONS_LAYER_ID, event: { time: Date.now(), title: '🔥 ' + store.$id, subtitle: 'HMR update', data: { store: formatDisplay(store.$id), info: formatDisplay(`HMR update`), }, }, }) // update the devtools too api.notifyComponentUpdate() api.sendInspectorTree(INSPECTOR_ID) api.sendInspectorState(INSPECTOR_ID) }) const { $dispose } = store store.$dispose = () => { $dispose() api.notifyComponentUpdate() api.sendInspectorTree(INSPECTOR_ID) api.sendInspectorState(INSPECTOR_ID) toastMessage(`Disposed "${store.$id}" store 🗑`) } // trigger an update so it can display new registered stores api.notifyComponentUpdate() api.sendInspectorTree(INSPECTOR_ID) api.sendInspectorState(INSPECTOR_ID) toastMessage(`"${store.$id}" store installed 🆕`) } ) } let runningActionId = 0 let activeAction: number | undefined /** * Patches a store to enable action grouping in devtools by wrapping the store with a Proxy that is passed as the context of all actions, allowing us to set `runningAction` on each access and effectively associating any state mutation to the action. * * @param store - store to patch * @param actionNames - list of actionst to patch */ function patchActionForGrouping(store: StoreGeneric, actionNames: string[]) { // original actions of the store as they are given by pinia. We are going to override them const actions = actionNames.reduce((storeActions, actionName) => { // use toRaw to avoid tracking #541 storeActions[actionName] = toRaw(store)[actionName] return storeActions }, {} as ActionsTree) for (const actionName in actions) { store[actionName] = function () { // setActivePinia(store._p) // the running action id is incremented in a before action hook const _actionId = runningActionId const trackedStore = new Proxy(store, { get(...args) { activeAction = _actionId return Reflect.get(...args) }, set(...args) { activeAction = _actionId return Reflect.set(...args) }, }) return actions[actionName].apply( trackedStore, arguments as unknown as any[] ) } } } /** * pinia.use(devtoolsPlugin) */ export function devtoolsPlugin< Id extends string = string, S extends StateTree = StateTree, G /* extends GettersTree<S> */ = GettersTree<S>, A /* extends ActionsTree */ = ActionsTree >({ app, store, options }: PiniaPluginContext<Id, S, G, A>) { // HMR module if (store.$id.startsWith('__hot:')) { return } // only wrap actions in option-defined stores as this technique relies on // wrapping the context of the action with a proxy if (typeof options.state === 'function') { patchActionForGrouping( // @ts-expect-error: can cast the store... store, Object.keys(options.actions) ) const originalHotUpdate = store._hotUpdate // Upgrade the HMR to also update the new actions toRaw(store)._hotUpdate = function (newStore) { originalHotUpdate.apply(this, arguments as any) patchActionForGrouping( store as StoreGeneric, Object.keys(newStore._hmrPayload.actions) ) } } addStoreToDevtools( app, // FIXME: is there a way to allow the assignment from Store<Id, S, G, A> to StoreGeneric? store as StoreGeneric ) }
the_stack
import { RequestHandler0, RequestHandler, ProgressType } from 'vscode-jsonrpc'; import { TextDocumentIdentifier, Diagnostic, DocumentUri, integer } from 'vscode-languageserver-types'; import * as Is from './utils/is'; import { ProtocolRequestType0, ProtocolRequestType } from './messages'; import { PartialResultParams, StaticRegistrationOptions, WorkDoneProgressParams, TextDocumentRegistrationOptions, WorkDoneProgressOptions, TextDocumentClientCapabilities } from './protocol'; /** * @since 3.17.0 - proposed state */ export interface DiagnosticClientCapabilities { /** * Whether implementation supports dynamic registration. If this is set to `true` * the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` * return value for the corresponding server capability as well. */ dynamicRegistration?: boolean; /** * Whether the clients supports related documents for document diagnostic pulls. */ relatedDocumentSupport?: boolean; } export interface $DiagnosticClientCapabilities { textDocument?: TextDocumentClientCapabilities & { diagnostic?: DiagnosticClientCapabilities; } } /** * Diagnostic options. * * @since 3.17.0 - proposed state */ export interface DiagnosticOptions extends WorkDoneProgressOptions { /** * An optional identifier under which the diagnostics are * managed by the client. */ identifier?: string; /** * Whether the language has inter file dependencies meaning that * editing code in one file can result in a different diagnostic * set in another file. Inter file dependencies are common for * most programming languages and typically uncommon for linters. */ interFileDependencies: boolean; /** * The server provides support for workspace diagnostics as well. */ workspaceDiagnostics: boolean; } /** * Diagnostic registration options. * * @since 3.17.0 - proposed state */ export interface DiagnosticRegistrationOptions extends TextDocumentRegistrationOptions, DiagnosticOptions, StaticRegistrationOptions { } export interface $DiagnosticServerCapabilities { diagnosticProvider?: DiagnosticOptions; } /** * Cancellation data returned from a diagnostic request. * * @since 3.17.0 - proposed state */ export interface DiagnosticServerCancellationData { retriggerRequest: boolean; } /** * @since 3.17.0 - proposed state */ export namespace DiagnosticServerCancellationData { export function is(value: any): value is DiagnosticServerCancellationData { const candidate = value as DiagnosticServerCancellationData; return candidate && Is.boolean(candidate.retriggerRequest); } } /** * Parameters of the document diagnostic request. * * @since 3.17.0 - proposed state */ export interface DocumentDiagnosticParams extends WorkDoneProgressParams, PartialResultParams { /** * The text document. */ textDocument: TextDocumentIdentifier; /** * The additional identifier provided during registration. */ identifier?: string; /** * The result id of a previous response if provided. */ previousResultId?: string; } /** * The document diagnostic report kinds. * * @since 3.17.0 - proposed state */ export enum DocumentDiagnosticReportKind { /** * A diagnostic report with a full * set of problems. */ full = 'full', /** * A report indicating that the last * returned report is still accurate. */ unChanged = 'unChanged' } /** * A diagnostic report with a full set of problems. * * @since 3.17.0 - proposed state */ export interface FullDocumentDiagnosticReport { /** * A full document diagnostic report. */ kind: DocumentDiagnosticReportKind.full; /** * An optional result id. If provided it will * be sent on the next diagnostic request for the * same document. */ resultId?: string; /** * The actual items. */ items: Diagnostic[]; } /** * A full diagnostic report with a set of related documents. * * @since 3.17.0 - proposed state */ export interface RelatedFullDocumentDiagnosticReport extends FullDocumentDiagnosticReport { /** * Diagnostics of related documents. This information is useful * in programming languages where code in a file A can generate * diagnostics in a file B which A depends on. An example of * such a language is C/C++ where marco definitions in a file * a.cpp and result in errors in a header file b.hpp. * * @since 3.17.0 - proposed state */ relatedDocuments?: { [uri: string /** DocumentUri */]: FullDocumentDiagnosticReport | UnchangedDocumentDiagnosticReport; } } /** * A diagnostic report indicating that the last returned * report is still accurate. * * @since 3.17.0 - proposed state */ export interface UnchangedDocumentDiagnosticReport { /** * A document diagnostic report indicating * no changes to the last result. A server can * only return `unchanged` if result ids are * provided. */ kind: DocumentDiagnosticReportKind.unChanged; /** * A result id which will be sent on the next * diagnostic request for the same document. */ resultId: string; } /** * An unchanged diagnostic report with a set of related documents. * * @since 3.17.0 - proposed state */ export interface RelatedUnchangedDocumentDiagnosticReport extends UnchangedDocumentDiagnosticReport { /** * Diagnostics of related documents. This information is useful * in programming languages where code in a file A can generate * diagnostics in a file B which A depends on. An example of * such a language is C/C++ where marco definitions in a file * a.cpp and result in errors in a header file b.hpp. * * @since 3.17.0 - proposed state */ relatedDocuments?: { [uri: string /** DocumentUri */]: FullDocumentDiagnosticReport | UnchangedDocumentDiagnosticReport; } } /** * The result of a document diagnostic pull request. A report can * either be a full report containing all diagnostics for the * requested document or a unchanged report indicating that nothing * has changed in terms of diagnostics in comparison to the last * pull request. * * @since 3.17.0 - proposed state */ export type DocumentDiagnosticReport = RelatedFullDocumentDiagnosticReport | RelatedUnchangedDocumentDiagnosticReport; /** * A partial result for a document diagnostic report. * * @since 3.17.0 - proposed state */ export interface DocumentDiagnosticReportPartialResult { relatedDocuments: { [uri: string /** DocumentUri */]: FullDocumentDiagnosticReport | UnchangedDocumentDiagnosticReport; } } /** * The document diagnostic request definition. * * @since 3.17.0 - proposed state */ export namespace DocumentDiagnosticRequest { export const method: 'textDocument/diagnostic' = 'textDocument/diagnostic'; export const type = new ProtocolRequestType<DocumentDiagnosticParams, DocumentDiagnosticReport, DocumentDiagnosticReportPartialResult, DiagnosticServerCancellationData, DiagnosticRegistrationOptions>(method); export const partialResult = new ProgressType<DocumentDiagnosticReportPartialResult>(); export type HandlerSignature = RequestHandler<DocumentDiagnosticParams, DocumentDiagnosticReport, void>; } /** * A previous result id in a workspace pull request. * * @since 3.17.0 - proposed state */ export type PreviousResultId = { /** * The URI for which the client knowns a * result id. */ uri: DocumentUri; /** * The value of the previous result id. */ value: string; }; /** * Parameters of the workspace diagnostic request. * * @since 3.17.0 - proposed state */ export interface WorkspaceDiagnosticParams extends WorkDoneProgressParams, PartialResultParams { /** * The additional identifier provided during registration. */ identifier?: string; /** * The currently known diagnostic reports with their * previous result ids. */ previousResultIds: PreviousResultId[]; } /** * A full document diagnostic report for a workspace diagnostic result. * * @since 3.17.0 - proposed state */ export interface WorkspaceFullDocumentDiagnosticReport extends FullDocumentDiagnosticReport { /** * The URI for which diagnostic information is reported. */ uri: DocumentUri; /** * The version number for which the diagnostics are reported. * If the document is not marked as open `null` can be provided. */ version: integer | null; } /** * An unchanged document diagnostic report for a workspace diagnostic result. * * @since 3.17.0 - proposed state */ export interface WorkspaceUnchangedDocumentDiagnosticReport extends UnchangedDocumentDiagnosticReport { /** * The URI for which diagnostic information is reported. */ uri: DocumentUri; /** * The version number for which the diagnostics are reported. * If the document is not marked as open `null` can be provided. */ version: integer | null; } /** * A workspace diagnostic document report. * * @since 3.17.0 - proposed state */ export type WorkspaceDocumentDiagnosticReport = WorkspaceFullDocumentDiagnosticReport | WorkspaceUnchangedDocumentDiagnosticReport; /** * A workspace diagnostic report. * * @since 3.17.0 - proposed state */ export interface WorkspaceDiagnosticReport { items: WorkspaceDocumentDiagnosticReport[]; } /** * A partial result for a workspace diagnostic report. * * @since 3.17.0 - proposed state */ export interface WorkspaceDiagnosticReportPartialResult { items: WorkspaceDocumentDiagnosticReport[]; } /** * The workspace diagnostic request definition. * * @since 3.17.0 - proposed state */ export namespace WorkspaceDiagnosticRequest { export const method: 'workspace/diagnostic' = 'workspace/diagnostic'; export const type = new ProtocolRequestType<WorkspaceDiagnosticParams, WorkspaceDiagnosticReport, WorkspaceDiagnosticReportPartialResult, DiagnosticServerCancellationData, void>(method); export const partialResult = new ProgressType<WorkspaceDiagnosticReportPartialResult>(); export type HandlerSignature = RequestHandler<WorkspaceDiagnosticParams, WorkspaceDiagnosticReport | null, void>; } /** * The diagnostic refresh request definition. * * @since 3.17.0 - proposed state */ export namespace DiagnosticRefreshRequest { export const method: `workspace/diagnostic/refresh` = `workspace/diagnostic/refresh`; export const type = new ProtocolRequestType0<void, void, void, void>(method); export type HandlerSignature = RequestHandler0<void, void>; }
the_stack
import * as BluebirdPromise from 'bluebird'; import { app, ipcMain, session } from 'electron'; import log from 'electron-log'; import { omit } from 'ramda'; import { Observable } from 'rxjs/Observable'; import { fromEvent } from 'rxjs/observable/fromEvent'; import { Subject } from 'rxjs/Subject'; import { sendToAllWebcontents } from '../../../lib/ipc-broadcast'; import { ServiceSubscription } from '../../lib/class'; import { observer } from '../../lib/helpers'; import { RPC } from '../../lib/types'; import { addOnCloseObserver, addOnDestroyedObserver, addOnDomReadyObserver, addOnNavigateObserver, addOnNewNotificationObserver, addOnNotificationCloseObserver, addOnPreventUnload, awaitDomReady, getWebContentsFromIdOrThrow, handleHackGoogleAppsURLs, } from './api'; import { AlertDialogProviderService, BasicAuthDetailsProviderService, TabWebContentsAutoLoginDetailsProviderService, TabWebContentsGlobalObserver, TabWebContentsLifeCycleObserver, TabWebContentsNotificationsObserver, TabWebContentsPrintObserver, TabWebContentsService, UrlDispatcherProviderService, WebContentsOverrideProviderService, } from './interface'; export class TabWebContentsServiceImpl extends TabWebContentsService implements RPC.Interface<TabWebContentsService> { protected webviews: Subject<Electron.WebContents>; protected askAutoLogin: Subject<number>; protected requestId: number | null; protected loop: boolean; constructor(uuid?: string) { super(uuid); this.webviews = new Subject(); this.askAutoLogin = new Subject(); this.requestId = null; this.loop = false; this.initWebviewsListener(); } initWebviewsListener() { app.on('web-contents-created', async (_e: any, contents: Electron.WebContents) => { if ((contents as any).getType() === 'webview') { this.webviews.next(contents); } }); } async clearHistory(webContentsId: number) { (await getWebContentsFromIdOrThrow(webContentsId)).clearHistory(); } async loadURL(webContentsId: number, url: string) { (await getWebContentsFromIdOrThrow(webContentsId)).loadURL(url); } async querySpellchecker(webContentsId: number, misspelledWord: string) { const wc = await getWebContentsFromIdOrThrow(webContentsId); return await new BluebirdPromise<string[]>(resolve => { ipcMain.once('spellchecker-get-correction-response', (_e: any, corrections: string[]) => resolve(corrections)); wc.send('spellchecker-get-correction', misspelledWord); }) .timeout(200) .catch(BluebirdPromise.TimeoutError, () => { log.warn('querySpellcheckerInWebContents timeouts'); return []; }); } async print(webContentsId: number) { (await getWebContentsFromIdOrThrow(webContentsId)).print(); } async setZoomLevel(webContentsId: number, zoomLevel: number) { (await getWebContentsFromIdOrThrow(webContentsId)).setZoomLevel(zoomLevel); } async findInPage(webContentsId: number, searchString: string, options?: Electron.FindInPageOptions) { const wc = await getWebContentsFromIdOrThrow(webContentsId); return new Promise<Electron.Result>(resolve => { if (wc.isDestroyed()) return resolve(); wc.once('found-in-page', (_e: any, result: Electron.Result) => { // We have a weird behaviour that we haven't successfully reproduced in fiddle yet. // When the search reached its last result, and we try to find the next one (which doesn't exist), // the main process freezes. // The fix is to loop the search like in Chromium, so when we have reached the end, // we clear the results and start a fresh search. this.loop = result.matches === result.activeMatchOrdinal; this.requestId = null; resolve(result); }); let opts = options; if (this.loop) { this.loop = false; opts = omit(['findNext'], options); } this.requestId = wc.findInPage(searchString, opts); }); } async stopFindInPage(webContentsId: number) { (await getWebContentsFromIdOrThrow(webContentsId)).stopFindInPage('clearSelection'); } async executeJavaScript(webContentsId: number, code: string, userGesture?: boolean) { const wc = await getWebContentsFromIdOrThrow(webContentsId); await awaitDomReady(wc); return wc.executeJavaScript(code, userGesture); } async askAutoLoginCredentials(webContentsId: number) { this.askAutoLogin.next(webContentsId); } // PROVIDERS async setAlertDialogProvider(provider: RPC.Node<AlertDialogProviderService>) { return new ServiceSubscription(this.onNewWebviews().subscribe(wc => { return fromEvent(wc, 'ipc-message-sync', (event, channel, props) => ({ event, channel, props })) .filter(({ channel }) => channel === 'window-alert') .subscribe(async ({ event, props }) => { await provider.show(wc.id, props); if (event && event.sendReply) { event.sendReply([]); } }); })); } async setAutoLoginDetailsProvider(provider: RPC.Node<TabWebContentsAutoLoginDetailsProviderService>) { const shared = this.onNewWebviews().share(); return new ServiceSubscription([ this.askAutoLogin.subscribe(async (webContentsId: number) => { const wc = await getWebContentsFromIdOrThrow(webContentsId); const { account, canAutoSubmit } = await provider.getCredentials(wc.id); if (account) { wc.focus(); wc.send('autologin-value-retrieved', account, canAutoSubmit); } }), shared.subscribe(wc => { return fromEvent(wc, 'ipc-message', (_e, channel) => channel) .filter(channel => channel === 'autologin-get-credentials') .subscribe(() => { return this.askAutoLoginCredentials(wc.id); }); }), shared.subscribe(wc => { return fromEvent(wc, 'ipc-message', (_e, channel) => channel) .filter(channel => channel === 'autologin-display-removeLinkBanner') .subscribe(async () => { await provider.showRemoveLinkBanner(wc.id); }); }), shared.subscribe(wc => { return fromEvent(wc, 'did-navigate') .subscribe(async () => { await provider.hideBanners(wc.id); }); }), shared.subscribe(wc => { return fromEvent(wc, 'did-navigate-in-page') .subscribe(async () => { await provider.hideBanners(wc.id); }); }), ]); } async setBasicAuthDetailsProvider(provider: RPC.Node<BasicAuthDetailsProviderService>) { return new ServiceSubscription(this.onNewWebviews().subscribe(wc => { return fromEvent(wc, 'login', (event, _request, authInfo, callback) => ({ event, authInfo, callback })) .subscribe(async ({ event, authInfo, callback }) => { event.preventDefault(); const { username, password } = await provider.getAuthData(wc.id, authInfo); callback(username, password); }); })); } async setWebContentsOverrideProvider(provider: RPC.Node<WebContentsOverrideProviderService>) { return new ServiceSubscription(this.onNewWebviews().subscribe(async wc => { const data = await provider.getOverrideData(wc.id); if (data.userAgent) { let userAgentWithRealOS = data.userAgent; const defaultUserAgent = session.defaultSession?.getUserAgent(); const baseOSUserAgent = defaultUserAgent?.match(/\(([^()]*)\)/m); // Preventing any pb about the non respect of UserAgent format,prefer to have a valid one in all cases if (baseOSUserAgent && baseOSUserAgent.length > 1) { userAgentWithRealOS = data.userAgent.replace(/\(([^()]*)\)/m, baseOSUserAgent[0]); } wc.setUserAgent(userAgentWithRealOS); } })); } async setUrlDispatcherProvider(provider: RPC.Node<UrlDispatcherProviderService>) { return new ServiceSubscription(this.onNewWebviews().subscribe(wc => { return fromEvent(wc, 'new-window', (event, url, _, disposition, options) => ({ event, url, disposition, options })) .subscribe(async ({ event, url, disposition, options }) => { if (disposition === 'new-window') { if (options) { options.fullscreen = false; } } else if (disposition === 'foreground-tab' && String(url).startsWith('about:blank')) { // Gmail PDF hack. Will download a printed PDF from thumbnail // EDIT: not only Gmail or just PDF but most of the URL link on a Google app with overriden User Agent // also falls here event.preventDefault(); const guest = await handleHackGoogleAppsURLs(event, options); if (guest) { // not a download const newWindowUrl = guest.webContents.getURL(); if (newWindowUrl.startsWith('about:blank')) { // if popup is still blank after 2 seconds, we show it to let it finish guest.show(); } else { guest.close(); // otherwise dispatch the current URL of the guest window into our URLRouter await provider.dispatchUrl(newWindowUrl, wc.id); } } } else { event.preventDefault(); await provider.dispatchUrl(url, wc.id); } }); })); } // OBSERVERS async addGlobalObserver(obs: RPC.ObserverNode<TabWebContentsGlobalObserver>) { if (obs.onNewWebview) { return new ServiceSubscription( this.webviews.asObservable() .subscribe(wc => { obs.onNewWebview!(wc.id); }), obs ); } return ServiceSubscription.noop; } async addLifeCycleObserver(webContentsId: number, obs: RPC.ObserverNode<TabWebContentsLifeCycleObserver>) { const wc = await getWebContentsFromIdOrThrow(webContentsId); const sub = new ServiceSubscription([ addOnDestroyedObserver(wc, obs), addOnDomReadyObserver(wc, obs), addOnCloseObserver(wc, obs), addOnNavigateObserver(wc, obs), addOnPreventUnload(wc, obs), ], obs); wc.once('destroyed', () => { sub.unsubscribe(); // Can be leveraged by worker to simply know when a webcontents is destroyed sendToAllWebcontents(`wc-destroyed-${webContentsId}`); }); return sub; } async addNotificationsObserver(webContentsId: number, obs: RPC.ObserverNode<TabWebContentsNotificationsObserver>) { const wc = await getWebContentsFromIdOrThrow(webContentsId); const sub = new ServiceSubscription([ addOnNewNotificationObserver(wc, obs), addOnNotificationCloseObserver(wc, obs), ], obs); wc.once('destroyed', () => { sub.unsubscribe(); }); return sub; } async addPrintObserver(webContentsId: number, obs: RPC.ObserverNode<TabWebContentsPrintObserver>) { const wc = await getWebContentsFromIdOrThrow(webContentsId); if (!wc) return ServiceSubscription.noop; if (obs.onPrint) { const sub = new ServiceSubscription( fromEvent(wc, 'ipc-message', (_e, channel) => channel) .filter(channel => channel === 'print') .subscribe(() => { obs.onPrint!(); }), obs ); wc.once('destroyed', () => { sub.unsubscribe(); }); return sub; } return ServiceSubscription.noop; } // Easily use local new webviews observer as an Observable protected onNewWebviews() { return new Observable<Electron.WebContents>(o => { this.addGlobalObserver(observer({ async onNewWebview(webContentsId: number) { const wc = await getWebContentsFromIdOrThrow(webContentsId); try { o.next(wc); } catch (e) { o.error(e); } }, })).catch(e => o.error(e)); }); } }
the_stack
import {KSeq, OpKind, InsertOp, RemoveOp} from '../src'; import {Ident} from '../src/idents'; import {assert} from 'chai'; function getWallTime(): number { return Math.floor(new Date().valueOf() / 1000); } function randomize(arr) { for (let i = arr.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } describe("KSeq", () => { //-------------------------------------------------------------------------------- describe("constructor()", () => { it("returns a KSeq instance", () => { let seq = new KSeq<string>("test"); assert.isNotNull(seq); }); it("assigns the replica id to the KSeq instance", () => { let name = Math.floor(Math.random() * 100000).toString(); let seq = new KSeq<string>(name); assert.equal(name, seq.name); }); }); //-------------------------------------------------------------------------------- describe("insert()", () => { describe("when the position is negative", () => { it("throws a RangeError", () => { let seq = new KSeq<string>("test"); let func = () => { seq.insert('a', -1); }; assert.throws(func, RangeError); }); }); it("returns a valid InsertOp for the operation", () => { let seq = new KSeq<string>("test"); let op = seq.insert('a', 0); assert.equal(op.kind, OpKind.Insert); assert.equal(op.value, 'a'); }); it("can add an atom to the end of the sequence", () => { let seq = new KSeq<string>("test"); seq.insert('a', 0); seq.insert('b', 1); assert.equal(seq.size(), 2); assert.equal(seq.get(0), 'a'); assert.equal(seq.get(1), 'b'); }); it("can add an atom to the beginning of the sequence", () => { let seq = new KSeq<string>("test"); seq.insert('a', 0); seq.insert('b', 1); seq.insert('c', 0); assert.equal(seq.size(), 3); assert.equal(seq.get(0), 'c'); assert.equal(seq.get(1), 'a'); assert.equal(seq.get(2), 'b'); }); it("can add 1000 items at the end", () => { let seq = new KSeq<number>("test"); for (let i = 1; i <= 1000; i++) { seq.insert(i, seq.size()); } assert.equal(seq.size(), 1000); assert.equal(seq.get(seq.size() - 1), 1000); }); it("can add 1000 items at the beginning", () => { let seq = new KSeq<number>("test"); for (let i = 1; i <= 1000; i++) { seq.insert(i, 0); } assert.equal(seq.size(), 1000); assert.equal(seq.get(0), 1000); }); }); //-------------------------------------------------------------------------------- describe("remove()", () => { describe("when the position is negative", () => { it("throws a RangeError", () => { let seq = new KSeq<string>("test"); let func = () => { seq.remove(-1); }; assert.throws(func, RangeError); }); }); describe("when the position is out of range", () => { it("returns null", () => { let seq = new KSeq<string>("test"); let ret = seq.remove(100); assert.equal(ret, null); }); }); describe("when an atom exists at the position", () => { it("returns a valid RemoveOp for the operation", () => { let seq = new KSeq<string>("test"); seq.insert('a', 0); assert.equal(seq.get(0), 'a'); let op = seq.remove(0); assert.equal(op.kind, OpKind.Remove); }); it("removes the atom at that position", () => { let seq = new KSeq<string>("test"); seq.insert('a', 0); seq.insert('b', 1); seq.insert('c', 2); assert.equal(seq.size(), 3); seq.remove(1); assert.equal(seq.size(), 2); assert.equal(seq.get(1), 'c'); }); }); }); //-------------------------------------------------------------------------------- describe("apply()", () => { describe("when passed an InsertOp", () => { describe("when the specified atom does not exist", () => { it("adds the atom", () => { let seq1 = new KSeq<string>("alice"); let seq2 = new KSeq<string>("bob"); let op = seq1.insert('a', 0); seq2.apply(op); assert.equal(seq2.size(), 1); assert.equal(seq2.get(0), 'a'); }); }); describe("when an atom with the specified ident already exists", () => { it("ignores the operation", () => { let seq = new KSeq<number>("test"); let op1 = seq.insert(42, 0); assert.equal(seq.size(), 1); assert.equal(seq.get(0), 42); let op2 = new InsertOp("test", getWallTime(), op1.id, 99); seq.apply(op2); assert.equal(seq.size(), 1); }); }); describe("when an atom with the specified ident has already been removed", () => { it("ignores the operation", () => { let seq = new KSeq<number>("test"); let op1 = seq.append(42); seq.append(99); seq.remove(0); assert.equal(seq.size(), 1); let op2 = new InsertOp("test", getWallTime(), op1.id, 123); seq.apply(op2); assert.equal(seq.size(), 1); }); }); }); describe("when passed a RemoveOp", () => { describe("when the specified atom does not exist", () => { it("ignores the operation", () => { let seq1 = new KSeq<string>("alice"); let seq2 = new KSeq<string>("bob"); seq1.insert('a', 0); seq2.insert('b', 0); let op = seq1.remove(0); assert.isNotNull(op); seq2.apply(op); assert.equal(seq2.size(), 1); assert.equal(seq2.get(0), 'b'); }); }); describe("when the specified atom exists", () => { it("removes the atom", () => { let seq1 = new KSeq<number>("alice"); let seq2 = new KSeq<number>("bob"); let insertOp = seq1.insert(42, 0); seq2.apply(insertOp); assert.equal(seq1.size(), seq2.size()); assert.equal(seq1.get(0), seq2.get(0)); let removeOp = seq2.remove(0); seq1.apply(removeOp); assert.equal(seq1.size(), seq2.size()); assert.equal(seq1.get(0), seq2.get(0)); }); }); describe("when an atom with the specified ident has already been removed", () => { it("ignores the operation", () => { let seq = new KSeq<number>("test"); let op1 = seq.append(42); seq.append(99); seq.remove(0); assert.equal(seq.size(), 1); let op2 = new RemoveOp("test", getWallTime(), op1.id); seq.apply(op2); assert.equal(seq.size(), 1); }); }); }); }); //-------------------------------------------------------------------------------- describe("is a CRDT", () => { it("supports insert/remove (base case)", () => { let seq = new KSeq<string>("alice"); seq.append("test"); assert.equal(seq.size(), 1); let ident = Ident.parse("1#0:bob"); let op1 = new InsertOp("bob", getWallTime(), ident, "hello"); let op2 = new RemoveOp("bob", getWallTime(), ident); seq.apply(op1); assert.equal(seq.size(), 2); seq.apply(op2); assert.equal(seq.size(), 1); }); it("idempotence: supports insert/insert (message duplication)", () => { let seq = new KSeq<string>("alice"); seq.append("test"); assert.equal(seq.size(), 1); let ident = Ident.parse("1#0:bob"); let op = new InsertOp("bob", getWallTime(), ident, "hello"); seq.apply(op); assert.equal(seq.size(), 2); seq.apply(op); assert.equal(seq.size(), 2); }); it("idempotence: supports remove/remove (message duplication)", () => { let seq = new KSeq<string>("alice"); seq.append("test"); assert.equal(seq.size(), 1); let ident = Ident.parse("1#0:bob"); let op1 = new InsertOp("bob", getWallTime(), ident, "hello"); let op2 = new RemoveOp("bob", getWallTime(), ident); seq.apply(op1); assert.equal(seq.size(), 2); seq.apply(op2); assert.equal(seq.size(), 1); seq.apply(op2); assert.equal(seq.size(), 1); }); it("commutative: supports remove/insert (messages out of order)", () => { let seq = new KSeq<string>("alice"); seq.append("test"); assert.equal(seq.size(), 1); let ident = Ident.parse("1#0:bob"); let op1 = new InsertOp("bob", getWallTime(), ident, "hello"); let op2 = new RemoveOp("bob", getWallTime(), ident); seq.apply(op2); assert.equal(seq.size(), 1); seq.apply(op1); assert.equal(seq.size(), 1); }); it("replicas converge when issued many randomized operations from a single replica", () => { let alice = new KSeq<number>("alice"); let bob = new KSeq<number>("bob"); let ops = []; for (let i = 0; i < 1000; i++) { let pos = Math.floor(Math.random() * i); ops.push(alice.insert(i, pos)); } for (let i = 0; i < 500; i++) { let pos = Math.floor(Math.random() * (1000 - i)); ops.push(alice.remove(pos)); } randomize(ops); for (let i = 0; i < ops.length; i++) { bob.apply(ops[i]); } assert.equal(alice.size(), 500); assert.equal(bob.size(), 500); assert.deepEqual(alice.toArray(), bob.toArray()); }); it("replicas converge when issued many randomized operations from multiple replicas", () => { let alice = new KSeq<number>("alice"); let bob = new KSeq<number>("bob"); let aliceOps = []; let bobOps = []; for (let i = 0; i < 1000; i++) { aliceOps.push(alice.insert(i, Math.floor(Math.random() * i))); bobOps.push(bob.insert(i, Math.floor(Math.random() * i))); } for (let i = 0; i < 500; i++) { aliceOps.push(alice.remove(Math.floor(Math.random() * (1000 - i)))); bobOps.push(bob.remove(Math.floor(Math.random() * (1000 - i)))); } randomize(aliceOps); randomize(bobOps); for (let i = 0; i < aliceOps.length; i++) { bob.apply(aliceOps[i]); } for (let i = 0; i < bobOps.length; i++) { alice.apply(bobOps[i]); } assert.equal(alice.size(), bob.size()); assert.deepEqual(alice.toArray(), bob.toArray()); }); }); //-------------------------------------------------------------------------------- });
the_stack
import expect from "expect"; import { assert, Assignment, ASTKind, ASTNode, ASTReader, Block, ContractDefinition, ExpressionStatement, FunctionCall, FunctionDefinition, Identifier, ImportDirective, IndexAccess, MemberAccess, OverrideSpecifier, ParameterList, PragmaDirective, SourceUnit, StructuredDocumentation, TupleExpression, TypeName, UnaryOperation } from "solc-typed-ast"; import { contains, forAll, forAny, InstrumentationMetaData, parseSrcTriple, PropertyMap, reNumber, searchRecursive, single } from "../../src/util"; import { loc2Src, removeProcWd, scrSample, toAstUsingCache } from "./utils"; type Src2NodeMap = Map<string, Set<ASTNode>>; function buildSrc2NodeMap(units: SourceUnit[], newSrcList?: string[]): Src2NodeMap { const res: Src2NodeMap = new Map(); let newIdx: number; for (const unit of units) { if (newSrcList) { newIdx = newSrcList.indexOf(unit.absolutePath); assert(newIdx !== -1, "No entry for {0} in {1}", unit.absolutePath, newSrcList); } unit.walk((node) => { const src = newSrcList ? reNumber(node.src, newIdx) : node.src; const set = res.get(src); if (set) { set.add(node); } else { res.set(src, new Set([node])); } }); } return res; } function fragment(src: string, contents: string) { const [off, len] = parseSrcTriple(src); return contents.slice(off, off + len); } type DecodedBytecodeSourceMapEntry = { byteIndex: number; start: number; length: number; sourceIndex: number; jump: string; }; function parseBytecodeSourceMapping(sourceMap: string): DecodedBytecodeSourceMapEntry[] { return sourceMap .split(";") .map((chunk) => chunk.split(":")) .map(([start, length, sourceIndex, jump]) => ({ start: start === "" ? undefined : start, length: length === "" ? undefined : length, sourceIndex: sourceIndex === "" ? undefined : sourceIndex, jump: jump === "" ? undefined : jump })) .reduce( ([previous, ...all], entry) => [ { start: parseInt(entry.start || previous.start, 10), length: parseInt(entry.length || previous.length, 10), sourceIndex: parseInt(entry.sourceIndex || previous.sourceIndex, 10), jump: entry.jump || previous.jump }, previous, ...all ], [{} as any] ) .reverse() .slice(1); } describe("Src2src map test", () => { const samplesDir = "test/samples/"; const samples = searchRecursive(samplesDir, (fileName) => fileName.endsWith(".instrumented.sol") ).map((fileName) => removeProcWd(fileName).replace(".instrumented.sol", ".sol")); it(`Source samples are present in ${samplesDir}`, () => { expect(samples.length).toBeGreaterThan(0); }); for (const sample of samples) { describe(`Sample ${sample}`, () => { let inAst: SourceUnit[]; let contents: string; let instrContents: string; let outJSON: any; let propMap: PropertyMap; let outAST: SourceUnit; let originalSrc2Node: Src2NodeMap; let instrSrc2Node: Src2NodeMap; let instrMD: InstrumentationMetaData; const coveredOriginalNodes = new Set<ASTNode>(); before(() => { const result = toAstUsingCache(sample); if (!result.files.has(sample)) { throw new Error(`Missing source for ${sample} in files mapping`); } inAst = result.units; contents = result.files.get(sample) as string; outJSON = JSON.parse(scrSample(sample, "--output-mode", "json")); instrContents = outJSON["sources"]["flattened.sol"]["source"]; const contentsMap = new Map<string, string>([["flattened.sol", instrContents]]); const reader = new ASTReader(); [outAST] = reader.read(outJSON, ASTKind.Modern, contentsMap); instrMD = outJSON.instrumentationMetadata; propMap = instrMD.propertyMap; originalSrc2Node = buildSrc2NodeMap(inAst, instrMD.originalSourceList); instrSrc2Node = buildSrc2NodeMap([outAST]); }); it("Src2src map maps nodes to nodes of same type", () => { for (const [instrRange, originalLoc] of instrMD.instrToOriginalMap) { const instrNodes = instrSrc2Node.get(instrRange); const originalRange = loc2Src(originalLoc); assert( instrNodes !== undefined, 'Instrumented range {0} (instr: "{1}", original {2}: "{3}") doesn\'t map to an ast node in instrumented code', instrRange, fragment(instrRange, instrContents), originalRange, fragment(originalRange, contents) ); const originalNodes = originalSrc2Node.get(originalRange); if (originalNodes === undefined) { // If no matchin original node, then this // mapping must map inside the body of one of the // annotations const containingProp = propMap.find((propDesc) => contains(loc2Src(propDesc.annotationSource), originalRange) ); assert( containingProp !== undefined, "Missing original node for {0} {1}", originalRange, fragment(originalRange, contents) ); continue; } // We expect that for each node in `instrNodes` there is a matching node at least by type for (const instrNode of instrNodes) { let matchingOrignal = [...originalNodes].find( (originalNode) => instrNode.constructor === originalNode.constructor ); /** * Handle the case where the writer emitted extra () */ if ( matchingOrignal === undefined && instrNode instanceof TupleExpression && instrNode.vComponents.length === 1 && !instrNode.isInlineArray ) { const innerExp = instrNode.vComponents[0]; matchingOrignal = [...originalNodes].find( (originalNode) => innerExp.constructor === originalNode.constructor ); } if (matchingOrignal === undefined) { // There are several exceptions for this: // 1) State var update substitutions - (those are substituted with function calls) // 2) Callsite substitutions // 3) Converting a type Identifier to a MemberAccess // 4) Substituting an expression with a temporary on the LHS of a tuple assignment if ( instrNode instanceof Identifier && instrNode.name.startsWith(`_callsite_`) ) { const oldCallee = single([...originalNodes]); oldCallee.walk((n) => coveredOriginalNodes.add(n)); } else if (instrNode instanceof FunctionCall) { for (const node of originalNodes) { if (node instanceof ExpressionStatement) { // nothing to do } else if (node instanceof Assignment) { for (const child of node.vLeftHandSide.getChildren(true)) { coveredOriginalNodes.add(child); } } else if (node instanceof UnaryOperation) { assert( ["++", "--", "delete"].includes(node.operator), "Only ++/--/delete may be interposed for state vars" ); for (const child of node.vSubExpression.getChildren(true)) { coveredOriginalNodes.add(child); } } else if (node instanceof IndexAccess) { for (const child of node.getChildren(true)) { coveredOriginalNodes.add(child); } } else { assert( false, "Unexpected original node {0} in state var update site", node ); } coveredOriginalNodes.add(node); } } else if ( forAll(originalNodes, (node) => { const tuple = node.getClosestParentByType(TupleExpression); if (tuple === undefined) { return false; } const assignment = tuple.getClosestParentByType(Assignment); // @todo chech that we are a left chidl of assignment here return assignment !== undefined; }) ) { for (const original of originalNodes) { for (const child of original.getChildren(true)) { coveredOriginalNodes.add(child); } } } else if ( instrNode instanceof MemberAccess && originalNodes.size === 1 ) { const originalNode = single([...originalNodes]); assert( originalNode instanceof Identifier && instrNode.memberName === originalNode.name && instrNode.vExpression instanceof Identifier && instrNode.vExpression.vReferencedDeclaration instanceof ContractDefinition, "For nodes {0} in {1} ({2}), no matching original node from {3} in {4} ({5})", instrNodes, instrRange, fragment(instrRange, instrContents), originalNodes, originalRange, fragment(originalRange, contents) ); coveredOriginalNodes.add(originalNode); } else { assert( false, "For nodes {0} in {1} ({2}), no matching original node from {3} in {4} ({5})", instrNodes, instrRange, fragment(instrRange, instrContents), originalNodes, originalRange, fragment(originalRange, contents) ); } } else { coveredOriginalNodes.add(matchingOrignal); } } } }); it("Src2src map covers all relevant AST nodes in original file", () => { for (const unit of inAst) { unit.walk((node) => { if (!coveredOriginalNodes.has(node)) { // There are several cases of original AST nodes that don't // have a corresponding node in the flattened instrumented output // 1) SourceUnits - may be removed in flat mode // 2) PragmaDirectives - maybe removed in flat mode // 3) ImportDirectives - maybe removed in flat mode // 4) StructureDocumentations - are stripped // 5) Empty ParamterLists (especiall in return params) may be removed // 6) OverrideSpecifiers are moved on interposition // 7) .push() and .pop() callees that are interposed // 8) Mapping type names inside of state variables and some struct definitions that get re-written during map interposition if ( !( ( node instanceof SourceUnit || // No original SourceUnits after flattening node instanceof PragmaDirective || // Compiler version pragma directives are stripped node instanceof ImportDirective || // Import directives are stripped node instanceof StructuredDocumentation || // Structured docs are stripped (node instanceof ParameterList && node.vParameters.length == 0) /* Empty parameter lists */ || node instanceof OverrideSpecifier || (node instanceof MemberAccess && ["push", "pop"].includes(node.memberName)) || (node.parent instanceof MemberAccess && ["push", "pop"].includes(node.parent.memberName)) || node instanceof TypeName ) /* Override specifiers are moved on interposition */ ) ) { assert( false, "Node {0} ({1}) from original not covered by AST map.", node, fragment(node.src, contents) ); } } }); } }); it("All assertion ranges are inside of an instrumentation range", () => { assert( forAll(instrMD.propertyMap, (prop) => forAll(prop.assertionRanges, (assertionRange) => forAny(prop.instrumentationRanges, (instrRange) => contains(instrRange, assertionRange) ) ) ), "Some assertion ranges are out of instrumentation ranges (they shouldn't be)" ); }); it("Bytecode map is covered by instrumentation metadata", () => { // Some compiler-generated code maps to the whole file. Skip it. const src2SrcMap = new Map(instrMD.instrToOriginalMap); // Need to skip some compiler-generated bytecode. Specifically any // bytecode related to entire functions, contracts or (as of 0.8.6) the entire body // of a function const skipSrcs = new Set<string>(); for (const node of outAST.getChildrenBySelector( (node) => node instanceof ContractDefinition || node instanceof FunctionDefinition || (node instanceof Block && node.parent instanceof FunctionDefinition), true )) { skipSrcs.add(node.src); } // Keep track of which `checkRange`s were hit for each property. // Each must be hit at least once by the bytecode map. const propertyChecksHit = new Set<string>(); for (const fileName in outJSON["contracts"]) { const fileJSON = outJSON["contracts"][fileName]; for (const contractName in fileJSON) { const contractJSON = fileJSON[contractName]; const bytecodeMap = contractJSON.evm.bytecode.sourceMap; const deployedBytecodeMap = contractJSON.evm.deployedBytecode.sourceMap; // Since 0.7.2 builtin utility code has a source range with source index -1. // Since 0.8.0 builtin utility code is emitted and has a positive source index 1 greater than the source list. // Want to ignore utility code in both the bytecode and deployedBytecode maps const bytecodeMapEntries = parseBytecodeSourceMapping(bytecodeMap).filter( (entry) => entry.sourceIndex !== -1 && entry.sourceIndex < instrMD.instrSourceList.length ); const deployedBytecodeMapEntries = parseBytecodeSourceMapping( deployedBytecodeMap ).filter( (entry) => entry.sourceIndex !== -1 && entry.sourceIndex < instrMD.instrSourceList.length ); // Interfaces have weird source maps. Skip them if ( bytecodeMapEntries.length === 1 && isNaN(bytecodeMapEntries[0].sourceIndex) ) { continue; } assert( forAll(bytecodeMapEntries, (entry) => entry.sourceIndex === 0), `Contract ${contractName} in ${fileName} has non-zero source inidices in its bytecode map.` ); assert( forAll(deployedBytecodeMapEntries, (entry) => entry.sourceIndex === 0), `Contract ${contractName} in ${fileName} has non-zero source inidices in its deployedBytecodemap.` ); const missing = new Set<string>(); for (const entry of bytecodeMapEntries.concat(deployedBytecodeMapEntries)) { const strEntry = `${entry.start}:${entry.length}:${entry.sourceIndex}`; // For every bytecode source map entry, EITHER it must EXACTLY match an entry in the src2src map if (src2SrcMap.has(strEntry)) { continue; } if (skipSrcs.has(strEntry)) { continue; } // Check if this source map entry corresponds to // some property check condition, and mark it instrMD.propertyMap.forEach((prop, propIdx) => { prop.checkRanges.forEach((checkRange, checkRangeIdx) => { if (contains(checkRange, strEntry)) { const key = `${propIdx}_${checkRangeIdx}`; propertyChecksHit.add(key); } }); }); // OR it must be part of the instrumentation of some property if ( forAny(instrMD.propertyMap, (prop) => forAny(prop.instrumentationRanges, (range) => contains(range, strEntry) ) ) ) { continue; } // OR it must be part of the general instrumentation if ( forAny(instrMD.otherInstrumentation, (range) => contains(range, strEntry) ) ) { continue; } missing.add(strEntry); } for (const strEntry of missing) { console.log( `Bytecode entry ${strEntry} for ${fileName}:${contractName} corresponding to ${fragment( strEntry, instrContents )} not covered` ); } assert( missing.size === 0, `Bytecode map for ${fileName} ${contractName} has missing entries.` ); } } instrMD.propertyMap.forEach((prop, propIdx) => { prop.checkRanges.forEach((checkRange, checkRangeIdx) => { const key = `${propIdx}_${checkRangeIdx}`; if (!propertyChecksHit.has(key)) { assert( false, "Instrumented check location {0} ({1}) for property {2} is not found anywhere in the bytecode map", checkRange, fragment(checkRange, instrContents), prop.id ); } }); }); }); }); } });
the_stack
namespace LiteMol.Extensions.ComplexReprensetation.Carbohydrates.Mapping { export interface RepresentationEntry { instanceName: string, name: string, shape: Core.Geometry.Surface[], color: Visualization.Color[], axisUp: number[], axisSide: number[] } export const RingNames: { __len: number, [n: string]: number }[] = [ { __len: 6, 'C1': 0, 'C2': 1, 'C3': 2, 'C4': 3, 'C5': 4, 'O5': 5 }, { __len: 6, 'C1': 0, 'C2': 1, 'C3': 2, 'C4': 3, 'C5': 4, 'O': 5 }, { __len: 6, 'C2': 0, 'C3': 1, 'C4': 2, 'C5': 3, 'C6': 4, 'O6': 5 }, { __len: 5, 'C1': 0, 'C2': 1, 'C3': 2, 'C4': 3, 'O4': 4 }, { __len: 5, 'C1\'': 0, 'C2\'': 1, 'C3\'': 2, 'C4\'': 3, 'O4\'': 4 }, ]; const data = [ /* === Filled sphere === */ { shape: [Shapes.Sphere] /* Filled sphere */, axisUp: [0, 0, 1], instances: [{ name: 'Glc', common: { colorA: '#0090bc', names: ['GLC', 'BGC'] }, charmm: { colorA: '#0090bc', names: ['AGLC', 'BGLC'] }, glycam: { colorA: '#0090bc', names: ['0GA', '0GB', '1GA', '1GB', '2GA', '2GB', '3GA', '3GB', '4GA', '4GB', '6GA', '6GB', 'ZGA', 'ZGB', 'YGA', 'YGB', 'XGA', 'XGB', 'WGA', 'WGB', 'VGA', 'VGB', 'UGA', 'UGB', 'TGA', 'TGB', 'SGA', 'SGB', 'RGA', 'RGB', 'QGA', 'QGB', 'PGA', 'PGB', '0gA', '0gB', '1gA', '1gB', '2gA', '2gB', '3gA', '3gB', '4gA', '4gB', '6gA', '6gB', 'ZgA', 'ZgB', 'YgA', 'YgB', 'XgA', 'XgB', 'WgA', 'WgB', 'VgA', 'VgB', 'UgA', 'UgB', 'TgA', 'TgB', 'SgA', 'SgB', 'RgA', 'RgB', 'QgA', 'QgB', 'PgA', 'PgB'] }, }, { name: 'Man', common: { colorA: '#00a651', names: ['MAN', 'BMA'] }, charmm: { colorA: '#00a651', names: ['AMAN', 'BMAN'] }, glycam: { colorA: '#00a651', names: ['0MA', '0MB', '1MA', '1MB', '2MA', '2MB', '3MA', '3MB', '4MA', '4MB', '6MA', '6MB', 'ZMA', 'ZMB', 'YMA', 'YMB', 'XMA', 'XMB', 'WMA', 'WMB', 'VMA', 'VMB', 'UMA', 'UMB', 'TMA', 'TMB', 'SMA', 'SMB', 'RMA', 'RMB', 'QMA', 'QMB', 'PMA', 'PMB', '0mA', '0mB', '1mA', '1mB', '2mA', '2mB', '3mA', '3mB', '4mA', '4mB', '6mA', '6mB', 'ZmA', 'ZmB', 'YmA', 'YmB', 'XmA', 'XmB', 'WmA', 'WmB', 'VmA', 'VmB', 'UmA', 'UmB', 'TmA', 'TmB', 'SmA', 'SmB', 'RmA', 'RmB', 'QmA', 'QmB', 'PmA', 'PmB'] }, }, { name: 'Gal', common: { colorA: '#ffd400', names: ['GAL', 'GLA'] }, charmm: { colorA: '#ffd400', names: ['AGAL', 'BGAL'] }, glycam: { colorA: '#ffd400', names: ['0LA', '0LB', '1LA', '1LB', '2LA', '2LB', '3LA', '3LB', '4LA', '4LB', '6LA', '6LB', 'ZLA', 'ZLB', 'YLA', 'YLB', 'XLA', 'XLB', 'WLA', 'WLB', 'VLA', 'VLB', 'ULA', 'ULB', 'TLA', 'TLB', 'SLA', 'SLB', 'RLA', 'RLB', 'QLA', 'QLB', 'PLA', 'PLB', '0lA', '0lB', '1lA', '1lB', '2lA', '2lB', '3lA', '3lB', '4lA', '4lB', '6lA', '6lB', 'ZlA', 'ZlB', 'YlA', 'YlB', 'XlA', 'XlB', 'WlA', 'WlB', 'VlA', 'VlB', 'UlA', 'UlB', 'TlA', 'TlB', 'SlA', 'SlB', 'RlA', 'RlB', 'QlA', 'QlB', 'PlA', 'PlB'] }, }, { name: 'Gul', common: { colorA: '#f47920', names: ['GUP', 'GL0'] }, charmm: { colorA: '#f47920', names: ['AGUL', 'BGUL'] }, glycam: { colorA: '#f47920', names: ['0KA', '0KB', '1KA', '1KB', '2KA', '2KB', '3KA', '3KB', '4KA', '4KB', '6KA', '6KB', 'ZKA', 'ZKB', 'YKA', 'YKB', 'XKA', 'XKB', 'WKA', 'WKB', 'VKA', 'VKB', 'UKA', 'UKB', 'TKA', 'TKB', 'SKA', 'SKB', 'RKA', 'RKB', 'QKA', 'QKB', 'PKA', 'PKB', '0kA', '0kB', '1kA', '1kB', '2kA', '2kB', '3kA', '3kB', '4kA', '4kB', '6kA', '6kB', 'ZkA', 'ZkB', 'YkA', 'YkB', 'XkA', 'XkB', 'WkA', 'WkB', 'VkA', 'VkB', 'UkA', 'UkB', 'TkA', 'TkB', 'SkA', 'SkB', 'RkA', 'RkB', 'QkA', 'QkB', 'PkA', 'PkB'] }, }, { name: 'Alt', common: { colorA: '#f69ea1', names: ['ALT'] }, charmm: { colorA: '#f69ea1', names: ['AALT', 'BALT'] }, glycam: { colorA: '#f69ea1', names: ['0EA', '0EB', '1EA', '1EB', '2EA', '2EB', '3EA', '3EB', '4EA', '4EB', '6EA', '6EB', 'ZEA', 'ZEB', 'YEA', 'YEB', 'XEA', 'XEB', 'WEA', 'WEB', 'VEA', 'VEB', 'UEA', 'UEB', 'TEA', 'TEB', 'SEA', 'SEB', 'REA', 'REB', 'QEA', 'QEB', 'PEA', 'PEB', '0eA', '0eB', '1eA', '1eB', '2eA', '2eB', '3eA', '3eB', '4eA', '4eB', '6eA', '6eB', 'ZeA', 'ZeB', 'YeA', 'YeB', 'XeA', 'XeB', 'WeA', 'WeB', 'VeA', 'VeB', 'UeA', 'UeB', 'TeA', 'TeB', 'SeA', 'SeB', 'ReA', 'ReB', 'QeA', 'QeB', 'PeA', 'PeB'] }, }, { name: 'All', common: { colorA: '#a54399', names: ['ALL', 'AFD'] }, charmm: { colorA: '#a54399', names: ['AALL', 'BALL'] }, glycam: { colorA: '#a54399', names: ['0NA', '0NB', '1NA', '1NB', '2NA', '2NB', '3NA', '3NB', '4NA', '4NB', '6NA', '6NB', 'ZNA', 'ZNB', 'YNA', 'YNB', 'XNA', 'XNB', 'WNA', 'WNB', 'VNA', 'VNB', 'UNA', 'UNB', 'TNA', 'TNB', 'SNA', 'SNB', 'RNA', 'RNB', 'QNA', 'QNB', 'PNA', 'PNB', '0nA', '0nB', '1nA', '1nB', '2nA', '2nB', '3nA', '3nB', '4nA', '4nB', '6nA', '6nB', 'ZnA', 'ZnB', 'YnA', 'YnB', 'XnA', 'XnB', 'WnA', 'WnB', 'VnA', 'VnB', 'UnA', 'UnB', 'TnA', 'TnB', 'SnA', 'SnB', 'RnA', 'RnB', 'QnA', 'QnB', 'PnA', 'PnB'] }, }, { name: 'Tal', common: { colorA: '#8fcce9', names: ['TAL'] }, charmm: { colorA: '#8fcce9', names: ['ATAL', 'BTAL'] }, glycam: { colorA: '#8fcce9', names: ['0TA', '0TB', '1TA', '1TB', '2TA', '2TB', '3TA', '3TB', '4TA', '4TB', '6TA', '6TB', 'ZTA', 'ZTB', 'YTA', 'YTB', 'XTA', 'XTB', 'WTA', 'WTB', 'VTA', 'VTB', 'UTA', 'UTB', 'TTA', 'TTB', 'STA', 'STB', 'RTA', 'RTB', 'QTA', 'QTB', 'PTA', 'PTB', '0tA', '0tB', '1tA', '1tB', '2tA', '2tB', '3tA', '3tB', '4tA', '4tB', '6tA', '6tB', 'ZtA', 'ZtB', 'YtA', 'YtB', 'XtA', 'XtB', 'WtA', 'WtB', 'VtA', 'VtB', 'UtA', 'UtB', 'TtA', 'TtB', 'StA', 'StB', 'RtA', 'RtB', 'QtA', 'QtB', 'PtA', 'PtB'] }, }, { name: 'Ido', common: { colorA: '#a17a4d', names: ['4N2'] }, charmm: { colorA: '#a17a4d', names: ['AIDO', 'BIDO'] }, glycam: { colorA: '#a17a4d', names: [] }, }] }, /* === Filled cube === */ { shape: [Shapes.Cube] /* Filled cube */, axisUp: [0, 0, 1], instances: [{ name: 'GlcNAc', common: { colorA: '#0090bc', names: ['NAG', 'NDG'] }, charmm: { colorA: '#0090bc', names: ['AGLCNA', 'BGLCNA', 'BGLCN0'] }, glycam: { colorA: '#0090bc', names: ['0YA', '0YB', '1YA', '1YB', '3YA', '3YB', '4YA', '4YB', '6YA', '6YB', 'WYA', 'WYB', 'VYA', 'VYB', 'UYA', 'UYB', 'QYA', 'QYB', '0yA', '0yB', '1yA', '1yB', '3yA', '3yB', '4yA', '4yB', '6yA', '6yB', 'WyA', 'WyB', 'VyA', 'VyB', 'UyA', 'UyB', 'QyA', 'QyB', '0YS', '0Ys', '3YS', '3Ys', '4YS', '4Ys', '6YS', '6Ys', 'QYS', 'QYs', 'UYS', 'UYs', 'VYS', 'VYs', 'WYS', 'WYs', '0yS', '0ys', '3yS', '3ys', '4yS', '4ys'] }, }, { name: 'ManNAc', common: { colorA: '#00a651', names: ['BM3'] }, charmm: { colorA: '#00a651', names: [] }, glycam: { colorA: '#00a651', names: ['0WA', '0WB', '1WA', '1WB', '3WA', '3WB', '4WA', '4WB', '6WA', '6WB', 'WWA', 'WWB', 'VWA', 'VWB', 'UWA', 'UWB', 'QWA', 'QWB', '0wA', '0wB', '1wA', '1wB', '3wA', '3wB', '4wA', '4wB', '6wA', '6wB', 'WwA', 'WwB', 'VwA', 'VwB', 'UwA', 'UwB', 'QwA', 'QwB'] }, }, { name: 'GalNAc', common: { colorA: '#ffd400', names: ['NGA', 'A2G'] }, charmm: { colorA: '#ffd400', names: ['AGALNA', 'BGALNA'] }, glycam: { colorA: '#ffd400', names: ['0VA', '0VB', '1VA', '1VB', '3VA', '3VB', '4VA', '4VB', '6VA', '6VB', 'WVA', 'WVB', 'VVA', 'VVB', 'UVA', 'UVB', 'QVA', 'QVB', '0vA', '0vB', '1vA', '1vB', '3vA', '3vB', '4vA', '4vB', '6vA', '6vB', 'WvA', 'WvB', 'VvA', 'VvB', 'UvA', 'UvB', 'QvA', 'QvB'] }, }, { name: 'GulNAc', common: { colorA: '#f47920', names: [] }, charmm: { colorA: '#f47920', names: [] }, glycam: { colorA: '#f47920', names: [] }, }, { name: 'AltNAc', common: { colorA: '#f69ea1', names: [] }, charmm: { colorA: '#f69ea1', names: [] }, glycam: { colorA: '#f69ea1', names: [] }, }, { name: 'AllNAc', common: { colorA: '#a54399', names: ['NAA'] }, charmm: { colorA: '#a54399', names: [] }, glycam: { colorA: '#a54399', names: [] }, }, { name: 'TalNAc', common: { colorA: '#8fcce9', names: [] }, charmm: { colorA: '#8fcce9', names: [] }, glycam: { colorA: '#8fcce9', names: [] }, }, { name: 'IdoNAc', common: { colorA: '#a17a4d', names: ['HSQ'] }, charmm: { colorA: '#a17a4d', names: [] }, glycam: { colorA: '#a17a4d', names: [] }, }] }, /* === Crossed cube === */ { shape: Shapes.stripe(Shapes.Cube) /* Crossed cube */, axisUp: [0, 0, 1], instances: [{ name: 'GlcN', common: { colorA: '#0090bc', colorB: '#f1ece1', names: ['GCS', 'PA1'] }, charmm: { colorA: '#0090bc', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#0090bc', colorB: '#f1ece1', names: ['0YN', '3YN', '4YN', '6YN', 'WYN', 'VYN', 'UYN', 'QYN', '3Yn', '4Yn', 'WYn', '0Yn', '0YP', '3YP', '4YP', '6YP', 'WYP', 'VYP', 'UYP', 'QYP', '0Yp', '3Yp', '4Yp', 'WYp'] }, }, { name: 'ManN', common: { colorA: '#00a651', colorB: '#f1ece1', names: ['95Z'] }, charmm: { colorA: '#00a651', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#00a651', colorB: '#f1ece1', names: [] }, }, { name: 'GalN', common: { colorA: '#ffd400', colorB: '#f1ece1', names: ['X6X', '1GN'] }, charmm: { colorA: '#ffd400', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#ffd400', colorB: '#f1ece1', names: [] }, }, { name: 'GulN', common: { colorA: '#f47920', colorB: '#f1ece1', names: [] }, charmm: { colorA: '#f47920', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#f47920', colorB: '#f1ece1', names: [] }, }, { name: 'AltN', common: { colorA: '#f69ea1', colorB: '#f1ece1', names: [] }, charmm: { colorA: '#f69ea1', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#f69ea1', colorB: '#f1ece1', names: [] }, }, { name: 'AllN', common: { colorA: '#a54399', colorB: '#f1ece1', names: [] }, charmm: { colorA: '#a54399', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#a54399', colorB: '#f1ece1', names: [] }, }, { name: 'TalN', common: { colorA: '#8fcce9', colorB: '#f1ece1', names: [] }, charmm: { colorA: '#8fcce9', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#8fcce9', colorB: '#f1ece1', names: [] }, }, { name: 'IdoN', common: { colorA: '#a17a4d', colorB: '#f1ece1', names: [] }, charmm: { colorA: '#a17a4d', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#a17a4d', colorB: '#f1ece1', names: [] }, }] }, /* === Divided diamond === */ { shape: Shapes.split(Shapes.Diamond) /* Divided diamond */, axisUp: [1, 0, 0], instances: [{ name: 'GlcA', common: { colorA: '#0090bc', colorB: '#f1ece1', names: ['GCU', 'BDP'] }, charmm: { colorA: '#0090bc', colorB: '#f1ece1', names: ['AGLCA', 'BGLCA', 'BGLCA0'] }, glycam: { colorA: '#0090bc', colorB: '#f1ece1', names: ['0ZA', '0ZB', '1ZA', '1ZB', '2ZA', '2ZB', '3ZA', '3ZB', '4ZA', '4ZB', 'ZZA', 'ZZB', 'YZA', 'YZB', 'WZA', 'WZB', 'TZA', 'TZB', '0zA', '0zB', '1zA', '1zB', '2zA', '2zB', '3zA', '3zB', '4zA', '4zB', 'ZzA', 'ZzB', 'YzA', 'YzB', 'WzA', 'WzB', 'TzA', 'TzB', '0ZBP'] }, }, { name: 'ManA', common: { colorA: '#00a651', colorB: '#f1ece1', names: ['MAV', 'BEM'] }, charmm: { colorA: '#00a651', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#00a651', colorB: '#f1ece1', names: [] }, }, { name: 'GalA', common: { colorA: '#ffd400', colorB: '#f1ece1', names: ['ADA', 'GTR'] }, charmm: { colorA: '#ffd400', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#ffd400', colorB: '#f1ece1', names: ['0OA', '0OB', '1OA', '1OB', '2OA', '2OB', '3OA', '3OB', '4OA', '4OB', 'ZOA', 'ZOB', 'YOA', 'YOB', 'WOA', 'WOB', 'TOA', 'TOB', '0oA', '0oB', '1oA', '1oB', '2oA', '2oB', '3oA', '3oB', '4oA', '4oB', 'ZoA', 'ZoB', 'YoA', 'YoB', 'WoA', 'WoB', 'ToA', 'ToB'] }, }, { name: 'GulA', common: { colorA: '#f47920', colorB: '#f1ece1', names: ['LGU'] }, charmm: { colorA: '#f47920', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#f47920', colorB: '#f1ece1', names: [] }, }, { name: 'AltA', common: { colorA: '#f1ece1', colorB: '#f69ea1', names: [] }, charmm: { colorA: '#f1ece1', colorB: '#f69ea1', names: [] }, glycam: { colorA: '#f1ece1', colorB: '#f69ea1', names: [] }, }, { name: 'AllA', common: { colorA: '#a54399', colorB: '#f1ece1', names: [] }, charmm: { colorA: '#a54399', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#a54399', colorB: '#f1ece1', names: [] }, }, { name: 'TalA', common: { colorA: '#8fcce9', colorB: '#f1ece1', names: ['X0X', 'X1X'] }, charmm: { colorA: '#8fcce9', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#8fcce9', colorB: '#f1ece1', names: [] }, }, { name: 'IdoA', common: { colorA: '#f1ece1', colorB: '#a17a4d', names: ['IDR'] }, charmm: { colorA: '#f1ece1', colorB: '#a17a4d', names: ['AIDOA', 'BIDOA'] }, glycam: { colorA: '#f1ece1', colorB: '#a17a4d', names: ['0UA', '0UB', '1UA', '1UB', '2UA', '2UB', '3UA', '3UB', '4UA', '4UB', 'ZUA', 'ZUB', 'YUA', 'YUB', 'WUA', 'WUB', 'TUA', 'TUB', '0uA', '0uB', '1uA', '1uB', '2uA', '2uB', '3uA', '3uB', '4uA', '4uB', 'ZuA', 'ZuB', 'YuA', 'YuB', 'WuA', 'WuB', 'TuA', 'TuB', 'YuAP'] }, }] }, /* === Filled cone === */ { shape: [Shapes.Cone] /* Filled cone */, axisUp: [0, 1, 0], instances: [{ name: 'Qui', common: { colorA: '#0090bc', names: ['G6D'] }, charmm: { colorA: '#0090bc', names: [] }, glycam: { colorA: '#0090bc', names: ['0QA', '0QB', '1QA', '1QB', '2QA', '2QB', '3QA', '3QB', '4QA', '4QB', 'ZQA', 'ZQB', 'YQA', 'YQB', 'WQA', 'WQB', 'TQA', 'TQB', '0qA', '0qB', '1qA', '1qB', '2qA', '2qB', '3qA', '3qB', '4qA', '4qB', 'ZqA', 'ZqB', 'YqA', 'YqB', 'WqA', 'WqB', 'TqA', 'TqB'] }, }, { name: 'Rha', common: { colorA: '#00a651', names: ['RAM', 'RM4'] }, charmm: { colorA: '#00a651', names: ['ARHM', 'BRHM'] }, glycam: { colorA: '#00a651', names: ['0HA', '0HB', '1HA', '1HB', '2HA', '2HB', '3HA', '3HB', '4HA', '4HB', 'ZHA', 'ZHB', 'YHA', 'YHB', 'WHA', 'WHB', 'THA', 'THB', '0hA', '0hB', '1hA', '1hB', '2hA', '2hB', '3hA', '3hB', '4hA', '4hB', 'ZhA', 'ZhB', 'YhA', 'YhB', 'WhA', 'WhB', 'ThA', 'ThB'] }, }, { name: 'x6dAlt', common: { colorA: '#F88CD2', names: [] }, charmm: { colorA: '#935D38', names: [] }, glycam: { colorA: '#57913F', names: [] }, }, { name: 'x6dTal', common: { colorA: '#B490DE', names: [] }, charmm: { colorA: '#64CABE', names: [] }, glycam: { colorA: '#D9147F', names: [] }, }, { name: 'Fuc', common: { colorA: '#ed1c24', names: ['FUC', 'FUL'] }, charmm: { colorA: '#ed1c24', names: ['AFUC', 'BFUC'] }, glycam: { colorA: '#ed1c24', names: ['0FA', '0FB', '1FA', '1FB', '2FA', '2FB', '3FA', '3FB', '4FA', '4FB', 'ZFA', 'ZFB', 'YFA', 'YFB', 'WFA', 'WFB', 'TFA', 'TFB', '0fA', '0fB', '1fA', '1fB', '2fA', '2fB', '3fA', '3fB', '4fA', '4fB', 'ZfA', 'ZfB', 'YfA', 'YfB', 'WfA', 'WfB', 'TfA', 'TfB'] }, }] }, /* === Divided cone === */ { shape: [Shapes.ConeLeft, Shapes.ConeRight] /* Divided cone */, axisUp: [0, 1, 0], instances: [{ name: 'QuiNAc', common: { colorA: '#0090bc', colorB: '#f1ece1', names: [] }, charmm: { colorA: '#0090bc', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#0090bc', colorB: '#f1ece1', names: [] }, }, { name: 'RhaNAc', common: { colorA: '#00a651', colorB: '#f1ece1', names: [] }, charmm: { colorA: '#00a651', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#00a651', colorB: '#f1ece1', names: [] }, }, { name: 'FucNAc', common: { colorA: '#ed1c24', colorB: '#f1ece1', names: [] }, charmm: { colorA: '#ed1c24', colorB: '#f1ece1', names: [] }, glycam: { colorA: '#ed1c24', colorB: '#f1ece1', names: [] }, }] }, /* === Flat rectangle === */ { shape: [Shapes.FlatRectangle] /* Flat rectangle */, axisUp: [0, 1, 0], instances: [{ name: 'Oli', common: { colorA: '#0090bc', names: ['DDA'] }, charmm: { colorA: '#0090bc', names: [] }, glycam: { colorA: '#0090bc', names: [] }, }, { name: 'Tyv', common: { colorA: '#00a651', names: ['TYV'] }, charmm: { colorA: '#00a651', names: [] }, glycam: { colorA: '#00a651', names: ['0TV', '0Tv', '1TV', '1Tv', '2TV', '2Tv', '4TV', '4Tv', 'YTV', 'YTv', '0tV', '0tv', '1tV', '1tv', '2tV', '2tv', '4tV', '4tv', 'YtV', 'Ytv'] }, }, { name: 'Abe', common: { colorA: '#f47920', names: ['ABE'] }, charmm: { colorA: '#f47920', names: [] }, glycam: { colorA: '#f47920', names: ['0AE', '2AE', '4AE', 'YGa', '0AF', '2AF', '4AF', 'YAF'] }, }, { name: 'Par', common: { colorA: '#f69ea1', names: ['PZU'] }, charmm: { colorA: '#f69ea1', names: [] }, glycam: { colorA: '#f69ea1', names: [] }, }, { name: 'Dig', common: { colorA: '#a54399', names: [] }, charmm: { colorA: '#a54399', names: [] }, glycam: { colorA: '#a54399', names: [] }, }, { name: 'Col', common: { colorA: '#8fcce9', names: [] }, charmm: { colorA: '#8fcce9', names: [] }, glycam: { colorA: '#8fcce9', names: [] }, }] }, /* === Filled star === */ { shape: [Shapes.Star] /* Filled star */, axisUp: [0, 0, 1], instances: [{ name: 'Ara', common: { colorA: '#00a651', names: ['ARA', 'ARB'] }, charmm: { colorA: '#00a651', names: ['AARB', 'BARB'] }, glycam: { colorA: '#00a651', names: ['0AA', '0AB', '1AA', '1AB', '2AA', '2AB', '3AA', '3AB', '4AA', '4AB', 'ZAA', 'ZAB', 'YAA', 'YAB', 'WAA', 'WAB', 'TAA', 'TAB', '0AD', '0AU', '1AD', '1AU', '2AD', '2AU', '3AD', '3AU', '5AD', '5AU', 'ZAD', 'ZAU', '0aA', '0aB', '1aA', '1aB', '2aA', '2aB', '3aA', '3aB', '4aA', '4aB', 'ZaA', 'ZaB', 'YaA', 'YaB', 'WaA', 'WaB', 'TaA', 'TaB', '0aD', '0aU', '1aD', '1aU', '2aD', '2aU', '3aD', '3aU', '5aD', '5aU', 'ZaD', 'ZaU'] }, }, { name: 'Lyx', common: { colorA: '#ffd400', names: ['LDY'] }, charmm: { colorA: '#ffd400', names: ['ALYF', 'BLYF'] }, glycam: { colorA: '#ffd400', names: ['0DA', '0DB', '1DA', '1DB', '2DA', '2DB', '3DA', '3DB', '4DA', '4DB', 'ZDA', 'ZDB', 'YDA', 'YDB', 'WDA', 'WDB', 'TDA', 'TDB', '0DD', '0DU', '1DD', '1DU', '2DD', '2DU', '3DD', '3DU', '5DD', '5DU', 'ZDD', 'ZDU', '0dA', '0dB', '1dA', '1dB', '2dA', '2dB', '3dA', '3dB', '4dA', '4dB', 'ZdA', 'ZdB', 'YdA', 'YdB', 'WdA', 'WdB', 'TdA', 'TdB', '0dD', '0dU', '1dD', '1dU', '2dD', '2dU', '3dD', '3dU', '5dD', '5dU', 'ZdD', 'ZdU'] }, }, { name: 'Xyl', common: { colorA: '#f47920', names: ['XYS', 'XYP'] }, charmm: { colorA: '#f47920', names: ['AXYL', 'BXYL', 'AXYF', 'BXYF'] }, glycam: { colorA: '#f47920', names: ['0XA', '0XB', '1XA', '1XB', '2XA', '2XB', '3XA', '3XB', '4XA', '4XB', 'ZXA', 'ZXB', 'YXA', 'YXB', 'WXA', 'WXB', 'TXA', 'TXB', '0XD', '0XU', '1XD', '1XU', '2XD', '2XU', '3XD', '3XU', '5XD', '5XU', 'ZXD', 'ZXU', '0xA', '0xB', '1xA', '1xB', '2xA', '2xB', '3xA', '3xB', '4xA', '4xB', 'ZxA', 'ZxB', 'YxA', 'YxB', 'WxA', 'WxB', 'TxA', 'TxB', '0xD', '0xU', '1xD', '1xU', '2xD', '2xU', '3xD', '3xU', '5xD', '5xU', 'ZxD', 'ZxU'] }, }, { name: 'Rib', common: { colorA: '#f69ea1', names: ['RIP', '0MK'] }, charmm: { colorA: '#f69ea1', names: ['ARIB', 'BRIB'] }, glycam: { colorA: '#f69ea1', names: ['0RA', '0RB', '1RA', '1RB', '2RA', '2RB', '3RA', '3RB', '4RA', '4RB', 'ZRA', 'ZRB', 'YRA', 'YRB', 'WRA', 'WRB', 'TRA', 'TRB', '0RD', '0RU', '1RD', '1RU', '2RD', '2RU', '3RD', '3RU', '5RD', '5RU', 'ZRD', 'ZRU', '0rA', '0rB', '1rA', '1rB', '2rA', '2rB', '3rA', '3rB', '4rA', '4rB', 'ZrA', 'ZrB', 'YrA', 'YrB', 'WrA', 'WrB', 'TrA', 'TrB', '0rD', '0rU', '1rD', '1rU', '2rD', '2rU', '3rD', '3rU', '5rD', '5rU', 'ZrD', 'ZrU'] }, }] }, /* === Filled diamond === */ { shape: [Shapes.Diamond] /* Filled diamond */, axisUp: [1, 0, 0], instances: [{ name: 'Kdn', common: { colorA: '#00a651', names: ['KDN', 'KDM'] }, charmm: { colorA: '#00a651', names: [] }, glycam: { colorA: '#00a651', names: [] }, }, { name: 'Neu5Ac', common: { colorA: '#a54399', names: ['SIA', 'SLB'] }, charmm: { colorA: '#a54399', names: ['ANE5AC', 'BNE5AC'] }, glycam: { colorA: '#a54399', names: ['0SA', '0SB', '4SA', '4SB', '7SA', '7SB', '8SA', '8SB', '9SA', '9SB', 'ASA', 'ASB', 'BSA', 'BSB', 'CSA', 'CSB', 'DSA', 'DSB', 'ESA', 'ESB', 'FSA', 'FSB', 'GSA', 'GSB', 'HSA', 'HSB', 'ISA', 'ISB', 'JSA', 'JSB', 'KSA', 'KSB', '0sA', '0sB', '4sA', '4sB', '7sA', '7sB', '8sA', '8sB', '9sA', '9sB', 'AsA', 'AsB', 'BsA', 'BsB', 'CsA', 'CsB', 'DsA', 'DsB', 'EsA', 'EsB', 'FsA', 'FsB', 'GsA', 'GsB', 'HsA', 'HsB', 'IsA', 'IsB', 'JsA', 'JsB', 'KsA', 'KsB'] }, }, { name: 'Neu5Gc', common: { colorA: '#8fcce9', names: ['NGC', 'NGE'] }, charmm: { colorA: '#8fcce9', names: [] }, glycam: { colorA: '#8fcce9', names: ['0GL', '4GL', '7GL', '8GL', '9GL', 'CGL', 'DGL', 'EGL', 'FGL', 'GGL', 'HGL', 'IGL', 'JGL', 'KGL', '0gL', '4gL', '7gL', '8gL', '9gL', 'AgL', 'BgL', 'CgL', 'DgL', 'EgL', 'FgL', 'GgL', 'HgL', 'IgL', 'JgL', 'KgL'] }, }, { name: 'Neu', common: { colorA: '#a17a4d', names: [] }, charmm: { colorA: '#a17a4d', names: [] }, glycam: { colorA: '#a17a4d', names: [] }, }] }, /* === Flat hexagon === */ { shape: [Shapes.FlatHexagon] /* Flat hexagon */, axisUp: [0, 0, 1], instances: [{ name: 'Bac', common: { colorA: '#0090bc', names: ['B6D'] }, charmm: { colorA: '#0090bc', names: [] }, glycam: { colorA: '#0090bc', names: ['0BC', '3BC', '0bC', '3bC'] }, }, { name: 'LDManHep', common: { colorA: '#00a651', names: ['GMH'] }, charmm: { colorA: '#00a651', names: [] }, glycam: { colorA: '#00a651', names: [] }, }, { name: 'Kdo', common: { colorA: '#ffd400', names: ['KDO'] }, charmm: { colorA: '#ffd400', names: [] }, glycam: { colorA: '#ffd400', names: [] }, }, { name: 'Dha', common: { colorA: '#f47920', names: [] }, charmm: { colorA: '#f47920', names: [] }, glycam: { colorA: '#f47920', names: [] }, }, { name: 'DDManHep', common: { colorA: '#f69ea1', names: [] }, charmm: { colorA: '#f69ea1', names: [] }, glycam: { colorA: '#f69ea1', names: [] }, }, { name: 'MurNAc', common: { colorA: '#a54399', names: ['AMU'] }, charmm: { colorA: '#a54399', names: [] }, glycam: { colorA: '#a54399', names: [] }, }, { name: 'MurNGc', common: { colorA: '#8fcce9', names: [] }, charmm: { colorA: '#8fcce9', names: [] }, glycam: { colorA: '#8fcce9', names: [] }, }, { name: 'Mur', common: { colorA: '#a17a4d', names: ['MUR'] }, charmm: { colorA: '#a17a4d', names: [] }, glycam: { colorA: '#a17a4d', names: [] }, }] }, /* === Flat pentagon === */ { shape: [Shapes.FlatPentagon] /* Flat pentagon */, axisUp: [0, 0, 1], instances: [{ name: 'Api', common: { colorA: '#0090bc', names: ['XXM'] }, charmm: { colorA: '#0090bc', names: [] }, glycam: { colorA: '#0090bc', names: [] }, }, { name: 'Fruc', common: { colorA: '#00a651', names: ['BDF'] }, charmm: { colorA: '#00a651', names: ['AFRU', 'BFRU'] }, glycam: { colorA: '#00a651', names: ['0CA', '0CB', '1CA', '1CB', '2CA', '2CB', '3CA', '3CB', '4CA', '4CB', '5CA', '5CB', 'WCA', 'WCB', '0CD', '0CU', '1CD', '1CU', '2CD', '2CU', '3CD', '3CU', '4CD', '4CU', '6CD', '6CU', 'WCD', 'WCU', 'VCD', 'VCU', 'UCD', 'UCU', 'QCD', 'QCU', '0cA', '0cB', '1cA', '1cB', '2cA', '2cB', '3cA', '3cB', '4cA', '4cB', '5cA', '5cB', 'WcA', 'WcB', '0cD', '0cU', '1cD', '1cU', '2cD', '2cU', '3cD', '3cU', '4cD', '4cU', '6cD', '6cU', 'WcD', 'WcU', 'VcD', 'VcU', 'UcD', 'UcU', 'QcD', 'QcU'] }, }, { name: 'Tag', common: { colorA: '#ffd400', names: ['T6T'] }, charmm: { colorA: '#ffd400', names: [] }, glycam: { colorA: '#ffd400', names: ['0JA', '0JB', '1JA', '1JB', '2JA', '2JB', '3JA', '3JB', '4JA', '4JB', '5JA', '5JB', 'WJA', 'WJB', '0JD', '0JU', '1JD', '1JU', '2JD', '2JU', '3JD', '3JU', '4JD', '4JU', '6JD', '6JU', 'WJD', 'WJU', 'VJD', 'VJU', 'UJD', 'UJU', 'QJD', 'QJU', '0jA', '0jB', '1jA', '1jB', '2jA', '2jB', '3jA', '3jB', '4jA', '4jB', '5jA', '5jB', 'WjA', 'WjB', '0jD', '0jU', '1jD', '1jU', '2jD', '2jU', '3jD', '3jU', '4jD', '4jU', '6jD', '6jU', 'WjD', 'WjU', 'VjD', 'VjU', 'UjD', 'UjU', 'QjD', 'QjU'] }, }, { name: 'Sor', common: { colorA: '#f47920', names: ['SOE'] }, charmm: { colorA: '#f47920', names: [] }, glycam: { colorA: '#f47920', names: ['0BA', '0BB', '1BA', '1BB', '2BA', '2BB', '3BA', '3BB', '4BA', '4BB', '5BA', '5BB', 'WBA', 'WBB', '0BD', '0BU', '1BD', '1BU', '2BD', '2BU', '3BD', '3BU', '4BD', '4BU', '6BD', '6BU', 'WBD', 'WBU', 'VBD', 'VBU', 'UBD', 'UBU', 'QBD', 'QBU', '0bA', '0bB', '1bA', '1bB', '2bA', '2bB', '3bA', '3bB', '4bA', '4bB', '5bA', '5bB', 'WbA', 'WbB', '0bD', '0bU', '1bD', '1bU', '2bD', '2bU', '3bD', '3bU', '4bD', '4bU', '6bD', '6bU', 'WbD', 'WbU', 'VbD', 'VbU', 'UbD', 'UbU', 'QbD', 'QbU'] }, }, { name: 'Psi', common: { colorA: '#f69ea1', names: [] }, charmm: { colorA: '#f69ea1', names: [] }, glycam: { colorA: '#f69ea1', names: [] } }] }, /* === Flat diamond === */ { shape: [Shapes.FlatDiamond] /* Flat pentagon */, axisUp: [0, 0, 1], instances: [{ name: 'Pse', common: { colorA: '#00a850', names: ['6PZ'] }, charmm: { colorA: '#00a850', names: [] }, glycam: { colorA: '#00a850', names: [] } }, { name: 'Leg', common: { colorA: '#f9d10d', names: [] }, charmm: { colorA: '#f9d10d', names: [] }, glycam: { colorA: '#f9d10d', names: [] } }, { name: 'Aci', common: { colorA: '#f69e9d', names: [] }, charmm: { colorA: '#f69e9d', names: [] }, glycam: { colorA: '#f69e9d', names: [] } }, { name: '4eLeg', common: { colorA: '#89c6e3', names: [] }, charmm: { colorA: '#89c6e3', names: [] }, glycam: { colorA: '#89c6e3', names: [] } }] }]; const mappedData = (function () { const map = Core.Utils.FastMap.create<string, RepresentationEntry>(); for (const shape of data) { for (const instance of shape.instances) { const entry = (name: string, elem: any) => map.set(name, { instanceName: instance.name, name, color: elem.colorB ? [Visualization.Color.fromHexString(elem.colorA), Visualization.Color.fromHexString(elem.colorB)] : [Visualization.Color.fromHexString(elem.colorA)], shape: shape.shape, axisUp: shape.axisUp, axisSide: [1, 0, 0] }) for (const name of instance.common.names) entry(name, instance.common); //for (const name of instance.charmm.names) entry(name, instance.charmm); //for (const name of instance.glycam.names) entry(name, instance.glycam); } } return map; })(); export function isResidueRepresentable(name: string) { return mappedData.has(name); } export function getResidueRepresentation(name: string) { return mappedData.get(name); } }
the_stack
// IMPORTANT // This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator // Generated from: https://firestore.googleapis.com/$discovery/rest?version=v1beta1 /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Google Cloud Firestore API v1beta1 */ function load(name: "firestore", version: "v1beta1"): PromiseLike<void>; function load(name: "firestore", version: "v1beta1", callback: () => any): void; const projects: firestore.ProjectsResource; namespace firestore { interface ArrayValue { /** Values in the array. */ values?: Value[]; } interface BatchGetDocumentsRequest { /** * The names of the documents to retrieve. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * The request will fail if any of the document is not a child resource of the * given `database`. Duplicate names will be elided. */ documents?: string[]; /** * The fields to return. If not set, returns all fields. * * If a document has a field that is not present in this mask, that field will * not be returned in the response. */ mask?: DocumentMask; /** * Starts a new transaction and reads the documents. * Defaults to a read-only transaction. * The new transaction ID will be returned as the first response in the * stream. */ newTransaction?: TransactionOptions; /** * Reads documents as they were at the given time. * This may not be older than 60 seconds. */ readTime?: string; /** Reads documents in a transaction. */ transaction?: string; } interface BatchGetDocumentsResponse { /** A document that was requested. */ found?: Document; /** * A document name that was requested but does not exist. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ missing?: string; /** * The time at which the document was read. * This may be monotically increasing, in this case the previous documents in * the result stream are guaranteed not to have changed between their * read_time and this one. */ readTime?: string; /** * The transaction that was started as part of this request. * Will only be set in the first response, and only if * BatchGetDocumentsRequest.new_transaction was set in the request. */ transaction?: string; } interface BeginTransactionRequest { /** * The options for the transaction. * Defaults to a read-write transaction. */ options?: TransactionOptions; } interface BeginTransactionResponse { /** The transaction that was started. */ transaction?: string; } interface CollectionSelector { /** * When false, selects only collections that are immediate children of * the `parent` specified in the containing `RunQueryRequest`. * When true, selects all descendant collections. */ allDescendants?: boolean; /** * The collection ID. * When set, selects only collections with this ID. */ collectionId?: string; } interface CommitRequest { /** * If non-empty, applies all writes in this transaction, and commits it. * Otherwise, applies the writes as if they were in their own transaction. */ transaction?: string; /** * The writes to apply. * * Always executed atomically and in order. */ writes?: Write[]; } interface CommitResponse { /** The time at which the commit occurred. */ commitTime?: string; /** * The result of applying the writes. * * This i-th write result corresponds to the i-th write in the * request. */ writeResults?: WriteResult[]; } interface CompositeFilter { /** * The list of filters to combine. * Must contain at least one filter. */ filters?: Filter[]; /** The operator for combining multiple filters. */ op?: string; } interface Cursor { /** * If the position is just before or just after the given values, relative * to the sort order defined by the query. */ before?: boolean; /** * The values that represent a position, in the order they appear in * the order by clause of a query. * * Can contain fewer values than specified in the order by clause. */ values?: Value[]; } interface Document { /** * Output only. The time at which the document was created. * * This value increases monotonically when a document is deleted then * recreated. It can also be compared to values from other documents and * the `read_time` of a query. */ createTime?: string; /** * The document's fields. * * The map keys represent field names. * * A simple field name contains only characters `a` to `z`, `A` to `Z`, * `0` to `9`, or `_`, and must not start with `0` to `9` or `_`. For example, * `foo_bar_17`. * * Field names matching the regular expression `__.&#42;__` are reserved. Reserved * field names are forbidden except in certain documented contexts. The map * keys, represented as UTF-8, must not exceed 1,500 bytes and cannot be * empty. * * Field paths may be used in other contexts to refer to structured fields * defined here. For `map_value`, the field path is represented by the simple * or quoted field names of the containing fields, delimited by `.`. For * example, the structured field * `"foo" : { map_value: { "x&y" : { string_value: "hello" }}}` would be * represented by the field path `foo.x&y`. * * Within a field path, a quoted field name starts and ends with `` ` `` and * may contain any character. Some characters, including `` ` ``, must be * escaped using a `\`. For example, `` `x&y` `` represents `x&y` and * `` `bak\`tik` `` represents `` bak`tik ``. */ fields?: Record<string, Value>; /** * The resource name of the document, for example * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ name?: string; /** * Output only. The time at which the document was last changed. * * This value is initally set to the `create_time` then increases * monotonically with each change to the document. It can also be * compared to values from other documents and the `read_time` of a query. */ updateTime?: string; } interface DocumentChange { /** * The new state of the Document. * * If `mask` is set, contains only fields that were updated or added. */ document?: Document; /** A set of target IDs for targets that no longer match this document. */ removedTargetIds?: number[]; /** A set of target IDs of targets that match this document. */ targetIds?: number[]; } interface DocumentDelete { /** The resource name of the Document that was deleted. */ document?: string; /** * The read timestamp at which the delete was observed. * * Greater or equal to the `commit_time` of the delete. */ readTime?: string; /** A set of target IDs for targets that previously matched this entity. */ removedTargetIds?: number[]; } interface DocumentMask { /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ fieldPaths?: string[]; } interface DocumentRemove { /** The resource name of the Document that has gone out of view. */ document?: string; /** * The read timestamp at which the remove was observed. * * Greater or equal to the `commit_time` of the change/delete/remove. */ readTime?: string; /** A set of target IDs for targets that previously matched this document. */ removedTargetIds?: number[]; } interface DocumentTransform { /** The name of the document to transform. */ document?: string; /** * The list of transformations to apply to the fields of the document, in * order. */ fieldTransforms?: FieldTransform[]; } interface DocumentsTarget { /** * The names of the documents to retrieve. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * The request will fail if any of the document is not a child resource of * the given `database`. Duplicate names will be elided. */ documents?: string[]; } interface ExistenceFilter { /** * The total count of documents that match target_id. * * If different from the count of documents in the client that match, the * client must manually determine which documents no longer match the target. */ count?: number; /** The target ID to which this filter applies. */ targetId?: number; } interface FieldFilter { /** The field to filter by. */ field?: FieldReference; /** The operator to filter by. */ op?: string; /** The value to compare to. */ value?: Value; } interface FieldReference { fieldPath?: string; } interface FieldTransform { /** * The path of the field. See Document.fields for the field path syntax * reference. */ fieldPath?: string; /** Sets the field to the given server value. */ setToServerValue?: string; } interface Filter { /** A composite filter. */ compositeFilter?: CompositeFilter; /** A filter on a document field. */ fieldFilter?: FieldFilter; /** A filter that takes exactly one argument. */ unaryFilter?: UnaryFilter; } interface Index { /** The collection ID to which this index applies. Required. */ collectionId?: string; /** The fields to index. */ fields?: IndexField[]; /** The resource name of the index. */ name?: string; /** * The state of the index. * The state is read-only. * @OutputOnly */ state?: string; } interface IndexField { /** * The path of the field. Must match the field path specification described * by google.firestore.v1beta1.Document.fields. * Special field path `__name__` may be used by itself or at the end of a * path. `__type__` may be used only at the end of path. */ fieldPath?: string; /** The field's mode. */ mode?: string; } interface IndexOperationMetadata { /** * True if the [google.longrunning.Operation] was cancelled. If the * cancellation is in progress, cancelled will be true but * google.longrunning.Operation.done will be false. */ cancelled?: boolean; /** Progress of the existing operation, measured in number of documents. */ documentProgress?: Progress; /** * The time the operation ended, either successfully or otherwise. Unset if * the operation is still active. */ endTime?: string; /** * The index resource that this operation is acting on. For example: * `projects/{project_id}/databases/{database_id}/indexes/{index_id}` */ index?: string; /** The type of index operation. */ operationType?: string; /** The time that work began on the operation. */ startTime?: string; } interface LatLng { /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ latitude?: number; /** The longitude in degrees. It must be in the range [-180.0, +180.0]. */ longitude?: number; } interface ListCollectionIdsResponse { /** The collection ids. */ collectionIds?: string[]; /** A page token that may be used to continue the list. */ nextPageToken?: string; } interface ListDocumentsResponse { /** The Documents found. */ documents?: Document[]; /** The next page token. */ nextPageToken?: string; } interface ListIndexesResponse { /** The indexes. */ indexes?: Index[]; /** The standard List next-page token. */ nextPageToken?: string; } interface ListenRequest { /** A target to add to this stream. */ addTarget?: Target; /** Labels associated with this target change. */ labels?: Record<string, string>; /** The ID of a target to remove from this stream. */ removeTarget?: number; } interface ListenResponse { /** A Document has changed. */ documentChange?: DocumentChange; /** A Document has been deleted. */ documentDelete?: DocumentDelete; /** * A Document has been removed from a target (because it is no longer * relevant to that target). */ documentRemove?: DocumentRemove; /** * A filter to apply to the set of documents previously returned for the * given target. * * Returned when documents may have been removed from the given target, but * the exact documents are unknown. */ filter?: ExistenceFilter; /** Targets have changed. */ targetChange?: TargetChange; } interface MapValue { /** * The map's fields. * * The map keys represent field names. Field names matching the regular * expression `__.&#42;__` are reserved. Reserved field names are forbidden except * in certain documented contexts. The map keys, represented as UTF-8, must * not exceed 1,500 bytes and cannot be empty. */ fields?: Record<string, Value>; } interface Operation { /** * If the value is `false`, it means the operation is still in progress. * If `true`, the operation is completed, and either `error` or `response` is * available. */ done?: boolean; /** The error result of the operation in case of failure or cancellation. */ error?: Status; /** * Service-specific metadata associated with the operation. It typically * contains progress information and common metadata such as create time. * Some services might not provide such metadata. Any method that returns a * long-running operation should document the metadata type, if any. */ metadata?: Record<string, any>; /** * The server-assigned name, which is only unique within the same service that * originally returns it. If you use the default HTTP mapping, the * `name` should have the format of `operations/some/unique/name`. */ name?: string; /** * The normal response of the operation in case of success. If the original * method returns no data on success, such as `Delete`, the response is * `google.protobuf.Empty`. If the original method is standard * `Get`/`Create`/`Update`, the response should be the resource. For other * methods, the response should have the type `XxxResponse`, where `Xxx` * is the original method name. For example, if the original method name * is `TakeSnapshot()`, the inferred response type is * `TakeSnapshotResponse`. */ response?: Record<string, any>; } interface Order { /** The direction to order by. Defaults to `ASCENDING`. */ direction?: string; /** The field to order by. */ field?: FieldReference; } interface Precondition { /** * When set to `true`, the target document must exist. * When set to `false`, the target document must not exist. */ exists?: boolean; /** * When set, the target document must exist and have been last updated at * that time. */ updateTime?: string; } interface Progress { /** * An estimate of how much work has been completed. Note that this may be * greater than `work_estimated`. */ workCompleted?: string; /** * An estimate of how much work needs to be performed. Zero if the * work estimate is unavailable. May change as work progresses. */ workEstimated?: string; } interface Projection { /** * The fields to return. * * If empty, all fields are returned. To only return the name * of the document, use `['__name__']`. */ fields?: FieldReference[]; } interface QueryTarget { /** * The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` */ parent?: string; /** A structured query. */ structuredQuery?: StructuredQuery; } interface ReadOnly { /** * Reads documents at the given time. * This may not be older than 60 seconds. */ readTime?: string; } interface ReadWrite { /** An optional transaction to retry. */ retryTransaction?: string; } interface RollbackRequest { /** The transaction to roll back. */ transaction?: string; } interface RunQueryRequest { /** * Starts a new transaction and reads the documents. * Defaults to a read-only transaction. * The new transaction ID will be returned as the first response in the * stream. */ newTransaction?: TransactionOptions; /** * Reads documents as they were at the given time. * This may not be older than 60 seconds. */ readTime?: string; /** A structured query. */ structuredQuery?: StructuredQuery; /** Reads documents in a transaction. */ transaction?: string; } interface RunQueryResponse { /** * A query result. * Not set when reporting partial progress. */ document?: Document; /** * The time at which the document was read. This may be monotonically * increasing; in this case, the previous documents in the result stream are * guaranteed not to have changed between their `read_time` and this one. * * If the query returns no results, a response with `read_time` and no * `document` will be sent, and this represents the time at which the query * was run. */ readTime?: string; /** * The number of results that have been skipped due to an offset between * the last response and the current response. */ skippedResults?: number; /** * The transaction that was started as part of this request. * Can only be set in the first response, and only if * RunQueryRequest.new_transaction was set in the request. * If set, no other fields will be set in this response. */ transaction?: string; } interface Status { /** The status code, which should be an enum value of google.rpc.Code. */ code?: number; /** * A list of messages that carry the error details. There is a common set of * message types for APIs to use. */ details?: Array<Record<string, any>>; /** * A developer-facing error message, which should be in English. Any * user-facing error message should be localized and sent in the * google.rpc.Status.details field, or localized by the client. */ message?: string; } interface StructuredQuery { /** A end point for the query results. */ endAt?: Cursor; /** The collections to query. */ from?: CollectionSelector[]; /** * The maximum number of results to return. * * Applies after all other constraints. * Must be >= 0 if specified. */ limit?: number; /** * The number of results to skip. * * Applies before limit, but after all other constraints. Must be >= 0 if * specified. */ offset?: number; /** * The order to apply to the query results. * * Firestore guarantees a stable ordering through the following rules: * * &#42; Any field required to appear in `order_by`, that is not already * specified in `order_by`, is appended to the order in field name order * by default. * &#42; If an order on `__name__` is not specified, it is appended by default. * * Fields are appended with the same sort direction as the last order * specified, or 'ASCENDING' if no order was specified. For example: * * &#42; `SELECT &#42; FROM Foo ORDER BY A` becomes * `SELECT &#42; FROM Foo ORDER BY A, __name__` * &#42; `SELECT &#42; FROM Foo ORDER BY A DESC` becomes * `SELECT &#42; FROM Foo ORDER BY A DESC, __name__ DESC` * &#42; `SELECT &#42; FROM Foo WHERE A > 1` becomes * `SELECT &#42; FROM Foo WHERE A > 1 ORDER BY A, __name__` */ orderBy?: Order[]; /** The projection to return. */ select?: Projection; /** A starting point for the query results. */ startAt?: Cursor; /** The filter to apply. */ where?: Filter; } interface Target { /** A target specified by a set of document names. */ documents?: DocumentsTarget; /** If the target should be removed once it is current and consistent. */ once?: boolean; /** A target specified by a query. */ query?: QueryTarget; /** * Start listening after a specific `read_time`. * * The client must know the state of matching documents at this time. */ readTime?: string; /** * A resume token from a prior TargetChange for an identical target. * * Using a resume token with a different target is unsupported and may fail. */ resumeToken?: string; /** * A client provided target ID. * * If not set, the server will assign an ID for the target. * * Used for resuming a target without changing IDs. The IDs can either be * client-assigned or be server-assigned in a previous stream. All targets * with client provided IDs must be added before adding a target that needs * a server-assigned id. */ targetId?: number; } interface TargetChange { /** The error that resulted in this change, if applicable. */ cause?: Status; /** * The consistent `read_time` for the given `target_ids` (omitted when the * target_ids are not at a consistent snapshot). * * The stream is guaranteed to send a `read_time` with `target_ids` empty * whenever the entire stream reaches a new consistent snapshot. ADD, * CURRENT, and RESET messages are guaranteed to (eventually) result in a * new consistent snapshot (while NO_CHANGE and REMOVE messages are not). * * For a given stream, `read_time` is guaranteed to be monotonically * increasing. */ readTime?: string; /** * A token that can be used to resume the stream for the given `target_ids`, * or all targets if `target_ids` is empty. * * Not set on every target change. */ resumeToken?: string; /** The type of change that occurred. */ targetChangeType?: string; /** * The target IDs of targets that have changed. * * If empty, the change applies to all targets. * * For `target_change_type=ADD`, the order of the target IDs matches the order * of the requests to add the targets. This allows clients to unambiguously * associate server-assigned target IDs with added targets. * * For other states, the order of the target IDs is not defined. */ targetIds?: number[]; } interface TransactionOptions { /** The transaction can only be used for read operations. */ readOnly?: ReadOnly; /** The transaction can be used for both read and write operations. */ readWrite?: ReadWrite; } interface UnaryFilter { /** The field to which to apply the operator. */ field?: FieldReference; /** The unary operator to apply. */ op?: string; } interface Value { /** * An array value. * * Cannot contain another array value. */ arrayValue?: ArrayValue; /** A boolean value. */ booleanValue?: boolean; /** * A bytes value. * * Must not exceed 1 MiB - 89 bytes. * Only the first 1,500 bytes are considered by queries. */ bytesValue?: string; /** A double value. */ doubleValue?: number; /** A geo point value representing a point on the surface of Earth. */ geoPointValue?: LatLng; /** An integer value. */ integerValue?: string; /** A map value. */ mapValue?: MapValue; /** A null value. */ nullValue?: string; /** * A reference to a document. For example: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ referenceValue?: string; /** * A string value. * * The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes. * Only the first 1,500 bytes of the UTF-8 representation are considered by * queries. */ stringValue?: string; /** * A timestamp value. * * Precise only to microseconds. When stored, any additional precision is * rounded down. */ timestampValue?: string; } interface Write { /** * An optional precondition on the document. * * The write will fail if this is set and not met by the target document. */ currentDocument?: Precondition; /** * A document name to delete. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ delete?: string; /** * Applies a tranformation to a document. * At most one `transform` per document is allowed in a given request. * An `update` cannot follow a `transform` on the same document in a given * request. */ transform?: DocumentTransform; /** A document to write. */ update?: Document; /** * The fields to update in this write. * * This field can be set only when the operation is `update`. * None of the field paths in the mask may contain a reserved name. * If the document exists on the server and has fields not referenced in the * mask, they are left unchanged. * Fields referenced in the mask, but not present in the input document, are * deleted from the document on the server. * The field paths in this mask must not contain a reserved field name. */ updateMask?: DocumentMask; } interface WriteRequest { /** Labels associated with this write request. */ labels?: Record<string, string>; /** * The ID of the write stream to resume. * This may only be set in the first message. When left empty, a new write * stream will be created. */ streamId?: string; /** * A stream token that was previously sent by the server. * * The client should set this field to the token from the most recent * WriteResponse it has received. This acknowledges that the client has * received responses up to this token. After sending this token, earlier * tokens may not be used anymore. * * The server may close the stream if there are too many unacknowledged * responses. * * Leave this field unset when creating a new stream. To resume a stream at * a specific point, set this field and the `stream_id` field. * * Leave this field unset when creating a new stream. */ streamToken?: string; /** * The writes to apply. * * Always executed atomically and in order. * This must be empty on the first request. * This may be empty on the last request. * This must not be empty on all other requests. */ writes?: Write[]; } interface WriteResponse { /** The time at which the commit occurred. */ commitTime?: string; /** * The ID of the stream. * Only set on the first message, when a new stream was created. */ streamId?: string; /** * A token that represents the position of this response in the stream. * This can be used by a client to resume the stream at this point. * * This field is always set. */ streamToken?: string; /** * The result of applying the writes. * * This i-th write result corresponds to the i-th write in the * request. */ writeResults?: WriteResult[]; } interface WriteResult { /** * The results of applying each DocumentTransform.FieldTransform, in the * same order. */ transformResults?: Value[]; /** * The last update time of the document after applying the write. Not set * after a `delete`. * * If the write did not actually change the document, this will be the * previous update_time. */ updateTime?: string; } interface DocumentsResource { /** * Gets multiple documents. * * Documents returned by this method are not guaranteed to be returned in the * same order that they were requested. */ batchGet(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** * The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ database: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<BatchGetDocumentsResponse>; /** Starts a new transaction. */ beginTransaction(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** * The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ database: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<BeginTransactionResponse>; /** Commits a transaction, while optionally updating documents. */ commit(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** * The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ database: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<CommitResponse>; /** Creates a new document. */ createDocument(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** The collection ID, relative to `parent`, to list. For example: `chatrooms`. */ collectionId: string; /** * The client-assigned document ID to use for this document. * * Optional. If not specified, an ID will be assigned by the service. */ documentId?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ "mask.fieldPaths"?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * The parent resource. For example: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<Document>; /** Deletes a document. */ delete(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** * When set to `true`, the target document must exist. * When set to `false`, the target document must not exist. */ "currentDocument.exists"?: boolean; /** * When set, the target document must exist and have been last updated at * that time. */ "currentDocument.updateTime"?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The resource name of the Document to delete. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<{}>; /** Gets a single document. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ "mask.fieldPaths"?: string; /** * The resource name of the Document to get. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Reads the version of the document at the given time. * This may not be older than 60 seconds. */ readTime?: string; /** Reads the document in a transaction. */ transaction?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<Document>; /** Lists documents. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** * The collection ID, relative to `parent`, to list. For example: `chatrooms` * or `messages`. */ collectionId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ "mask.fieldPaths"?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The order to sort results by. For example: `priority desc, name`. */ orderBy?: string; /** The maximum number of documents to return. */ pageSize?: number; /** The `next_page_token` value returned from a previous List request, if any. */ pageToken?: string; /** * The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Reads documents as they were at the given time. * This may not be older than 60 seconds. */ readTime?: string; /** * If the list should show missing documents. A missing document is a * document that does not exist but has sub-documents. These documents will * be returned with a key but will not have fields, Document.create_time, * or Document.update_time set. * * Requests with `show_missing` may not specify `where` or * `order_by`. */ showMissing?: boolean; /** Reads documents in a transaction. */ transaction?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ListDocumentsResponse>; /** Lists all the collection IDs underneath a document. */ listCollectionIds(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The maximum number of results to return. */ pageSize?: number; /** * A page token. Must be a value from * ListCollectionIdsResponse. */ pageToken?: string; /** * The parent document. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ListCollectionIdsResponse>; /** Listens to changes. */ listen(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** * The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ database: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ListenResponse>; /** Updates or inserts a document. */ patch(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** * When set to `true`, the target document must exist. * When set to `false`, the target document must not exist. */ "currentDocument.exists"?: boolean; /** * When set, the target document must exist and have been last updated at * that time. */ "currentDocument.updateTime"?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ "mask.fieldPaths"?: string; /** * The resource name of the document, for example * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ "updateMask.fieldPaths"?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<Document>; /** Rolls back a transaction. */ rollback(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** * The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ database: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<{}>; /** Runs a query. */ runQuery(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<RunQueryResponse>; /** Streams batches of document updates and deletes, in order. */ write(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** * The database name. In the format: * `projects/{project_id}/databases/{database_id}`. * This is only required in the first message. */ database: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<WriteResponse>; } interface IndexesResource { /** * Creates the specified index. * A newly created index's initial state is `CREATING`. On completion of the * returned google.longrunning.Operation, the state will be `READY`. * If the index already exists, the call will return an `ALREADY_EXISTS` * status. * * During creation, the process could result in an error, in which case the * index will move to the `ERROR` state. The process can be recovered by * fixing the data that caused the error, removing the index with * delete, then re-creating the index with * create. * * Indexes with a single field cannot be created. */ create(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * The name of the database this index will apply to. For example: * `projects/{project_id}/databases/{database_id}` */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<Operation>; /** Deletes an index. */ delete(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The index name. For example: * `projects/{project_id}/databases/{database_id}/indexes/{index_id}` */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<{}>; /** Gets an index. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * The name of the index. For example: * `projects/{project_id}/databases/{database_id}/indexes/{index_id}` */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<Index>; /** Lists the indexes that match the specified filters. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; filter?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The standard List page size. */ pageSize?: number; /** The standard List page token. */ pageToken?: string; /** * The database name. For example: * `projects/{project_id}/databases/{database_id}` */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ListIndexesResponse>; } interface DatabasesResource { documents: DocumentsResource; indexes: IndexesResource; } interface ProjectsResource { databases: DatabasesResource; } } }
the_stack
* Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ import React, { Component } from 'react'; import { EuiTitle, EuiFlyout, EuiFlyoutBody, EuiFlyoutHeader, EuiLink, EuiIcon, EuiCallOut, EuiLoadingSpinner, EuiInMemoryTable, EuiToolTip, EuiText, EuiSpacer, } from '@elastic/eui'; import { SearchFilterConfig } from '@elastic/eui'; import { i18n } from '@osd/i18n'; import { FormattedMessage } from '@osd/i18n/react'; import { IBasePath } from 'src/core/public'; import { getDefaultTitle, getSavedObjectLabel } from '../../../lib'; import { SavedObjectWithMetadata, SavedObjectRelation } from '../../../types'; export interface RelationshipsProps { basePath: IBasePath; getRelationships: (type: string, id: string) => Promise<SavedObjectRelation[]>; savedObject: SavedObjectWithMetadata; close: () => void; goInspectObject: (obj: SavedObjectWithMetadata) => void; canGoInApp: (obj: SavedObjectWithMetadata) => boolean; } export interface RelationshipsState { relationships: SavedObjectRelation[]; isLoading: boolean; error?: string; } export class Relationships extends Component<RelationshipsProps, RelationshipsState> { constructor(props: RelationshipsProps) { super(props); this.state = { relationships: [], isLoading: false, error: undefined, }; } UNSAFE_componentWillMount() { this.getRelationshipData(); } UNSAFE_componentWillReceiveProps(nextProps: RelationshipsProps) { if (nextProps.savedObject.id !== this.props.savedObject.id) { this.getRelationshipData(); } } async getRelationshipData() { const { savedObject, getRelationships } = this.props; this.setState({ isLoading: true }); try { const relationships = await getRelationships(savedObject.type, savedObject.id); this.setState({ relationships, isLoading: false, error: undefined }); } catch (err) { this.setState({ error: err.message, isLoading: false }); } } renderError() { const { error } = this.state; if (!error) { return null; } return ( <EuiCallOut title={ <FormattedMessage id="savedObjectsManagement.objectsTable.relationships.renderErrorMessage" defaultMessage="Error" /> } color="danger" > {error} </EuiCallOut> ); } renderRelationships() { const { goInspectObject, savedObject, basePath } = this.props; const { relationships, isLoading, error } = this.state; if (error) { return this.renderError(); } if (isLoading) { return <EuiLoadingSpinner size="xl" />; } const columns = [ { field: 'type', name: i18n.translate('savedObjectsManagement.objectsTable.relationships.columnTypeName', { defaultMessage: 'Type', }), width: '50px', align: 'center', description: i18n.translate( 'savedObjectsManagement.objectsTable.relationships.columnTypeDescription', { defaultMessage: 'Type of the saved object' } ), sortable: false, render: (type: string, object: SavedObjectWithMetadata) => { return ( <EuiToolTip position="top" content={getSavedObjectLabel(type)}> <EuiIcon aria-label={getSavedObjectLabel(type)} type={object.meta.icon || 'apps'} size="s" data-test-subj="relationshipsObjectType" /> </EuiToolTip> ); }, }, { field: 'relationship', name: i18n.translate( 'savedObjectsManagement.objectsTable.relationships.columnRelationshipName', { defaultMessage: 'Direct relationship' } ), dataType: 'string', sortable: false, width: '125px', 'data-test-subj': 'directRelationship', render: (relationship: string) => { if (relationship === 'parent') { return ( <EuiText size="s"> <FormattedMessage id="savedObjectsManagement.objectsTable.relationships.columnRelationship.parentAsValue" defaultMessage="Parent" /> </EuiText> ); } if (relationship === 'child') { return ( <EuiText size="s"> <FormattedMessage id="savedObjectsManagement.objectsTable.relationships.columnRelationship.childAsValue" defaultMessage="Child" /> </EuiText> ); } }, }, { field: 'meta.title', name: i18n.translate('savedObjectsManagement.objectsTable.relationships.columnTitleName', { defaultMessage: 'Title', }), description: i18n.translate( 'savedObjectsManagement.objectsTable.relationships.columnTitleDescription', { defaultMessage: 'Title of the saved object' } ), dataType: 'string', sortable: false, render: (title: string, object: SavedObjectWithMetadata) => { const { path = '' } = object.meta.inAppUrl || {}; const canGoInApp = this.props.canGoInApp(object); if (!canGoInApp) { return ( <EuiText size="s" data-test-subj="relationshipsTitle"> {title || getDefaultTitle(object)} </EuiText> ); } return ( <EuiLink href={basePath.prepend(path)} data-test-subj="relationshipsTitle"> {title || getDefaultTitle(object)} </EuiLink> ); }, }, { name: i18n.translate( 'savedObjectsManagement.objectsTable.relationships.columnActionsName', { defaultMessage: 'Actions' } ), actions: [ { name: i18n.translate( 'savedObjectsManagement.objectsTable.relationships.columnActions.inspectActionName', { defaultMessage: 'Inspect' } ), description: i18n.translate( 'savedObjectsManagement.objectsTable.relationships.columnActions.inspectActionDescription', { defaultMessage: 'Inspect this saved object' } ), type: 'icon', icon: 'inspect', 'data-test-subj': 'relationshipsTableAction-inspect', onClick: (object: SavedObjectWithMetadata) => goInspectObject(object), available: (object: SavedObjectWithMetadata) => !!object.meta.editUrl, }, ], }, ]; const filterTypesMap = new Map( relationships.map((relationship) => [ relationship.type, { value: relationship.type, name: relationship.type, view: relationship.type, }, ]) ); const search = { filters: [ { type: 'field_value_selection', field: 'relationship', name: i18n.translate( 'savedObjectsManagement.objectsTable.relationships.search.filters.relationship.name', { defaultMessage: 'Direct relationship' } ), multiSelect: 'or', options: [ { value: 'parent', name: 'parent', view: i18n.translate( 'savedObjectsManagement.objectsTable.relationships.search.filters.relationship.parentAsValue.view', { defaultMessage: 'Parent' } ), }, { value: 'child', name: 'child', view: i18n.translate( 'savedObjectsManagement.objectsTable.relationships.search.filters.relationship.childAsValue.view', { defaultMessage: 'Child' } ), }, ], }, { type: 'field_value_selection', field: 'type', name: i18n.translate( 'savedObjectsManagement.objectsTable.relationships.search.filters.type.name', { defaultMessage: 'Type' } ), multiSelect: 'or', options: [...filterTypesMap.values()], }, ] as SearchFilterConfig[], }; return ( <div> <EuiCallOut> <p> {i18n.translate( 'savedObjectsManagement.objectsTable.relationships.relationshipsTitle', { defaultMessage: 'Here are the saved objects related to {title}. ' + 'Deleting this {type} affects its parent objects, but not its children.', values: { type: savedObject.type, title: savedObject.meta.title || getDefaultTitle(savedObject), }, } )} </p> </EuiCallOut> <EuiSpacer /> <EuiInMemoryTable items={relationships} columns={columns as any} pagination={true} search={search} rowProps={() => ({ 'data-test-subj': `relationshipsTableRow`, })} /> </div> ); } render() { const { close, savedObject } = this.props; return ( <EuiFlyout onClose={close}> <EuiFlyoutHeader hasBorder> <EuiTitle size="m"> <h2> <EuiToolTip position="top" content={getSavedObjectLabel(savedObject.type)}> <EuiIcon aria-label={getSavedObjectLabel(savedObject.type)} size="m" type={savedObject.meta.icon || 'apps'} /> </EuiToolTip> &nbsp;&nbsp; {savedObject.meta.title || getDefaultTitle(savedObject)} </h2> </EuiTitle> </EuiFlyoutHeader> <EuiFlyoutBody>{this.renderRelationships()}</EuiFlyoutBody> </EuiFlyout> ); } }
the_stack
import path from 'path'; import _ from 'lodash'; import uuid from 'uuid'; import inquirer from 'inquirer'; import { $TSContext, stateManager, pathManager, JSONUtilities, exitOnNextTick } from 'amplify-cli-core'; import { functionParametersFileName } from './constants'; import { categoryName } from '../../../constants'; export const validKey = new RegExp(/^[a-zA-Z0-9_]+$/); export const getStoredEnvironmentVariables = (resourceName: string, currentEnvName?: string): Record<string, string> => { const storedList = getStoredList(resourceName); const storedReferences = getStoredReferences(resourceName); const storedParameters = getStoredParameters(resourceName); const storedKeyValue = getStoredKeyValue(resourceName, currentEnvName); const environmentVariables = {}; // Search for key and take matched // environment variables based on 4 steps storedList.forEach(({ environmentVariableName, cloudFormationParameterName }) => { // 1. Check if format is correct in function-parameter.json if (!environmentVariableName) return; if (!cloudFormationParameterName) return; // 2. Check if key exists in CFn template if (!storedParameters[cloudFormationParameterName]) return; if (storedReferences[environmentVariableName]?.Ref !== cloudFormationParameterName) return; // 3. Check if key exists in team-provider-info.json if (!_.has(storedKeyValue, cloudFormationParameterName)) return; // 4. Take matched environment variables environmentVariables[environmentVariableName] = storedKeyValue[cloudFormationParameterName]; }); return environmentVariables; }; export const saveEnvironmentVariables = (context: $TSContext, resourceName: string, newEnvironmentVariables: Record<string, string>) => { const currentEnvironmentVariables = getStoredEnvironmentVariables(resourceName); _.each(currentEnvironmentVariables, (_, key) => { deleteEnvironmentVariable(resourceName, key); }); _.each(newEnvironmentVariables, (value, key) => { setEnvironmentVariable(context, resourceName, key, value); }); }; export const askEnvironmentVariableCarryOut = async ( context: $TSContext, currentEnvName: string, projectPath: string, yesFlagSet?: boolean, ) => { const teamProviderInfo = stateManager.getTeamProviderInfo(projectPath, { throwIfNotExist: false, default: {}, }); const functions = teamProviderInfo[currentEnvName]?.categories?.function || {}; const functionNames = Object.keys(functions); if (functionNames.length === 0) { return; } const hasEnvVars = !!functionNames.find(funcName => !_.isEmpty(getStoredEnvironmentVariables(funcName, currentEnvName))); if (!hasEnvVars) { return; } const envVarQuestion = async () => { const envVarQuestion: inquirer.ListQuestion = { type: 'list', name: 'envVar', message: 'You have configured environment variables for functions. How do you want to proceed?', choices: [ { value: 'carry', name: 'Carry over existing environment variables to this new environment', }, { value: 'update', name: 'Update environment variables now', }, ], }; if (context.parameters.options.quickstart) return; const { envVar } = yesFlagSet ? { envVar: 'carry' } : await inquirer.prompt(envVarQuestion); if (envVar === 'carry') return; if (envVar === 'update') await envVarSelectFunction(); }; const envVarSelectFunction = async () => { const abortKey = uuid.v4(); const functionNameQuestion: inquirer.ListQuestion = { type: 'list', name: 'functionName', message: 'Select the Lambda function you want to update values', choices: functionNames .map(name => ({ name, value: name, })) .concat({ name: "I'm done", value: abortKey, }), }; const { functionName } = await inquirer.prompt(functionNameQuestion); if (functionName === abortKey) return; await envVarSelectKey(functionName); }; const envVarSelectKey = async (functionName: string) => { const envVars = getStoredEnvironmentVariables(functionName, currentEnvName); const abortKey = uuid.v4(); const keyNameQuestion: inquirer.ListQuestion = { type: 'list', name: 'keyName', message: 'Which function’s environment variables do you want to edit?', choices: Object.keys(envVars) .map(name => ({ name, value: name, })) .concat({ name: "I'm done", value: abortKey, }), }; const { keyName } = await inquirer.prompt(keyNameQuestion); if (keyName === abortKey) { await envVarSelectFunction(); return; } await envVarUpdateValue(functionName, keyName); }; const envVarUpdateValue = async (functionName: string, keyName: string) => { const envVars = getStoredEnvironmentVariables(functionName, currentEnvName); const newValueQuestion: inquirer.InputQuestion = { type: 'input', name: 'newValue', message: 'Enter the environment variable value:', default: envVars[keyName], validate: input => { if (input.length >= 2048) { return 'The value must be 2048 characters or less'; } return true; }, }; const { newValue } = await inquirer.prompt(newValueQuestion); functions[functionName][_.camelCase(keyName)] = newValue; await envVarSelectKey(functionName); }; await envVarQuestion(); Object.keys(functions).forEach(functionName => { setStoredKeyValue(functionName, functions[functionName]); }); }; export const ensureEnvironmentVariableValues = async (context: $TSContext) => { const yesFlagSet = context?.exeInfo?.inputParams?.yes || context?.input?.options?.yes; const currentEnvName = stateManager.getLocalEnvInfo()?.envName; const teamProviderInfo = stateManager.getTeamProviderInfo(undefined, { throwIfNotExist: false, default: {}, }); const functions = teamProviderInfo[currentEnvName]?.categories?.function || {}; const functionNames = Object.keys(functions); if (functionNames.length === 0) { return; } let printedMessage = false; for (const functionName of functionNames) { const storedList = getStoredList(functionName); const storedKeyValue = getStoredKeyValue(functionName); for (const item of storedList) { const envName = item.environmentVariableName; const keyName = item.cloudFormationParameterName; if (storedKeyValue.hasOwnProperty(keyName)) continue; if (!printedMessage) { if (yesFlagSet) { const errMessage = `An error occurred pushing an env "${currentEnvName}" due to missing environment variable values`; context.print.error(errMessage); await context.usageData.emitError(new Error(errMessage)); exitOnNextTick(1); } else { context.print.info(''); context.print.info('Some Lambda function environment variables are defined but missing values.'); context.print.info(''); } printedMessage = true; } const newValueQuestion: inquirer.InputQuestion = { type: 'input', name: 'newValue', message: `Enter the missing environment variable value of ${envName} in ${functionName}:`, validate: input => { if (input.length >= 2048) { return 'The value must be 2048 characters or less'; } return true; }, }; const { newValue } = await inquirer.prompt(newValueQuestion); setStoredKeyValue(functionName, { ...storedKeyValue, [keyName]: newValue, }); } } }; const setEnvironmentVariable = ( context: $TSContext, resourceName: string, newEnvironmentVariableKey: string, newEnvironmentVariableValue: string, ): void => { const newList = getStoredList(resourceName); const newReferences = getStoredReferences(resourceName); const newParameters = getStoredParameters(resourceName); const newKeyValue = getStoredKeyValue(resourceName); const cameledKey = _.camelCase(newEnvironmentVariableKey); newList.push({ cloudFormationParameterName: cameledKey, environmentVariableName: newEnvironmentVariableKey, }); newReferences[newEnvironmentVariableKey] = { Ref: cameledKey }; newParameters[cameledKey] = { Type: 'String' }; newKeyValue[cameledKey] = newEnvironmentVariableValue; setStoredList(resourceName, newList); setStoredReference(resourceName, newReferences); setStoredParameters(resourceName, newParameters); setStoredKeyValue(resourceName, newKeyValue); }; const deleteEnvironmentVariable = (resourceName: string, targetedKey: string): void => { let newList = getStoredList(resourceName); const newReferences = getStoredReferences(resourceName); const newKeyValue = getStoredKeyValue(resourceName); const newParameters = getStoredParameters(resourceName); const cameledKey = _.camelCase(targetedKey); newList = _.filter(newList, item => { return item.cloudFormationParameterName !== cameledKey && item.environmentVariableName !== targetedKey; }); _.unset(newReferences, targetedKey); _.unset(newParameters, cameledKey); _.unset(newKeyValue, cameledKey); setStoredList(resourceName, newList); setStoredReference(resourceName, newReferences); setStoredParameters(resourceName, newParameters); setStoredKeyValue(resourceName, newKeyValue); }; const getStoredList = (resourceName: string): { cloudFormationParameterName: string; environmentVariableName: string }[] => { const projectBackendDirPath = pathManager.getBackendDirPath(); const resourcePath = path.join(projectBackendDirPath, categoryName, resourceName); const functionParameterFilePath = path.join(resourcePath, functionParametersFileName); const functionParameters = (JSONUtilities.readJson(functionParameterFilePath, { throwIfNotExist: false }) as object) || {}; return _.get(functionParameters, 'environmentVariableList', []); }; const setStoredList = (resourceName: string, newList: object): void => { const projectBackendDirPath = pathManager.getBackendDirPath(); const resourcePath = path.join(projectBackendDirPath, categoryName, resourceName); const functionParameterFilePath = path.join(resourcePath, functionParametersFileName); const functionParameters = (JSONUtilities.readJson(functionParameterFilePath, { throwIfNotExist: false }) as object) || {}; _.set(functionParameters, 'environmentVariableList', newList); JSONUtilities.writeJson(functionParameterFilePath, functionParameters); }; const getStoredReferences = (resourceName: string): object => { const projectBackendDirPath = pathManager.getBackendDirPath(); const resourcePath = path.join(projectBackendDirPath, categoryName, resourceName); const cfnFileName = `${resourceName}-cloudformation-template.json`; const cfnFilePath = path.join(resourcePath, cfnFileName); const cfnContent = JSONUtilities.readJson(cfnFilePath, { throwIfNotExist: false }) || {}; return _.get(cfnContent, ['Resources', 'LambdaFunction', 'Properties', 'Environment', 'Variables'], {}); }; const setStoredReference = (resourceName: string, newReferences: object): void => { const projectBackendDirPath = pathManager.getBackendDirPath(); const resourcePath = path.join(projectBackendDirPath, categoryName, resourceName); const cfnFileName = `${resourceName}-cloudformation-template.json`; const cfnFilePath = path.join(resourcePath, cfnFileName); const cfnContent = (JSONUtilities.readJson(cfnFilePath, { throwIfNotExist: false }) as object) || {}; _.set(cfnContent, ['Resources', 'LambdaFunction', 'Properties', 'Environment', 'Variables'], newReferences); JSONUtilities.writeJson(cfnFilePath, cfnContent); }; const getStoredParameters = (resourceName: string): object => { const projectBackendDirPath = pathManager.getBackendDirPath(); const resourcePath = path.join(projectBackendDirPath, categoryName, resourceName); const cfnFileName = `${resourceName}-cloudformation-template.json`; const cfnFilePath = path.join(resourcePath, cfnFileName); const cfnContent = JSONUtilities.readJson(cfnFilePath, { throwIfNotExist: false }) || {}; return _.get(cfnContent, ['Parameters'], {}); }; const setStoredParameters = (resourceName: string, newParameters: object): void => { const projectBackendDirPath = pathManager.getBackendDirPath(); const resourcePath = path.join(projectBackendDirPath, categoryName, resourceName); const cfnFileName = `${resourceName}-cloudformation-template.json`; const cfnFilePath = path.join(resourcePath, cfnFileName); const cfnContent = (JSONUtilities.readJson(cfnFilePath, { throwIfNotExist: false }) as object) || {}; _.set(cfnContent, ['Parameters'], newParameters); JSONUtilities.writeJson(cfnFilePath, cfnContent); }; const getStoredKeyValue = (resourceName: string, currentEnvName?: string): object => { const projectPath = pathManager.findProjectRoot(); const envName = currentEnvName || stateManager.getLocalEnvInfo().envName; const teamProviderInfo = stateManager.getTeamProviderInfo(projectPath, { throwIfNotExist: false }); return _.get(teamProviderInfo, [envName, 'categories', categoryName, resourceName], {}); }; const setStoredKeyValue = (resourceName: string, newKeyValue: object): void => { const projectPath = pathManager.findProjectRoot(); const envName = stateManager.getLocalEnvInfo().envName; const teamProviderInfo = stateManager.getTeamProviderInfo(projectPath, { throwIfNotExist: false }); _.set(teamProviderInfo, [envName, 'categories', categoryName, resourceName], newKeyValue); stateManager.setTeamProviderInfo(projectPath, teamProviderInfo); };
the_stack
import {protoManage} from "../proto/manage" import {globals} from "./globals"; import axios from "axios"; import {convert} from "./convert"; import i18n from '../base/i18n' export module request { export function reqFindSystemInitInfo(req:protoManage.ReqSystemInitInfo):Promise<protoManage.AnsSystemInitInfo> { return new Promise((resolve, reject)=>{ let msg = protoManage.ReqSystemInitInfo.encode(req).finish() request.httpRequest("/system/getInitInfo", msg) .then((response) => { let ans = protoManage.AnsSystemInitInfo.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqManagerLogin(req:protoManage.Manager):Promise<protoManage.Manager> { return new Promise((resolve, reject)=>{ let msg = protoManage.Manager.encode(req).finish() request.httpRequest("/manager/login", msg) .then((response) => { let ans = protoManage.Manager.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqManagerRegister(req:protoManage.Manager):Promise<protoManage.Manager> { return new Promise((resolve, reject)=>{ let msg = protoManage.Manager.encode(req).finish() request.httpRequest("/manager/register", msg) .then((response) => { let ans = protoManage.Manager.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqManagerAdd(req:protoManage.Manager):Promise<protoManage.Manager> { return new Promise((resolve, reject)=>{ let msg = protoManage.Manager.encode(req).finish() request.httpRequest("/manager/add", msg) .then((response) => { let ans = protoManage.Manager.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqManagerNickNameList():Promise<protoManage.AnsManagerList> { return new Promise((resolve, reject)=>{ let req = protoManage.ReqManagerList.create({}) let msg = protoManage.ReqManagerList.encode(req).finish() request.httpRequest("/manager/findNickName", msg) .then((response) => { let ans = protoManage.AnsManagerList.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqManagerList():Promise<protoManage.AnsManagerList> { return new Promise((resolve, reject)=>{ let req = protoManage.ReqManagerList.create({}) let msg = protoManage.ReqManagerList.encode(req).finish() request.httpRequest("/manager/find", msg) .then((response) => { let ans = protoManage.AnsManagerList.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqManagerByID(req:protoManage.Manager):Promise<protoManage.Manager> { return new Promise((resolve, reject)=>{ let msg = protoManage.Manager.encode(req).finish() request.httpRequest("/manager/findByID", msg) .then((response) => { let ans = protoManage.Manager.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqManagerUpdate(req:protoManage.Manager):Promise<protoManage.Manager> { return new Promise((resolve, reject)=>{ let msg = protoManage.Manager.encode(req).finish() request.httpRequest("/manager/update", msg) .then((response) => { let ans = protoManage.Manager.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqManagerUpdatePasswd(req:protoManage.Manager):Promise<protoManage.Manager> { return new Promise((resolve, reject)=>{ let msg = protoManage.Manager.encode(req).finish() request.httpRequest("/manager/updatePasswd", msg) .then((response) => { let ans = protoManage.Manager.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqManagerUpdateSetting(req:protoManage.Manager):Promise<protoManage.Manager> { return new Promise((resolve, reject)=>{ let msg = protoManage.Manager.encode(req).finish() request.httpRequest("/manager/updateSetting", msg) .then((response) => { let ans = protoManage.Manager.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqManagerDel(req:protoManage.Manager):Promise<protoManage.Manager> { return new Promise((resolve, reject)=>{ let msg = protoManage.Manager.encode(req).finish() request.httpRequest("/manager/del", msg) .then((response) => { let ans = protoManage.Manager.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqTopLinkList():Promise<protoManage.AnsTopLinkList> { return new Promise((resolve, reject)=>{ let req = protoManage.ReqTopLinkList.create({}) let msg = protoManage.ReqTopLinkList.encode(req).finish() request.httpRequest("/topLink/find", msg) .then((response) => { let ans = protoManage.AnsTopLinkList.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqTopLinkByID(req:protoManage.TopLink):Promise<protoManage.TopLink> { return new Promise((resolve, reject)=>{ let msg = protoManage.TopLink.encode(req).finish() request.httpRequest("/topLink/findByID", msg) .then((response) => { let ans = protoManage.TopLink.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqTopLinkAdd(req:protoManage.TopLink):Promise<protoManage.TopLink> { return new Promise((resolve, reject)=>{ let msg = protoManage.TopLink.encode(req).finish() request.httpRequest("/topLink/add", msg) .then((response) => { let ans = protoManage.TopLink.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqTopLinkDel(req:protoManage.TopLink):Promise<protoManage.TopLink> { return new Promise((resolve, reject)=>{ let msg = protoManage.TopLink.encode(req).finish() request.httpRequest("/topLink/del", msg) .then((response) => { let ans = protoManage.TopLink.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqTopLinkUpdate(req:protoManage.TopLink):Promise<protoManage.TopLink> { return new Promise((resolve, reject)=>{ let msg = protoManage.TopLink.encode(req).finish() request.httpRequest("/topLink/update", msg) .then((response) => { let ans = protoManage.TopLink.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeList(req:protoManage.ReqNodeList):Promise<protoManage.AnsNodeList> { return new Promise((resolve, reject)=>{ let msg = protoManage.ReqNodeList.encode(req).finish() request.httpRequest("/node/find", msg) .then((response) => { let ans = protoManage.AnsNodeList.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeByID(id: number):Promise<protoManage.Node> { return new Promise((resolve, reject)=>{ let req = protoManage.Node.create({Base:protoManage.Base.create({ID:id})}) let msg = protoManage.Node.encode(req).finish() request.httpRequest("/node/findByID", msg) .then((response) => { let ans = protoManage.Node.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeDel(req:protoManage.Node):Promise<protoManage.Node> { return new Promise((resolve, reject)=>{ let msg = protoManage.Node.encode(req).finish() request.httpRequest("/node/del", msg) .then((response) => { let ans = protoManage.Node.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeFuncList(req:protoManage.ReqNodeFuncList):Promise<protoManage.AnsNodeFuncList> { return new Promise((resolve, reject)=>{ let msg = protoManage.ReqNodeFuncList.encode(req).finish() request.httpRequest("/nodeFunc/find", msg) .then((response) => { let ans = protoManage.AnsNodeFuncList.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeFuncDel(req:protoManage.NodeFunc):Promise<protoManage.NodeFunc> { return new Promise((resolve, reject)=>{ let msg = protoManage.NodeFunc.encode(req).finish() request.httpRequest("/nodeFunc/del", msg) .then((response) => { let ans = protoManage.NodeFunc.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqCallNodeFunc(req:protoManage.ReqNodeFuncCall):Promise<protoManage.Base> { return new Promise((resolve, reject)=>{ let msg = protoManage.ReqNodeFuncCall.encode(req).finish() request.httpRequest("/nodeFuncCall/call", msg) .then((response) => { let ans = protoManage.Base.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeFuncCallList(req:protoManage.ReqNodeFuncCallList):Promise<protoManage.AnsNodeFuncCallList> { return new Promise((resolve, reject)=>{ let msg = protoManage.ReqNodeFuncCallList.encode(req).finish() request.httpRequest("/nodeFuncCall/find", msg) .then((response) => { let ans = protoManage.AnsNodeFuncCallList.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeFuncCallByID(req:protoManage.NodeFuncCall):Promise<protoManage.NodeFuncCall> { return new Promise((resolve, reject)=>{ let msg = protoManage.NodeFuncCall.encode(req).finish() request.httpRequest("/nodeFuncCall/findByID", msg) .then((response) => { let ans = protoManage.NodeFuncCall.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeFuncCallParameterByID(req:protoManage.NodeFuncCall):Promise<protoManage.NodeFuncCall> { return new Promise((resolve, reject)=>{ let msg = protoManage.NodeFuncCall.encode(req).finish() request.httpRequest("/nodeFuncCall/findParameterByID", msg) .then((response) => { let ans = protoManage.NodeFuncCall.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeFuncCallReturnValByID(req:protoManage.NodeFuncCall):Promise<protoManage.NodeFuncCall> { return new Promise((resolve, reject)=>{ let msg = protoManage.NodeFuncCall.encode(req).finish() request.httpRequest("/nodeFuncCall/findReturnValByID", msg) .then((response) => { let ans = protoManage.NodeFuncCall.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeReportList(req:protoManage.ReqNodeReportList):Promise<protoManage.AnsNodeReportList> { return new Promise((resolve, reject)=>{ let msg = protoManage.ReqNodeReportList.encode(req).finish() request.httpRequest("/nodeReport/find", msg) .then((response) => { let ans = protoManage.AnsNodeReportList.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeReportDel(req:protoManage.NodeReport):Promise<protoManage.NodeReport> { return new Promise((resolve, reject)=>{ let msg = protoManage.NodeReport.encode(req).finish() request.httpRequest("/nodeReport/del", msg) .then((response) => { let ans = protoManage.NodeReport.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeReportValList(req:protoManage.ReqNodeReportValList):Promise<protoManage.AnsNodeReportValList> { return new Promise((resolve, reject)=>{ let msg = protoManage.ReqNodeReportValList.encode(req).finish() request.httpRequest("/nodeReportVal/find", msg) .then((response) => { let ans = protoManage.AnsNodeReportValList.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeNotifyList(req:protoManage.ReqNodeNotifyList):Promise<protoManage.AnsNodeNotifyList> { return new Promise((resolve, reject)=>{ let msg = protoManage.ReqNodeNotifyList.encode(req).finish() request.httpRequest("/nodeNotify/find", msg) .then((response) => { let ans = protoManage.AnsNodeNotifyList.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeResourceCheck(req:protoManage.NodeResource):Promise<protoManage.NodeResource> { return new Promise((resolve, reject)=>{ let msg = protoManage.NodeResource.encode(req).finish() request.httpRequest("/nodeResource/check", msg) .then((response) => { let ans = protoManage.NodeResource.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeResourceList(req:protoManage.ReqNodeResourceList):Promise<protoManage.AnsNodeResourceList> { return new Promise((resolve, reject)=>{ let msg = protoManage.ReqNodeResourceList.encode(req).finish() request.httpRequest("/nodeResource/find", msg) .then((response) => { let ans = protoManage.AnsNodeResourceList.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeResourceUpload(req:protoManage.NodeResource, file:Blob, onUploadProgressCall:(e:any)=>void):Promise<protoManage.NodeResource> { return new Promise((resolve, reject)=>{ reqNodeResourceCheck(req).then((ans:protoManage.NodeResource) => { if (ans.Base?.ID != 0){ resolve(ans) }else { let msg = protoManage.NodeResource.encode(req).finish() httpRequestUpLoad("/nodeResource/upload", file, msg, onUploadProgressCall) .then((response:protoManage.NodeResource) => { resolve(response) }).catch(error => { reject(error) }) } }).catch(error => { reject(error) }) }) } export function reqNodeResourceDownLoad(req:protoManage.NodeResource) { httpRequestDownLoad("/nodeResource/download/" + req.Name, Number(req.Base?.ID)) } export function reqNodeResourceDel(req:protoManage.NodeResource):Promise<protoManage.NodeResource> { return new Promise((resolve, reject)=>{ let msg = protoManage.NodeResource.encode(req).finish() request.httpRequest("/nodeResource/del", msg) .then((response) => { let ans = protoManage.NodeResource.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function reqNodeTest(req:protoManage.ReqNodeTest):Promise<protoManage.AnsNodeTest> { return new Promise((resolve, reject)=>{ let msg = protoManage.ReqNodeTest.encode(req).finish() request.httpRequest("/nodeTest/test", msg) .then((response) => { let ans = protoManage.AnsNodeTest.decode(response) resolve(ans) }).catch(error => { reject(error) }) }) } export function httpRequest(path:string, data:Uint8Array):Promise<Uint8Array> { return new Promise((resolve, reject)=>{ let blob = new Blob([data], {type: 'buffer'}); axios({ responseType: 'arraybuffer', method:'post', url: globals.getHttpHost() + path, data: blob, headers:{ 'token':globals.globalsData.manager.info.Token }, timeout: globals.globalsConfig.httpConfig.requestTimeout, }).then(response => { if (response.status == 200) { resolve(new Uint8Array(<Uint8Array>response.data)) }else { httpError(response.status, <Uint8Array>response.data) reject(response) } }).catch(error => { if (error.response != undefined){ httpError(error.response.status, error.response.data) }else{ globals.viewError(i18n.global.t('request.error.fail', { msg: error})); } reject(error) }) }) } export function httpRequestUpLoad(path:string, file:Blob, data:Uint8Array, onUploadProgressCall:(e:any)=>void):Promise<protoManage.NodeResource> { let formData = new FormData(); let str = convert.uint8ArrayToString(data) formData.append("file", file); formData.append("data", str); return new Promise((resolve, reject)=>{ axios({ responseType: 'arraybuffer', method:'post', url: globals.getHttpHost() + path, data: formData, headers:{ 'Content-type':'multipart/form-data', 'token':globals.globalsData.manager.info.Token }, timeout: globals.globalsConfig.httpConfig.requestTimeout, onUploadProgress: onUploadProgressCall }).then(response => { if (response.status == 200) { let ans = protoManage.NodeResource.decode(new Uint8Array(<Uint8Array>response.data)) resolve(ans) }else { httpError(response.status, <Uint8Array>response.data) reject(response) } }).catch(error => { if (error.response != undefined){ httpError(error.response.status, error.response.data) }else{ globals.viewError(i18n.global.t('request.error.fail', { msg: error})); } reject(error) }) }) } export function httpRequestDownLoad(path:string, id:number) { let url = globals.getHttpHost() + path + "?token="+globals.globalsData.manager.info.Token + "&id="+id window.open(url) // let downloadLink = document.createElement("a"); // downloadLink.href = url; // downloadLink.download = name; // document.body.appendChild(downloadLink); // downloadLink.click(); // document.body.removeChild(downloadLink); } export function httpError(code:number, data:Uint8Array) { let str = new TextDecoder().decode(data) switch (code) { case protoManage.HttpError.HttpErrorGetHeader: globals.viewError(i18n.global.t('request.error.header', { msg: str})); break case protoManage.HttpError.HttpErrorGetBody: globals.viewError(i18n.global.t('request.error.body', { msg: str})); break case protoManage.HttpError.HttpErrorGetFile: globals.viewError(i18n.global.t('request.error.file', { msg: str})); break case protoManage.HttpError.HttpErrorCheckFile: globals.viewError(i18n.global.t('request.error.checkFile', { msg: str})); break case protoManage.HttpError.HttpErrorMarshal: globals.viewError(i18n.global.t('request.error.marshal', { msg: str})); break case protoManage.HttpError.HttpErrorUnmarshal: globals.viewError(i18n.global.t('request.error.unmarshal', { msg: str})); break case protoManage.HttpError.HttpErrorRegister: globals.viewError(i18n.global.t('request.error.register', { msg: str})); break case protoManage.HttpError.HttpErrorLoginWithAccount: globals.viewError(i18n.global.t('request.error.loginWithAccount', { msg: str})); break case protoManage.HttpError.HttpErrorPasswordWithAccount: globals.viewError(i18n.global.t('request.error.passwordWithAccount', { msg: str})); break case protoManage.HttpError.HttpErrorLoginWithToken: globals.viewError(i18n.global.t('request.error.loginWithToken', { msg: str})); globals.reLogin() break case protoManage.HttpError.HttpErrorLevelLow: globals.viewError(i18n.global.t('request.error.levelLow', { msg: str})); break case protoManage.HttpError.HttpErrorRequest: globals.viewError(i18n.global.t('request.error.request', { msg: str})); break default: globals.viewError(i18n.global.t('request.error.fail', { msg: str})); break } } }
the_stack
import HostedNumbers = require('../../HostedNumbers'); import Page = require('../../../../base/Page'); import Response = require('../../../../http/response'); import { SerializableClass } from '../../../../interfaces'; type DependentHostedNumberOrderStatus = 'received'|'pending-verification'|'verified'|'pending-loa'|'carrier-processing'|'testing'|'completed'|'failed'|'action-required'; type DependentHostedNumberOrderVerificationType = 'phone-call'|'phone-bill'; /** * Initialize the DependentHostedNumberOrderList * * PLEASE NOTE that this class contains preview products that are subject to * change. Use them with caution. If you currently do not have developer preview * access, please contact help@twilio.com. * * @param version - Version of the resource * @param signingDocumentSid - LOA document sid. */ declare function DependentHostedNumberOrderList(version: HostedNumbers, signingDocumentSid: string): DependentHostedNumberOrderListInstance; interface DependentHostedNumberOrderListInstance { /** * Streams DependentHostedNumberOrderInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Function to process each record */ each(opts?: DependentHostedNumberOrderListInstanceEachOptions, callback?: (item: DependentHostedNumberOrderInstance, done: (err?: Error) => void) => void): void; /** * Retrieve a single target page of DependentHostedNumberOrderInstance records from * the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param targetUrl - API-generated URL for the requested results page * @param callback - Callback to handle list of records */ getPage(targetUrl?: string, callback?: (error: Error | null, items: DependentHostedNumberOrderPage) => any): Promise<DependentHostedNumberOrderPage>; /** * Lists DependentHostedNumberOrderInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ list(opts?: DependentHostedNumberOrderListInstanceOptions, callback?: (error: Error | null, items: DependentHostedNumberOrderInstance[]) => any): Promise<DependentHostedNumberOrderInstance[]>; /** * Retrieve a single page of DependentHostedNumberOrderInstance records from the * API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ page(opts?: DependentHostedNumberOrderListInstancePageOptions, callback?: (error: Error | null, items: DependentHostedNumberOrderPage) => any): Promise<DependentHostedNumberOrderPage>; /** * Provide a user-friendly representation */ toJSON(): any; } /** * Options to pass to each * * @property callback - * Function to process each record. If this and a positional * callback are passed, this one will be used * @property done - Function to be called upon completion of streaming * @property friendlyName - A human readable description of this resource. * @property incomingPhoneNumberSid - IncomingPhoneNumber sid. * @property limit - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) * @property phoneNumber - An E164 formatted phone number. * @property status - The Status of this HostedNumberOrder. * @property uniqueName - A unique, developer assigned name of this HostedNumberOrder. */ interface DependentHostedNumberOrderListInstanceEachOptions { callback?: (item: DependentHostedNumberOrderInstance, done: (err?: Error) => void) => void; done?: Function; friendlyName?: string; incomingPhoneNumberSid?: string; limit?: number; pageSize?: number; phoneNumber?: string; status?: DependentHostedNumberOrderStatus; uniqueName?: string; } /** * Options to pass to list * * @property friendlyName - A human readable description of this resource. * @property incomingPhoneNumberSid - IncomingPhoneNumber sid. * @property limit - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) * @property phoneNumber - An E164 formatted phone number. * @property status - The Status of this HostedNumberOrder. * @property uniqueName - A unique, developer assigned name of this HostedNumberOrder. */ interface DependentHostedNumberOrderListInstanceOptions { friendlyName?: string; incomingPhoneNumberSid?: string; limit?: number; pageSize?: number; phoneNumber?: string; status?: DependentHostedNumberOrderStatus; uniqueName?: string; } /** * Options to pass to page * * @property friendlyName - A human readable description of this resource. * @property incomingPhoneNumberSid - IncomingPhoneNumber sid. * @property pageNumber - Page Number, this value is simply for client state * @property pageSize - Number of records to return, defaults to 50 * @property pageToken - PageToken provided by the API * @property phoneNumber - An E164 formatted phone number. * @property status - The Status of this HostedNumberOrder. * @property uniqueName - A unique, developer assigned name of this HostedNumberOrder. */ interface DependentHostedNumberOrderListInstancePageOptions { friendlyName?: string; incomingPhoneNumberSid?: string; pageNumber?: number; pageSize?: number; pageToken?: string; phoneNumber?: string; status?: DependentHostedNumberOrderStatus; uniqueName?: string; } interface DependentHostedNumberOrderPayload extends DependentHostedNumberOrderResource, Page.TwilioResponsePayload { } interface DependentHostedNumberOrderResource { account_sid: string; address_sid: string; call_delay: number; capabilities: string; cc_emails: string; date_created: Date; date_updated: Date; email: string; extension: string; failure_reason: string; friendly_name: string; incoming_phone_number_sid: string; phone_number: string; sid: string; signing_document_sid: string; status: DependentHostedNumberOrderStatus; unique_name: string; verification_attempts: number; verification_call_sids: string; verification_code: string; verification_document_sid: string; verification_type: DependentHostedNumberOrderVerificationType; } interface DependentHostedNumberOrderSolution { signingDocumentSid?: string; } declare class DependentHostedNumberOrderInstance extends SerializableClass { /** * Initialize the DependentHostedNumberOrderContext * * PLEASE NOTE that this class contains preview products that are subject to * change. Use them with caution. If you currently do not have developer preview * access, please contact help@twilio.com. * * @param version - Version of the resource * @param payload - The instance payload * @param signingDocumentSid - LOA document sid. */ constructor(version: HostedNumbers, payload: DependentHostedNumberOrderPayload, signingDocumentSid: string); accountSid: string; addressSid: string; callDelay: number; capabilities: string; ccEmails: string; dateCreated: Date; dateUpdated: Date; email: string; extension: string; failureReason: string; friendlyName: string; incomingPhoneNumberSid: string; phoneNumber: string; sid: string; signingDocumentSid: string; status: DependentHostedNumberOrderStatus; /** * Provide a user-friendly representation */ toJSON(): any; uniqueName: string; verificationAttempts: number; verificationCallSids: string; verificationCode: string; verificationDocumentSid: string; verificationType: DependentHostedNumberOrderVerificationType; } declare class DependentHostedNumberOrderPage extends Page<HostedNumbers, DependentHostedNumberOrderPayload, DependentHostedNumberOrderResource, DependentHostedNumberOrderInstance> { /** * Initialize the DependentHostedNumberOrderPage * * PLEASE NOTE that this class contains preview products that are subject to * change. Use them with caution. If you currently do not have developer preview * access, please contact help@twilio.com. * * @param version - Version of the resource * @param response - Response from the API * @param solution - Path solution */ constructor(version: HostedNumbers, response: Response<string>, solution: DependentHostedNumberOrderSolution); /** * Build an instance of DependentHostedNumberOrderInstance * * @param payload - Payload response from the API */ getInstance(payload: DependentHostedNumberOrderPayload): DependentHostedNumberOrderInstance; /** * Provide a user-friendly representation */ toJSON(): any; } export { DependentHostedNumberOrderInstance, DependentHostedNumberOrderList, DependentHostedNumberOrderListInstance, DependentHostedNumberOrderListInstanceEachOptions, DependentHostedNumberOrderListInstanceOptions, DependentHostedNumberOrderListInstancePageOptions, DependentHostedNumberOrderPage, DependentHostedNumberOrderPayload, DependentHostedNumberOrderResource, DependentHostedNumberOrderSolution }
the_stack
import { useScopedStore } from '@edtr-io/core' import { change, findNextNode, findPreviousNode, focusNext, focusPrevious, getDocument, getFocusTree, getParent, getPlugins, insertChildAfter, mayInsertChild, mayRemoveChild, removeChild, replace, getFocusPath, getPlugin, } from '@edtr-io/store' import * as Immutable from 'immutable' import isHotkey from 'is-hotkey' import * as R from 'ramda' import * as React from 'react' import { Block, Editor as CoreEditor, Node, Operation, Value, ValueJSON, } from 'slate' import { Editor, EventHook, getEventTransfer } from 'slate-react' import { isValueEmpty, serializer, TextPlugin, TextProps } from '..' import { I18nContext } from '../i18n-context' import { htmlToSlateValue, katexBlockNode, slateSchema } from '../model' import { SlateClosure } from './types' export function TextEditor(props: TextProps) { const store = useScopedStore() const editor = React.useRef<CoreEditor>() const [rawState, setRawState] = React.useState(() => { // slate.js changed format with version 0.46 // old format is still supported, but new states will be in new format return Value.fromJSON(props.state.value) }) const thisState = React.useRef(props.state) const lastValue = React.useRef(props.state.value) const { focused, state } = props React.useEffect(() => { thisState.current = state if (lastValue.current !== state.value) { setRawState(Value.fromJSON(state.value)) lastValue.current = state.value // Refocus Slate after state change if needed setTimeout(() => { if (!editor.current) return if (focused) { editor.current.focus() } }) } }, [lastValue, focused, state]) // Sync Slate focus with Edtr.io focus React.useEffect(() => { if (!editor.current) return if (props.focused) { editor.current.focus() } else { editor.current.blur() } }, [props.focused]) // This ref makes sure that slate hooks and plugins have access to the latest values const slateClosure = React.useRef<SlateClosure>({ id: props.id, config: props.config, store, }) slateClosure.current = { store, config: props.config, id: props.id, } React.useEffect(() => { if (!editor.current) return if (props.focused) { setTimeout(() => { if (!editor.current) return editor.current.focus() }) } else { editor.current.blur() } }, [props.focused]) const slatePlugins = React.useRef<TextPlugin[]>() if (slatePlugins.current === undefined) { slatePlugins.current = [ ...props.config.plugins.map((slatePluginFactory) => slatePluginFactory(slateClosure) ), newSlateOnEnter(slateClosure), focusNextDocumentOnArrowDown(slateClosure), ] } const onPaste = React.useMemo(() => { return createOnPaste(slateClosure) }, [slateClosure]) const onKeyDown = React.useMemo(() => { return createOnKeyDown(slateClosure) }, [slateClosure]) const onClick = React.useCallback<EventHook<React.MouseEvent>>( (e, editor, next): Editor | void => { if (e.target) { const node = editor.findNode(e.target as Element) if (!node) { return editor } } next() }, [] ) const onChange = React.useCallback( (change: { operations: Immutable.List<Operation>; value: Value }) => { const nextValue = change.value.toJSON() setRawState(change.value) const withoutSelections = change.operations.filter( (operation) => typeof operation !== 'undefined' && operation.type !== 'set_selection' ) if (!withoutSelections.isEmpty()) { lastValue.current = nextValue if (thisState.current) thisState.current.set(nextValue) } }, [thisState] ) return React.useMemo( () => ( <I18nContext.Provider value={props.config.i18n}> <Editor ref={(slate) => { const slateReact = slate as unknown as CoreEditor | null if (slateReact && !editor.current) { editor.current = slateReact } }} onPaste={onPaste} onKeyDown={onKeyDown} onClick={onClick} onChange={onChange} placeholder={props.editable ? props.config.placeholder : ''} plugins={slatePlugins.current} readOnly={!props.focused} value={rawState} schema={slateSchema} /> </I18nContext.Provider> ), [ onPaste, onKeyDown, onClick, onChange, props.editable, props.config.i18n, props.config.placeholder, props.focused, rawState, ] ) } function createOnPaste( slateClosure: React.RefObject<SlateClosure> ): EventHook<React.ClipboardEvent> { return (e, editor, next): void => { if (!slateClosure.current) { next() return } const { id, store } = slateClosure.current const document = getDocument(id)(store.getState()) if (!document) { next() return } const name = document.plugin const plugins = getPlugins()(store.getState()) const mayInsert = mayInsertChild(id)(store.getState()) if (!mayInsert) { next() return } const { clipboardData } = e const files = getFilesFromDataTransfer(clipboardData) const text = clipboardData.getData('text') if (files && files.length > 0) { for (const key in plugins) { if (!Object.prototype.hasOwnProperty.call(plugins, key)) continue // eslint-disable-next-line @typescript-eslint/unbound-method const { onFiles } = plugins[key] if (typeof onFiles === 'function') { const result = onFiles(files) if (result !== undefined) { handleResult(key, result) return } } } } if (text) { for (const key in plugins) { if (!Object.prototype.hasOwnProperty.call(plugins, key)) continue // eslint-disable-next-line @typescript-eslint/unbound-method const { onText } = plugins[key] if (typeof onText === 'function') { const result = onText(text) if (result !== undefined) { handleResult(key, result) return } } } } const transfer = getEventTransfer(e) if (transfer.type === 'html') { // @ts-expect-error: outdated slate types const html = transfer.html as string const { document } = htmlToSlateValue(html) editor.insertFragment(document) e.preventDefault() return } next() function getFilesFromDataTransfer(clipboardData: DataTransfer) { const items = clipboardData.files const files: File[] = [] for (let i = 0; i < items.length; i++) { const item = items[i] if (!item) continue files.push(item) } return files } function handleResult(key: string, result: { state?: unknown }) { if (mayRemoveChild(id)(store.getState()) && isValueEmpty(editor.value)) { store.dispatch( replace({ id, plugin: key, state: result.state, }) ) } else { const nextSlateState = splitBlockAtSelection(editor) const parent = getParent(id)(store.getState()) if (!parent) return setTimeout(() => { // insert new text-plugin with the parts after the current cursor position if any if (nextSlateState) { store.dispatch( insertChildAfter({ parent: parent.id, sibling: id, document: { plugin: name, state: serializer.serialize(nextSlateState), }, }) ) } store.dispatch( insertChildAfter({ parent: parent.id, sibling: id, document: { plugin: key, state: result.state, }, }) ) }) } } } } function createOnKeyDown( slateClosure: React.RefObject<SlateClosure> ): EventHook<React.KeyboardEvent> { return (e, editor, next): void => { const { key } = e const event = e as unknown as KeyboardEvent if ( isHotkey('mod+z', event) || isHotkey('mod+y', event) || isHotkey('mod+shift+z', event) ) { e.preventDefault() return } if ( (key === 'Backspace' && isSelectionAtStart(editor)) || (key === 'Delete' && isSelectionAtEnd(editor)) ) { // prevent accidentally leaving page with backspace e.preventDefault() if (!slateClosure.current) return const previous = key === 'Backspace' if (isValueEmpty(editor.value)) { // Focus previous resp. next document and remove self const { id, store } = slateClosure.current const mayRemove = mayRemoveChild(id)(store.getState()) const focus = previous ? focusPrevious : focusNext if (mayRemove) { const parent = getParent(id)(store.getState()) if (!parent) return store.dispatch(focus()) store.dispatch(removeChild({ parent: parent.id, child: id })) } } else { const { id, store } = slateClosure.current const mayRemove = mayRemoveChild(id)(store.getState()) const mayInsert = mayInsertChild(id)(store.getState()) if (!mayRemove || !mayInsert) return const parent = getParent(id)(store.getState()) if (!parent) return const children = parent.children || [] const index = R.findIndex((child) => child.id === id, children) if (index === -1) return const currentDocument = getDocument(id)(store.getState()) if (!currentDocument) return if (previous) { if (index - 1 < 0) return const previousSibling = children[index - 1] let previousDocument = getDocument(previousSibling.id)( store.getState() ) if (!previousDocument) return if (previousDocument.plugin === currentDocument.plugin) { merge(previousDocument.state, previous) setTimeout(() => { store.dispatch( removeChild({ parent: parent.id, child: previousSibling.id }) ) }) } else { const root = getFocusTree()(store.getState()) if (!root) return const previousFocusId = findPreviousNode(root, id) if (!previousFocusId) return previousDocument = getDocument(previousFocusId)(store.getState()) if ( !previousDocument || previousDocument.plugin !== currentDocument.plugin ) return const merged = merge(previousDocument.state, previous) store.dispatch(focusPrevious()) store.dispatch( change({ id: previousFocusId, state: { initial: () => merged }, }) ) store.dispatch( removeChild({ parent: parent.id, child: id, }) ) } } else { if (index + 1 >= children.length) return const nextSibling = children[index + 1] let nextDocument = getDocument(nextSibling.id)(store.getState()) if (!nextDocument) return if (nextDocument.plugin === currentDocument.plugin) { merge(nextDocument.state, previous) setTimeout(() => { store.dispatch( removeChild({ parent: parent.id, child: nextSibling.id }) ) }) } else { const root = getFocusTree()(store.getState()) if (!root) return const nextFocusId = findNextNode(root, id) if (!nextFocusId) return nextDocument = getDocument(nextFocusId)(store.getState()) if (!nextDocument || nextDocument.plugin !== currentDocument.plugin) return merge(nextDocument.state, previous) store.dispatch( removeChild({ parent: parent.id, child: nextSibling.id }) ) } } } return } return next() function merge(other: unknown, previous: boolean) { const value = Value.fromJSON(other as ValueJSON) const insertionIndex = previous ? 0 : editor.value.document.nodes.size // lower level command to merge two documents editor.insertFragmentByKey( editor.value.document.key, insertionIndex, value.document ) return editor.value.toJSON() } } } function isSelectionAtStart(editor: Editor) { const { selection } = editor.value const startNode = editor.value.document.getFirstText() return ( selection.isCollapsed && startNode && editor.value.startText.key === startNode.key && selection.start.offset === 0 ) } function isSelectionAtEnd(editor: Editor) { const { selection } = editor.value const endNode = editor.value.document.getLastText() return ( selection.isCollapsed && endNode && editor.value.endText.key === endNode.key && selection.end.offset === editor.value.endText.text.length ) } function newSlateOnEnter( slateClosure: React.RefObject<SlateClosure> ): TextPlugin { return { onKeyDown(e, editor, next) { if ( isHotkey('enter', e as unknown as KeyboardEvent) && !editor.value.selection.isExpanded ) { // remove text plugin and insert on parent if plugin is empty if (isValueEmpty(editor.value)) { if (!slateClosure.current) return const { id, store } = slateClosure.current const mayRemove = mayRemoveChild(id)(store.getState()) if (!mayRemove) return const result = findParentWith('insertChild', slateClosure) if (result) { e.preventDefault() const document = getDocument(id)(store.getState()) if (!document) return const directParent = getParent(id)(store.getState()) if (!directParent) return store.dispatch( insertChildAfter({ parent: result.parent, sibling: result.sibling, document: { plugin: document.plugin, }, }) ) store.dispatch( removeChild({ parent: directParent.id, child: id, }) ) return } } // remove block and insert plugin on parent, if block is empty if ( editor.value.startText.text === '' && editor.value.startBlock.nodes.size === 1 ) { if (!slateClosure.current) return const { id, store } = slateClosure.current const result = findParentWith('insertChild', slateClosure) if (result) { e.preventDefault() const document = getDocument(id)(store.getState()) if (!document) return editor.delete() store.dispatch( insertChildAfter({ parent: result.parent, sibling: result.sibling, document: { plugin: document.plugin, }, }) ) return } } if (!slateClosure.current) return const { id, store } = slateClosure.current const mayInsert = mayInsertChild(id)(store.getState()) if (mayInsert) { e.preventDefault() const document = getDocument(id)(store.getState()) if (!document) return const parent = getParent(id)(store.getState()) if (!parent) return const nextSlateState = splitBlockAtSelection(editor) setTimeout(() => { if (nextSlateState) { store.dispatch( insertChildAfter({ parent: parent.id, sibling: id, document: { plugin: document.plugin, state: serializer.serialize(nextSlateState), }, }) ) } else { store.dispatch( insertChildAfter({ parent: parent.id, sibling: id, document: { plugin: document.plugin, }, }) ) } }) return } } return next() }, } } function focusNextDocumentOnArrowDown( slateClosure: React.RefObject<SlateClosure> ): TextPlugin { return { onKeyDown(e, editor, next) { const { key } = e as unknown as React.KeyboardEvent if (key === 'ArrowDown' || key === 'ArrowUp') { const lastRange = getRange() if (lastRange) { const lastY = lastRange.getBoundingClientRect().top setTimeout(() => { const currentRange = getRange() if (!currentRange) return const currentY = currentRange.getBoundingClientRect().top if (lastY === currentY) { if (!slateClosure.current) return const { store } = slateClosure.current const focus = key === 'ArrowDown' ? focusNext : focusPrevious store.dispatch(focus()) } }) } } return next() function getRange(): Range | null { const selection = window.getSelection() if (selection && selection.rangeCount > 0) { return selection.getRangeAt(0) } return null } }, } } function findParentWith( funcQuery: 'insertChild' | 'removeChild', closure: React.RefObject<SlateClosure> ): { parent: string; sibling: string } | null { if (!closure.current) return null const { id, store } = closure.current const focusPath = getFocusPath(id)(store.getState()) if (!focusPath || focusPath.length <= 2) return null const parents = R.init(R.init(focusPath)) const index = R.findLastIndex((parent) => { const parentDocument = getDocument(parent)(store.getState()) if (!parentDocument) return false const plugin = getPlugin(parentDocument.plugin)(store.getState()) if (!plugin) return false return typeof plugin[funcQuery] === 'function' }, parents) if (index === -1) return null return { parent: focusPath[index], sibling: focusPath[index + 1] } } function splitBlockAtSelection(editor: Editor) { if (isSelectionAtEnd(editor)) { return } if (editor.value.focusBlock.type == katexBlockNode) { // If katex block node is focused, don't attempt to split it, insert empty paragraph instead editor.moveToEndOfBlock() editor.insertBlock('paragraph') } else { editor.splitBlock(1) } const blocks = editor.value.document.nodes const afterSelected = blocks.skipUntil((block) => { if (!block) { return false } return editor.value.blocks.first<Block>().key === block.key }) afterSelected.forEach((block) => { if (!block) return editor.removeNodeByKey(block.key) }) return createDocumentFromNodes(afterSelected.toArray()) } function createDocumentFromNodes(nodes: Node[]) { return { document: { nodes: [...nodes.map((node) => node.toJSON())], }, } }
the_stack
import { ts } from "../../../deps.ts"; import { defaultKeyword, IdentifierMap } from "./_util.ts"; const printer: ts.Printer = ts.createPrinter({ removeComments: false }); export function typescriptInjectIdentifiersTransformer( identifierMap: Map<string, string>, blacklistIdentifiers: Set<string>, ) { return (context: ts.TransformationContext) => { const visitor = (sourceFile: ts.SourceFile) => (identifierMap: Map<string, string>): ts.Visitor => (node: ts.Node) => { if (ts.isExportAssignment(node)) { const identifier = identifierMap.get(defaultKeyword)!; return ts.factory.createVariableStatement( undefined, ts.factory.createVariableDeclarationList( [ts.factory.createVariableDeclaration( ts.factory.createIdentifier(identifier), undefined, undefined, node.expression, )], ts.NodeFlags.Const, ), ); } else if ( ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) ) { // const x = "x" const text = node.name.text; const identifier = identifierMap.get(text) || text; node = ts.factory.updateVariableDeclaration( node, ts.factory.createIdentifier(identifier), node.exclamationToken, node.type, node.initializer, ); } else if (ts.isCallExpression(node)) { // console.log(x) let expression = node.expression; if (ts.isIdentifier(expression)) { const text = expression.text; const identifier = identifierMap.get(text) || text; expression = ts.factory.createIdentifier(identifier); } node = ts.factory.updateCallExpression( node, expression, node.typeArguments, node.arguments.map((arg) => { if ( ts.isIdentifier(arg) ) { const text = arg.text; const identifier = identifierMap.get(text) || text; return ts.factory.createIdentifier(identifier); } return arg; }), ); } else if (ts.isFunctionDeclaration(node)) { // function x() { } let name = node.name; if (name) { const text = name.text; const identifier = identifierMap.get(text) || text; name = ts.factory.createIdentifier(identifier); } const newIdentifierMap = new Map(identifierMap); node.parameters.forEach((parameter) => { if ( ts.isIdentifier(parameter.name) && !blacklistIdentifiers.has(parameter.name.text) ) { newIdentifierMap.delete(parameter.name.text); } }); node = ts.factory.updateFunctionDeclaration( node, node.decorators, node.modifiers, node.asteriskToken, name, node.typeParameters, node.parameters, node.type, node.body, ); return ts.visitEachChild( node, visitor(sourceFile)(newIdentifierMap), context, ); } else if (ts.isClassDeclaration(node) && node.name) { const text = node.name.text; const identifier = identifierMap.get(text) || text; node = ts.factory.updateClassDeclaration( node, node.decorators, node.modifiers, ts.factory.createIdentifier(identifier), node.typeParameters, node.heritageClauses, node.members, ); } else if (ts.isArrayLiteralExpression(node)) { // const a = [x, y, z] node = ts.factory.updateArrayLiteralExpression( node, node.elements.map((element) => { if (ts.isIdentifier(element)) { const text = element.text; const identifier = identifierMap.get(text) || text; return ts.factory.createIdentifier(identifier); } return element; }), ); } else if (ts.isObjectLiteralExpression(node)) { // const a = { x, y, z: x } node = ts.factory.updateObjectLiteralExpression( node, node.properties.map((property) => { if ( ts.isPropertyAssignment(property) && ts.isIdentifier(property.initializer) ) { const text = property.initializer.text; const identifier = identifierMap.get(text) || text; property = ts.factory.updatePropertyAssignment( property, property.name, ts.factory.createIdentifier(identifier), ); } else if (ts.isShorthandPropertyAssignment(property)) { const text = property.name.text; const identifier = identifierMap.get(text) || text; property = ts.factory.updateShorthandPropertyAssignment( property, ts.factory.createIdentifier(identifier), property.objectAssignmentInitializer, ); } return property; }), ); } else if ( // x.a ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) ) { const text = node.expression.text; const identifier = identifierMap.get(text) || text; node = ts.factory.updatePropertyAccessExpression( node, ts.factory.createIdentifier(identifier), node.name, ); } else if ( // x["a"] ts.isElementAccessExpression(node) && ts.isIdentifier(node.expression) ) { const text = node.expression.text; const identifier = identifierMap.get(text) || text; node = ts.factory.updateElementAccessExpression( node, ts.factory.createIdentifier(identifier), node.argumentExpression, ); } else if ( ts.isTypeOfExpression(node) && ts.isIdentifier(node.expression) ) { // typeof x const text = node.expression.text; const identifier = identifierMap.get(text) || text; node = ts.factory.updateTypeOfExpression( node, ts.factory.createIdentifier(identifier), ); } else if (ts.isBinaryExpression(node)) { // x instanceof x //x += 1 let left = node.left; let right = node.right; if (ts.isIdentifier(left)) { const text = left.text; const identifier = identifierMap.get(text) || text; left = ts.factory.createIdentifier(identifier); } if (ts.isIdentifier(right)) { const text = right.text; const identifier = identifierMap.get(text) || text; right = ts.factory.createIdentifier(identifier); } node = ts.factory.updateBinaryExpression( node, left, node.operatorToken, right, ); } else if ( ts.isPrefixUnaryExpression(node) && ts.isIdentifier(node.operand) ) { // ++x const text = node.operand.text; const identifier = identifierMap.get(text) || text; node = ts.factory.updatePrefixUnaryExpression( node, ts.factory.createIdentifier(identifier), ); } else if ( ts.isPostfixUnaryExpression(node) && ts.isIdentifier(node.operand) ) { // x++ const text = node.operand.text; const identifier = identifierMap.get(text) || text; node = ts.factory.updatePostfixUnaryExpression( node, ts.factory.createIdentifier(identifier), ); } else if (ts.isConditionalExpression(node)) { // x ? x : x let condition = node.condition; let whenTrue = node.whenTrue; let whenFalse = node.whenFalse; if (ts.isIdentifier(condition)) { const text = condition.text; const identifier = identifierMap.get(text) || text; condition = ts.factory.createIdentifier(identifier); } if (ts.isIdentifier(whenTrue)) { const text = whenTrue.text; const identifier = identifierMap.get(text) || text; whenTrue = ts.factory.createIdentifier(identifier); } if (ts.isIdentifier(whenFalse)) { const text = whenFalse.text; const identifier = identifierMap.get(text) || text; whenFalse = ts.factory.createIdentifier(identifier); } node = ts.factory.updateConditionalExpression( node, condition, node.questionToken, whenTrue, node.colonToken, whenFalse, ); } else if (ts.isIfStatement(node)) { // if (x) { } let expression = node.expression; if (ts.isIdentifier(expression)) { const text = expression.text; const identifier = identifierMap.get(text) || text; expression = ts.factory.createIdentifier(identifier); } node = ts.factory.updateIfStatement( node, expression, node.thenStatement, node.elseStatement, ); } else if (ts.isSwitchStatement(node)) { // switch (x) { } let expression = node.expression; if (ts.isIdentifier(expression)) { const text = expression.text; const identifier = identifierMap.get(text) || text; expression = ts.factory.createIdentifier(identifier); } node = ts.factory.updateSwitchStatement( node, expression, node.caseBlock, ); } else if (ts.isCaseClause(node)) { let expression = node.expression; if (ts.isIdentifier(expression)) { const text = expression.text; const identifier = identifierMap.get(text) || text; expression = ts.factory.createIdentifier(identifier); } node = ts.factory.updateCaseClause( node, expression, node.statements, ); } else if (ts.isWhileStatement(node)) { // while (x) { } let expression = node.expression; if (ts.isIdentifier(expression)) { const text = expression.text; const identifier = identifierMap.get(text) || text; expression = ts.factory.createIdentifier(identifier); } node = ts.factory.updateWhileStatement( node, expression, node.statement, ); } else if (ts.isDoStatement(node)) { // do {} while (x) { } let expression = node.expression; if (ts.isIdentifier(expression)) { const text = expression.text; const identifier = identifierMap.get(text) || text; expression = ts.factory.createIdentifier(identifier); } node = ts.factory.updateDoStatement( node, node.statement, expression, ); } else if (ts.isForStatement(node)) { // for (let x = 0; x > 0; i++) { } let initializer = node.initializer; let condition = node.condition; let incrementor = node.incrementor; if (initializer && ts.isIdentifier(initializer)) { const text = initializer.text; const identifier = identifierMap.get(text) || text; initializer = ts.factory.createIdentifier(identifier); } if (condition && ts.isIdentifier(condition)) { const text = condition.text; const identifier = identifierMap.get(text) || text; condition = ts.factory.createIdentifier(identifier); } if (incrementor && ts.isIdentifier(incrementor)) { const text = incrementor.text; const identifier = identifierMap.get(text) || text; incrementor = ts.factory.createIdentifier(identifier); } node = ts.factory.updateForStatement( node, initializer, condition, incrementor, node.statement, ); } else if (ts.isForOfStatement(node)) { // for (x of x) { } let initializer = node.initializer; let expression = node.expression; if (ts.isIdentifier(initializer)) { const text = initializer.text; const identifier = identifierMap.get(text) || text; initializer = ts.factory.createIdentifier(identifier); } if (ts.isIdentifier(expression)) { const text = expression.text; const identifier = identifierMap.get(text) || text; expression = ts.factory.createIdentifier(identifier); } node = ts.factory.updateForOfStatement( node, node.awaitModifier, initializer, expression, node.statement, ); } else if (ts.isForInStatement(node)) { // for (x in x) { } let initializer = node.initializer; let expression = node.expression; if (ts.isIdentifier(initializer)) { const text = initializer.text; const identifier = identifierMap.get(text) || text; initializer = ts.factory.createIdentifier(identifier); } if (ts.isIdentifier(expression)) { const text = expression.text; const identifier = identifierMap.get(text) || text; expression = ts.factory.createIdentifier(identifier); } node = ts.factory.updateForInStatement( node, initializer, expression, node.statement, ); } else if (ts.isNewExpression(node)) { // new x() let expression = node.expression; if (ts.isIdentifier(expression)) { const text = expression.text; const identifier = identifierMap.get(text) || text; expression = ts.factory.createIdentifier(identifier); } node = ts.factory.updateNewExpression( node, expression, node.typeArguments, node.arguments, ); } else if (ts.isEnumDeclaration(node)) { let name = node.name; if (ts.isIdentifier(name)) { const text = name.text; const identifier = identifierMap.get(text) || text; name = ts.factory.createIdentifier(identifier); } node = ts.factory.updateEnumDeclaration( node, node.decorators, node.modifiers, name, node.members, ); } return ts.visitEachChild( node, visitor(sourceFile)(identifierMap), context, ); }; return (node: ts.Node) => ts.visitNode( node, (child: ts.Node) => visitor(node as ts.SourceFile)(identifierMap)(child), ); }; } export function injectIdentifiersFromSourceFile( sourceFile: ts.SourceFile, identifierMap: IdentifierMap, blacklistIdentifiers: Set<string>, ) { const { transformed } = ts.transform(sourceFile, [ typescriptInjectIdentifiersTransformer(identifierMap, blacklistIdentifiers), ]); return printer.printFile(transformed[0] as ts.SourceFile); } export function injectIdentifiers( fileName: string, sourceText: string, identifierMap: IdentifierMap, blacklistIdentifiers: Set<string>, ) { const sourceFile = ts.createSourceFile( fileName, sourceText, ts.ScriptTarget.Latest, ); return injectIdentifiersFromSourceFile( sourceFile, identifierMap, blacklistIdentifiers, ); }
the_stack
import { mockAwsS3, mockAwsSecretManager } from './mock'; import SecretsManager from 'aws-sdk/clients/secretsmanager'; import S3 from 'aws-sdk/clients/s3'; import { ImageRequest } from '../image-request'; import { ImageHandlerError, RequestTypes, StatusCodes } from '../lib'; import { SecretProvider } from '../secret-provider'; describe('setup()', () => { const s3Client = new S3(); const secretsManager = new SecretsManager(); let secretProvider = new SecretProvider(secretsManager); beforeEach(() => { jest.resetAllMocks(); }); afterEach(() => { jest.clearAllMocks(); secretProvider = new SecretProvider(secretsManager); // need to re-create the provider to make sure the secret is not cached }); describe('001/defaultImageRequest', () => { const OLD_ENV = process.env; beforeEach(() => { jest.resetAllMocks(); process.env = { ...OLD_ENV }; }); afterEach(() => { jest.clearAllMocks(); }); afterAll(() => { process.env = OLD_ENV; }); it('Should pass when a default image request is provided and populate the ImageRequest object with the proper values', async () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJ2YWxpZEJ1Y2tldCIsImtleSI6InZhbGlkS2V5IiwiZWRpdHMiOnsiZ3JheXNjYWxlIjp0cnVlfSwib3V0cHV0Rm9ybWF0IjoianBlZyJ9' }; process.env.SOURCE_BUCKETS = 'validBucket, validBucket2'; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: 'Default', bucket: 'validBucket', key: 'validKey', edits: { grayscale: true }, outputFormat: 'jpeg', originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=31536000,public', contentType: 'image/jpeg' }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'validBucket', Key: 'validKey' }); expect(imageRequestInfo).toEqual(expectedResult); }); }); describe('002/defaultImageRequest/toFormat', () => { const OLD_ENV = process.env; beforeEach(() => { jest.resetAllMocks(); process.env = { ...OLD_ENV }; }); afterEach(() => { jest.clearAllMocks(); }); afterAll(() => { process.env = OLD_ENV; }); it('Should pass when a default image request is provided and populate the ImageRequest object with the proper values', async () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJ2YWxpZEJ1Y2tldCIsImtleSI6InZhbGlkS2V5IiwiZWRpdHMiOnsidG9Gb3JtYXQiOiJwbmcifX0=' }; process.env.SOURCE_BUCKETS = 'validBucket, validBucket2'; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: 'Default', bucket: 'validBucket', key: 'validKey', edits: { toFormat: 'png' }, outputFormat: 'png', originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=31536000,public', contentType: 'image/png' }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'validBucket', Key: 'validKey' }); expect(imageRequestInfo).toEqual(expectedResult); }); }); describe('003/thumborImageRequest', () => { const OLD_ENV = process.env; beforeEach(() => { jest.resetAllMocks(); process.env = { ...OLD_ENV }; }); afterEach(() => { jest.clearAllMocks(); }); afterAll(() => { process.env = OLD_ENV; }); it('Should pass when a thumbor image request is provided and populate the ImageRequest object with the proper values', async () => { // Arrange const event = { path: '/filters:grayscale()/test-image-001.jpg' }; process.env.SOURCE_BUCKETS = 'allowedBucket001, allowedBucket002'; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: 'Thumbor', bucket: 'allowedBucket001', key: 'test-image-001.jpg', edits: { grayscale: true }, originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=31536000,public', contentType: 'image' }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'allowedBucket001', Key: 'test-image-001.jpg' }); expect(imageRequestInfo).toEqual(expectedResult); }); }); describe('004/thumborImageRequest/quality', () => { const OLD_ENV = process.env; beforeEach(() => { jest.resetAllMocks(); process.env = { ...OLD_ENV }; }); afterEach(() => { jest.clearAllMocks(); }); afterAll(() => { process.env = OLD_ENV; }); it('Should pass when a thumbor image request is provided and populate the ImageRequest object with the proper values', async () => { // Arrange const event = { path: '/filters:format(png)/filters:quality(50)/test-image-001.jpg' }; process.env.SOURCE_BUCKETS = 'allowedBucket001, allowedBucket002'; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: 'Thumbor', bucket: 'allowedBucket001', key: 'test-image-001.jpg', edits: { toFormat: 'png', png: { quality: 50 } }, originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=31536000,public', outputFormat: 'png', contentType: 'image/png' }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'allowedBucket001', Key: 'test-image-001.jpg' }); expect(imageRequestInfo).toEqual(expectedResult); }); }); describe('005/customImageRequest', () => { const OLD_ENV = process.env; beforeEach(() => { jest.resetAllMocks(); process.env = { ...OLD_ENV }; }); afterEach(() => { jest.clearAllMocks(); }); afterAll(() => { process.env = OLD_ENV; }); it('Should pass when a custom image request is provided and populate the ImageRequest object with the proper values', async () => { // Arrange const event = { path: '/filters-rotate(90)/filters-grayscale()/custom-image.jpg' }; process.env = { SOURCE_BUCKETS: 'allowedBucket001, allowedBucket002', REWRITE_MATCH_PATTERN: '/(filters-)/gm', REWRITE_SUBSTITUTION: 'filters:' }; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ CacheControl: 'max-age=300,public', ContentType: 'custom-type', Expires: 'Tue, 24 Dec 2019 13:46:28 GMT', LastModified: 'Sat, 19 Dec 2009 16:30:47 GMT', Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: RequestTypes.CUSTOM, bucket: 'allowedBucket001', key: 'custom-image.jpg', edits: { grayscale: true, rotate: 90 }, originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=300,public', contentType: 'custom-type', expires: 'Tue, 24 Dec 2019 13:46:28 GMT', lastModified: 'Sat, 19 Dec 2009 16:30:47 GMT' }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'allowedBucket001', Key: 'custom-image.jpg' }); expect(imageRequestInfo).toEqual(expectedResult); }); it('Should pass when a custom image request is provided and populate the ImageRequest object with the proper values and no file extension', async () => { // Arrange const event = { path: '/filters-rotate(90)/filters-grayscale()/custom-image' }; process.env = { SOURCE_BUCKETS: 'allowedBucket001, allowedBucket002', REWRITE_MATCH_PATTERN: '/(filters-)/gm', REWRITE_SUBSTITUTION: 'filters:' }; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ CacheControl: 'max-age=300,public', ContentType: 'custom-type', Expires: 'Tue, 24 Dec 2019 13:46:28 GMT', LastModified: 'Sat, 19 Dec 2009 16:30:47 GMT', Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: RequestTypes.CUSTOM, bucket: 'allowedBucket001', key: 'custom-image', edits: { grayscale: true, rotate: 90 }, originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=300,public', contentType: 'custom-type', expires: 'Tue, 24 Dec 2019 13:46:28 GMT', lastModified: 'Sat, 19 Dec 2009 16:30:47 GMT' }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'allowedBucket001', Key: 'custom-image' }); expect(imageRequestInfo).toEqual(expectedResult); }); }); describe('006/errorCase', () => { const OLD_ENV = process.env; beforeEach(() => { jest.resetAllMocks(); process.env = { ...OLD_ENV }; }); afterEach(() => { jest.clearAllMocks(); }); afterAll(() => { process.env = OLD_ENV; }); it('Should pass when an error is caught', async () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJ2YWxpZEJ1Y2tldCIsImtleSI6InZhbGlkS2V5IiwiZWRpdHMiOnsiZ3JheXNjYWxlIjp0cnVlfX0=' }; process.env.SOURCE_BUCKETS = 'allowedBucket001, allowedBucket002'; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); // Assert try { await imageRequest.setup(event); } catch (error) { expect(error.code).toEqual('ImageBucket::CannotAccessBucket'); } }); }); describe('007/enableSignature', () => { const OLD_ENV = process.env; beforeAll(() => { process.env.ENABLE_SIGNATURE = 'Yes'; process.env.SECRETS_MANAGER = 'serverless-image-handler'; process.env.SECRET_KEY = 'signatureKey'; process.env.SOURCE_BUCKETS = 'validBucket'; }); beforeEach(() => { jest.resetAllMocks(); }); afterEach(() => { jest.clearAllMocks(); }); afterAll(() => { process.env = OLD_ENV; }); it('Should pass when the image signature is correct', async () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJ2YWxpZEJ1Y2tldCIsImtleSI6InZhbGlkS2V5IiwiZWRpdHMiOnsidG9Gb3JtYXQiOiJwbmcifX0=', queryStringParameters: { signature: '4d41311006641a56de7bca8abdbda91af254506107a2c7b338a13ca2fa95eac3' } }; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ Body: Buffer.from('SampleImageContent\n') }); } })); mockAwsSecretManager.getSecretValue.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ SecretString: JSON.stringify({ [process.env.SECRET_KEY]: 'secret' }) }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: 'Default', bucket: 'validBucket', key: 'validKey', edits: { toFormat: 'png' }, outputFormat: 'png', originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=31536000,public', contentType: 'image/png' }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'validBucket', Key: 'validKey' }); expect(mockAwsSecretManager.getSecretValue).toHaveBeenCalledWith({ SecretId: process.env.SECRETS_MANAGER }); expect(imageRequestInfo).toEqual(expectedResult); }); it('Should throw an error when queryStringParameters are missing', async () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJ2YWxpZEJ1Y2tldCIsImtleSI6InZhbGlkS2V5IiwiZWRpdHMiOnsidG9Gb3JtYXQiOiJwbmcifX0=' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); try { await imageRequest.setup(event); } catch (error) { // Assert expect(error).toMatchObject({ status: StatusCodes.BAD_REQUEST, code: 'AuthorizationQueryParametersError', message: 'Query-string requires the signature parameter.' }); } }); it('Should throw an error when the image signature query parameter is missing', async () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJ2YWxpZEJ1Y2tldCIsImtleSI6InZhbGlkS2V5IiwiZWRpdHMiOnsidG9Gb3JtYXQiOiJwbmcifX0=', queryStringParameters: null }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); try { await imageRequest.setup(event); } catch (error) { // Assert expect(error).toMatchObject({ status: StatusCodes.BAD_REQUEST, message: 'Query-string requires the signature parameter.', code: 'AuthorizationQueryParametersError' }); } }); it('Should throw an error when signature does not match', async () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJ2YWxpZEJ1Y2tldCIsImtleSI6InZhbGlkS2V5IiwiZWRpdHMiOnsidG9Gb3JtYXQiOiJwbmcifX0=', queryStringParameters: { signature: 'invalid' } }; // Mock mockAwsSecretManager.getSecretValue.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ SecretString: JSON.stringify({ [process.env.SECRET_KEY]: 'secret' }) }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); try { await imageRequest.setup(event); } catch (error) { // Assert expect(mockAwsSecretManager.getSecretValue).toHaveBeenCalledWith({ SecretId: process.env.SECRETS_MANAGER }); expect(error).toMatchObject({ status: 403, message: 'Signature does not match.', code: 'SignatureDoesNotMatch' }); } }); it('Should throw an error when any other error occurs', async () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJ2YWxpZEJ1Y2tldCIsImtleSI6InZhbGlkS2V5IiwiZWRpdHMiOnsidG9Gb3JtYXQiOiJwbmcifX0=', queryStringParameters: { signature: '4d41311006641a56de7bca8abdbda91af254506107a2c7b338a13ca2fa95eac3' } }; // Mock mockAwsSecretManager.getSecretValue.mockImplementationOnce(() => ({ promise() { return Promise.reject(new ImageHandlerError(StatusCodes.INTERNAL_SERVER_ERROR, 'InternalServerError', 'SimulatedError')); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); try { await imageRequest.setup(event); } catch (error) { // Assert expect(mockAwsSecretManager.getSecretValue).toHaveBeenCalledWith({ SecretId: process.env.SECRETS_MANAGER }); expect(error).toMatchObject({ status: StatusCodes.INTERNAL_SERVER_ERROR, message: 'Signature validation failed.', code: 'SignatureValidationFailure' }); } }); }); describe('008/SVGSupport', () => { const OLD_ENV = process.env; beforeAll(() => { process.env.ENABLE_SIGNATURE = 'No'; process.env.SOURCE_BUCKETS = 'validBucket'; }); beforeEach(() => { jest.resetAllMocks(); }); afterEach(() => { jest.clearAllMocks(); }); afterAll(() => { process.env = OLD_ENV; }); it('Should return SVG image when no edit is provided for the SVG image', async () => { // Arrange const event = { path: '/image.svg' }; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ ContentType: 'image/svg+xml', Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: 'Thumbor', bucket: 'validBucket', key: 'image.svg', edits: {}, originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=31536000,public', contentType: 'image/svg+xml' }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'validBucket', Key: 'image.svg' }); expect(imageRequestInfo).toEqual(expectedResult); }); it('Should return WebP image when there are any edits and no output is specified for the SVG image', async () => { // Arrange const event = { path: '/100x100/image.svg' }; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ ContentType: 'image/svg+xml', Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: 'Thumbor', bucket: 'validBucket', key: 'image.svg', edits: { resize: { width: 100, height: 100 } }, outputFormat: 'png', originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=31536000,public', contentType: 'image/png' }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'validBucket', Key: 'image.svg' }); expect(imageRequestInfo).toEqual(expectedResult); }); it('Should return JPG image when output is specified to JPG for the SVG image', async () => { // Arrange const event = { path: '/filters:format(jpg)/image.svg' }; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ ContentType: 'image/svg+xml', Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: 'Thumbor', bucket: 'validBucket', key: 'image.svg', edits: { toFormat: 'jpeg' }, outputFormat: 'jpeg', originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=31536000,public', contentType: 'image/jpeg' }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'validBucket', Key: 'image.svg' }); expect(imageRequestInfo).toEqual(expectedResult); }); }); describe('009/customHeaders', () => { const OLD_ENV = process.env; beforeEach(() => { jest.resetAllMocks(); process.env = { ...OLD_ENV }; }); afterEach(() => { jest.clearAllMocks(); }); afterAll(() => { process.env = OLD_ENV; }); it('Should pass and return the customer headers if custom headers are provided', async () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJ2YWxpZEJ1Y2tldCIsImtleSI6InZhbGlkS2V5IiwiaGVhZGVycyI6eyJDYWNoZS1Db250cm9sIjoibWF4LWFnZT0zMTUzNjAwMCxwdWJsaWMifSwib3V0cHV0Rm9ybWF0IjoianBlZyJ9' }; process.env.SOURCE_BUCKETS = 'validBucket, validBucket2'; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: 'Default', bucket: 'validBucket', key: 'validKey', headers: { 'Cache-Control': 'max-age=31536000,public' }, outputFormat: 'jpeg', originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=31536000,public', contentType: 'image/jpeg' }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'validBucket', Key: 'validKey' }); expect(imageRequestInfo).toEqual(expectedResult); }); }); describe('010/reductionEffort', () => { it('Should pass when valid reduction effort is provided and output is webp', async () => { const event = { path: '/eyJidWNrZXQiOiJ0ZXN0Iiwia2V5IjoidGVzdC5wbmciLCJvdXRwdXRGb3JtYXQiOiJ3ZWJwIiwicmVkdWN0aW9uRWZmb3J0IjozfQ==' }; process.env.SOURCE_BUCKETS = 'test, validBucket, validBucket2'; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: 'Default', bucket: 'test', key: 'test.png', edits: undefined, headers: undefined, outputFormat: 'webp', originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=31536000,public', contentType: 'image/webp', reductionEffort: 3 }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'test', Key: 'test.png' }); expect(imageRequestInfo).toEqual(expectedResult); }); it('Should pass and use default reduction effort if it is invalid type and output is webp', async () => { const event = { path: '/eyJidWNrZXQiOiJ0ZXN0Iiwia2V5IjoidGVzdC5wbmciLCJvdXRwdXRGb3JtYXQiOiJ3ZWJwIiwicmVkdWN0aW9uRWZmb3J0IjoidGVzdCJ9' }; process.env.SOURCE_BUCKETS = 'test, validBucket, validBucket2'; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: 'Default', bucket: 'test', key: 'test.png', edits: undefined, headers: undefined, outputFormat: 'webp', originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=31536000,public', contentType: 'image/webp', reductionEffort: 4 }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'test', Key: 'test.png' }); expect(imageRequestInfo).toEqual(expectedResult); }); it('Should pass and use default reduction effort if it is out of range and output is webp', async () => { const event = { path: '/eyJidWNrZXQiOiJ0ZXN0Iiwia2V5IjoidGVzdC5wbmciLCJvdXRwdXRGb3JtYXQiOiJ3ZWJwIiwicmVkdWN0aW9uRWZmb3J0IjoxMH0=' }; process.env.SOURCE_BUCKETS = 'test, validBucket, validBucket2'; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: 'Default', bucket: 'test', key: 'test.png', edits: undefined, headers: undefined, outputFormat: 'webp', originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=31536000,public', contentType: 'image/webp', reductionEffort: 4 }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'test', Key: 'test.png' }); expect(imageRequestInfo).toEqual(expectedResult); }); it('Should pass and not use reductionEffort if it is not provided and output is webp', async () => { const event = { path: '/eyJidWNrZXQiOiJ0ZXN0Iiwia2V5IjoidGVzdC5wbmciLCJvdXRwdXRGb3JtYXQiOiJ3ZWJwIn0=' }; process.env.SOURCE_BUCKETS = 'test, validBucket, validBucket2'; // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const imageRequestInfo = await imageRequest.setup(event); const expectedResult = { requestType: 'Default', bucket: 'test', key: 'test.png', edits: undefined, headers: undefined, outputFormat: 'webp', originalImage: Buffer.from('SampleImageContent\n'), cacheControl: 'max-age=31536000,public', contentType: 'image/webp' }; // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'test', Key: 'test.png' }); expect(imageRequestInfo).toEqual(expectedResult); }); }); }); describe('getOriginalImage()', () => { const s3Client = new S3(); const secretsManager = new SecretsManager(); const secretProvider = new SecretProvider(secretsManager); beforeEach(() => { jest.resetAllMocks(); }); afterEach(() => { jest.clearAllMocks(); }); describe('001/imageExists', () => { it('Should pass if the proper bucket name and key are supplied, simulating an image file that can be retrieved', async () => { // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ Body: Buffer.from('SampleImageContent\n') }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = await imageRequest.getOriginalImage('validBucket', 'validKey'); // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'validBucket', Key: 'validKey' }); expect(result.originalImage).toEqual(Buffer.from('SampleImageContent\n')); }); }); describe('002/imageDoesNotExist', () => { it('Should throw an error if an invalid bucket or key name is provided, simulating a non-existent original image', async () => { // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.reject(new ImageHandlerError(StatusCodes.NOT_FOUND, 'NoSuchKey', 'SimulatedException')); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); // Assert try { await imageRequest.getOriginalImage('invalidBucket', 'invalidKey'); } catch (error) { expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'invalidBucket', Key: 'invalidKey' }); expect(error.status).toEqual(StatusCodes.NOT_FOUND); } }); }); describe('003/unknownError', () => { it('Should throw an error if an unknown problem happens when getting an object', async () => { // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.reject(new ImageHandlerError(StatusCodes.INTERNAL_SERVER_ERROR, 'InternalServerError', 'SimulatedException')); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); // Assert try { await imageRequest.getOriginalImage('invalidBucket', 'invalidKey'); } catch (error) { expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'invalidBucket', Key: 'invalidKey' }); expect(error.status).toEqual(StatusCodes.INTERNAL_SERVER_ERROR); } }); }); describe('004/noExtension', () => { const testFiles = [ [0x89, 0x50, 0x4e, 0x47], [0xff, 0xd8, 0xff, 0xdb], [0xff, 0xd8, 0xff, 0xe0], [0xff, 0xd8, 0xff, 0xee], [0xff, 0xd8, 0xff, 0xe1], [0x52, 0x49, 0x46, 0x46], [0x49, 0x49, 0x2a, 0x00], [0x4d, 0x4d, 0x00, 0x2a] ]; const expectFileType = ['image/png', 'image/jpeg', 'image/jpeg', 'image/jpeg', 'image/jpeg', 'image/webp', 'image/tiff', 'image/tiff']; testFiles.forEach((test, index) => { it('Should pass and infer content type if there is no extension, had default s3 content type and it has a valid key and a valid bucket', async () => { // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ ContentType: 'binary/octet-stream', Body: Buffer.from(new Uint8Array(test)) }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = await imageRequest.getOriginalImage('validBucket', 'validKey'); // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'validBucket', Key: 'validKey' }); expect(result.originalImage).toEqual(Buffer.from(new Uint8Array(test))); expect(result.contentType).toEqual(expectFileType[index]); }); it('Should pass and infer content type if there is no extension, had default s3 content type and it has a valid key and a valid bucket and content type is application/octet-stream', async () => { // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ ContentType: 'application/octet-stream', Body: Buffer.from(new Uint8Array(test)) }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = await imageRequest.getOriginalImage('validBucket', 'validKey'); // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'validBucket', Key: 'validKey' }); expect(result.originalImage).toEqual(Buffer.from(new Uint8Array(test))); expect(result.contentType).toEqual(expectFileType[index]); }); it('Should fail to infer content type if there is no extension and file header is not recognized', async () => { // Mock mockAwsS3.getObject.mockImplementationOnce(() => ({ promise() { return Promise.resolve({ ContentType: 'binary/octet-stream', Body: Buffer.from(new Uint8Array(test)) }); } })); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); try { await imageRequest.getOriginalImage('validBucket', 'validKey'); } catch (error) { // Assert expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'validBucket', Key: 'validKey' }); expect(error.status).toEqual(500); } }); }); }); }); describe('parseImageBucket()', () => { const s3Client = new S3(); const secretsManager = new SecretsManager(); const secretProvider = new SecretProvider(secretsManager); const OLD_ENV = process.env; beforeEach(() => { process.env = { ...OLD_ENV }; }); afterAll(() => { process.env = OLD_ENV; }); describe('001/defaultRequestType/bucketSpecifiedInRequest/allowed', () => { it('Should pass if the bucket name is provided in the image request and has been allowed in SOURCE_BUCKETS', () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJhbGxvd2VkQnVja2V0MDAxIiwia2V5Ijoic2FtcGxlSW1hZ2VLZXkwMDEuanBnIiwiZWRpdHMiOnsiZ3JheXNjYWxlIjoidHJ1ZSJ9fQ==' }; process.env.SOURCE_BUCKETS = 'allowedBucket001, allowedBucket002'; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageBucket(event, RequestTypes.DEFAULT); // Assert const expectedResult = 'allowedBucket001'; expect(result).toEqual(expectedResult); }); }); describe('002/defaultRequestType/bucketSpecifiedInRequest/notAllowed', () => { it('Should throw an error if the bucket name is provided in the image request but has not been allowed in SOURCE_BUCKETS', () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJhbGxvd2VkQnVja2V0MDAxIiwia2V5Ijoic2FtcGxlSW1hZ2VLZXkwMDEuanBnIiwiZWRpdHMiOnsiZ3JheXNjYWxlIjoidHJ1ZSJ9fQ==' }; process.env.SOURCE_BUCKETS = 'allowedBucket003, allowedBucket004'; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); // Assert try { imageRequest.parseImageBucket(event, RequestTypes.DEFAULT); } catch (error) { expect(error).toMatchObject({ status: StatusCodes.FORBIDDEN, code: 'ImageBucket::CannotAccessBucket', message: 'The bucket you specified could not be accessed. Please check that the bucket is specified in your SOURCE_BUCKETS.' }); } }); }); describe('003/defaultRequestType/bucketNotSpecifiedInRequest', () => { it('Should pass if the image request does not contain a source bucket but SOURCE_BUCKETS contains at least one bucket that can be used as a default', () => { // Arrange const event = { path: '/eyJrZXkiOiJzYW1wbGVJbWFnZUtleTAwMS5qcGciLCJlZGl0cyI6eyJncmF5c2NhbGUiOiJ0cnVlIn19==' }; process.env.SOURCE_BUCKETS = 'allowedBucket001, allowedBucket002'; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageBucket(event, RequestTypes.DEFAULT); // Assert const expectedResult = 'allowedBucket001'; expect(result).toEqual(expectedResult); }); }); describe('004/thumborRequestType', () => { it('Should pass if there is at least one SOURCE_BUCKET specified that can be used as the default for Thumbor requests', () => { // Arrange const event = { path: '/filters:grayscale()/test-image-001.jpg' }; process.env.SOURCE_BUCKETS = 'allowedBucket001, allowedBucket002'; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageBucket(event, RequestTypes.THUMBOR); // Assert const expectedResult = 'allowedBucket001'; expect(result).toEqual(expectedResult); }); }); describe('005/customRequestType', () => { it('Should pass if there is at least one SOURCE_BUCKET specified that can be used as the default for Custom requests', () => { // Arrange const event = { path: '/filters:grayscale()/test-image-001.jpg' }; process.env.SOURCE_BUCKETS = 'allowedBucket001, allowedBucket002'; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageBucket(event, RequestTypes.CUSTOM); // Assert const expectedResult = 'allowedBucket001'; expect(result).toEqual(expectedResult); }); }); describe('006/invalidRequestType', () => { it('Should pass if there is at least one SOURCE_BUCKET specified that can be used as the default for Custom requests', () => { // Arrange const event = { path: '/filters:grayscale()/test-image-001.jpg' }; process.env.SOURCE_BUCKETS = 'allowedBucket001, allowedBucket002'; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); // Assert try { imageRequest.parseImageBucket(event, undefined); } catch (error) { expect(error).toMatchObject({ status: StatusCodes.NOT_FOUND, code: 'ImageBucket::CannotFindBucket', message: 'The bucket you specified could not be found. Please check the spelling of the bucket name in your request.' }); } }); }); }); describe('parseImageEdits()', () => { const s3Client = new S3(); const secretsManager = new SecretsManager(); const secretProvider = new SecretProvider(secretsManager); const OLD_ENV = process.env; beforeEach(() => { process.env = { ...OLD_ENV }; }); afterAll(() => { process.env = OLD_ENV; }); describe('001/defaultRequestType', () => { it('Should pass if the proper result is returned for a sample base64-encoded image request', () => { // Arrange const event = { path: '/eyJlZGl0cyI6eyJncmF5c2NhbGUiOiJ0cnVlIiwicm90YXRlIjo5MCwiZmxpcCI6InRydWUifX0=' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageEdits(event, RequestTypes.DEFAULT); // Assert const expectedResult = { grayscale: 'true', rotate: 90, flip: 'true' }; expect(result).toEqual(expectedResult); }); }); describe('002/thumborRequestType', () => { it('Should pass if the proper result is returned for a sample thumbor-type image request', () => { // Arrange const event = { path: '/filters:rotate(90)/filters:grayscale()/thumbor-image.jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageEdits(event, RequestTypes.THUMBOR); // Assert const expectedResult = { rotate: 90, grayscale: true }; expect(result).toEqual(expectedResult); }); }); describe('003/customRequestType', () => { it('Should pass if the proper result is returned for a sample custom-type image request', () => { // Arrange const event = { path: '/filters-rotate(90)/filters-grayscale()/thumbor-image.jpg' }; process.env = { REWRITE_MATCH_PATTERN: '/(filters-)/gm', REWRITE_SUBSTITUTION: 'filters:' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageEdits(event, RequestTypes.CUSTOM); // Assert const expectedResult = { rotate: 90, grayscale: true }; expect(result).toEqual(expectedResult); }); }); describe('004/customRequestType', () => { it('Should throw an error if a requestType is not specified and/or the image edits cannot be parsed', () => { // Arrange const event = { path: '/filters:rotate(90)/filters:grayscale()/other-image.jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); // Assert try { imageRequest.parseImageEdits(event, undefined); } catch (error) { expect(error).toMatchObject({ status: StatusCodes.BAD_REQUEST, code: 'ImageEdits::CannotParseEdits', message: 'The edits you provided could not be parsed. Please check the syntax of your request and refer to the documentation for additional guidance.' }); } }); }); }); describe('parseImageKey()', () => { const s3Client = new S3(); const secretsManager = new SecretsManager(); const secretProvider = new SecretProvider(secretsManager); const OLD_ENV = process.env; beforeEach(() => { process.env = { ...OLD_ENV }; }); afterAll(() => { process.env = OLD_ENV; }); describe('001/defaultRequestType', () => { it('Should pass if an image key value is provided in the default request format', () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJteS1zYW1wbGUtYnVja2V0Iiwia2V5Ijoic2FtcGxlLWltYWdlLTAwMS5qcGcifQ==' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.DEFAULT); // Assert const expectedResult = 'sample-image-001.jpg'; expect(result).toEqual(expectedResult); }); }); describe('002/defaultRequestType/withSlashRequest', () => { it('should read image requests with base64 encoding having slash', () => { const event = { path: '/eyJidWNrZXQiOiJlbGFzdGljYmVhbnN0YWxrLXVzLWVhc3QtMi0wNjY3ODQ4ODU1MTgiLCJrZXkiOiJlbnYtcHJvZC9nY2MvbGFuZGluZ3BhZ2UvMV81N19TbGltTl9MaWZ0LUNvcnNldC1Gb3ItTWVuLVNOQVAvYXR0YWNobWVudHMvZmZjMWYxNjAtYmQzOC00MWU4LThiYWQtZTNhMTljYzYxZGQzX1/Ys9mE2YrZhSDZhNmK2YHYqiAoMikuanBnIiwiZWRpdHMiOnsicmVzaXplIjp7IndpZHRoIjo0ODAsImZpdCI6ImNvdmVyIn19fQ==' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.DEFAULT); // Assert const expectedResult = 'env-prod/gcc/landingpage/1_57_SlimN_Lift-Corset-For-Men-SNAP/attachments/ffc1f160-bd38-41e8-8bad-e3a19cc61dd3__سليم ليفت (2).jpg'; expect(result).toEqual(expectedResult); }); }); describe('003/thumborRequestType', () => { it('Should pass if an image key value is provided in the thumbor request format', () => { // Arrange const event = { path: '/filters:rotate(90)/filters:grayscale()/thumbor-image.jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.THUMBOR); // Assert const expectedResult = 'thumbor-image.jpg'; expect(result).toEqual(expectedResult); }); }); describe('004/thumborRequestType/withParenthesesRequest', () => { it('Should pass if an image key value is provided in the thumbor request format having open, close parentheses', () => { // Arrange const event = { path: '/filters:rotate(90)/filters:grayscale()/thumbor-image (1).jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.THUMBOR); // Assert const expectedResult = 'thumbor-image (1).jpg'; expect(result).toEqual(expectedResult); }); it('Should pass if an image key value is provided in the thumbor request format having open parentheses', () => { // Arrange const event = { path: '/filters:rotate(90)/filters:grayscale()/thumbor-image (1.jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.THUMBOR); // Assert const expectedResult = 'thumbor-image (1.jpg'; expect(result).toEqual(expectedResult); }); it('Should pass if an image key value is provided in the thumbor request format having close parentheses', () => { // Arrange const event = { path: '/filters:rotate(90)/filters:grayscale()/thumbor-image 1).jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.THUMBOR); // Assert const expectedResult = 'thumbor-image 1).jpg'; expect(result).toEqual(expectedResult); }); it('Should pass if an image key value is provided in the thumbor request format having close parentheses in the middle of the name', () => { // Arrange const event = { path: '/filters:rotate(90)/filters:grayscale()/thumbor-image (1) suffix.jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.THUMBOR); // Assert const expectedResult = 'thumbor-image (1) suffix.jpg'; expect(result).toEqual(expectedResult); }); it('Should pass if an image key value is provided in the thumbor request and the path has crop filter', () => { // Arrange const event = { path: '/10x10:100x100/filters:rotate(90)/filters:grayscale()/thumbor-image (1) suffix.jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.THUMBOR); // Assert const expectedResult = 'thumbor-image (1) suffix.jpg'; expect(result).toEqual(expectedResult); }); it('Should pass if an image key value is provided in the thumbor request and the path has resize filter', () => { // Arrange const event = { path: '/10x10/filters:rotate(90)/filters:grayscale()/thumbor-image (1) suffix.jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.THUMBOR); // Assert const expectedResult = 'thumbor-image (1) suffix.jpg'; expect(result).toEqual(expectedResult); }); it('Should pass if an image key value is provided in the thumbor request and the path has crop and resize filters', () => { // Arrange const event = { path: '/10x20:100x200/10x10/filters:rotate(90)/filters:grayscale()/thumbor-image (1) suffix.jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.THUMBOR); // Assert const expectedResult = 'thumbor-image (1) suffix.jpg'; expect(result).toEqual(expectedResult); }); it('Should pass if an image key value is provided in the thumbor request and the key string has substring "fit-in"', () => { // Arrange const event = { path: '/fit-in/400x0/filters:fill(ffffff)/fit-in-thumbor-image (1) suffix.jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.THUMBOR); // Assert const expectedResult = 'fit-in-thumbor-image (1) suffix.jpg'; expect(result).toEqual(expectedResult); }); it('Should pass if the image in the sub-directory', () => { // Arrange const event = { path: '/100x100/test-100x100/test/beach-100x100.jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.THUMBOR); // Assert const expectedResult = 'test-100x100/test/beach-100x100.jpg'; expect(result).toEqual(expectedResult); }); }); describe('005/customRequestType', () => { it('Should pass if an image key value is provided in the custom request format', () => { // Arrange const event = { path: '/filters-rotate(90)/filters-grayscale()/custom-image.jpg' }; process.env = { REWRITE_MATCH_PATTERN: '/(filters-)/gm', REWRITE_SUBSTITUTION: 'filters:' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.CUSTOM); // Assert const expectedResult = 'custom-image.jpg'; expect(result).toEqual(expectedResult); }); }); describe('006/customRequestStringType', () => { it('Should pass if an image key value is provided in the custom request format', () => { // Arrange const event = { path: '/filters-rotate(90)/filters-grayscale()/custom-image.jpg' }; process.env = { REWRITE_MATCH_PATTERN: '/(filters-)/gm', REWRITE_SUBSTITUTION: 'filters:' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageKey(event, RequestTypes.CUSTOM); // Assert const expectedResult = 'custom-image.jpg'; expect(result).toEqual(expectedResult); }); }); describe('007/elseCondition', () => { it('Should throw an error if an unrecognized requestType is passed into the function as a parameter', () => { // Arrange const event = { path: '/filters:rotate(90)/filters:grayscale()/other-image.jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); // Assert try { imageRequest.parseImageKey(event, undefined); } catch (error) { expect(error).toMatchObject({ status: StatusCodes.NOT_FOUND, code: 'ImageEdits::CannotFindImage', message: 'The image you specified could not be found. Please check your request syntax as well as the bucket you specified to ensure it exists.' }); } }); }); }); describe('parseRequestType()', () => { const s3Client = new S3(); const secretsManager = new SecretsManager(); const secretProvider = new SecretProvider(secretsManager); const OLD_ENV = process.env; beforeEach(() => { process.env = { ...OLD_ENV }; }); afterAll(() => { process.env = OLD_ENV; }); describe('001/defaultRequestType', () => { it('Should pass if the method detects a default request', () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJteS1zYW1wbGUtYnVja2V0Iiwia2V5IjoibXktc2FtcGxlLWtleSIsImVkaXRzIjp7ImdyYXlzY2FsZSI6dHJ1ZX19' }; process.env = {}; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseRequestType(event); // Assert const expectedResult = RequestTypes.DEFAULT; expect(result).toEqual(expectedResult); }); }); describe('002/thumborRequestType', () => { it('Should pass if the method detects a thumbor request', () => { // Arrange const event = { path: '/unsafe/filters:brightness(10):contrast(30)/https://upload.wikimedia.org/wikipedia/commons/thumb/7/79/Coffee_berries_1.jpg/1200px-Coffee_berries_1.jpg' }; process.env = {}; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseRequestType(event); // Assert const expectedResult = RequestTypes.THUMBOR; expect(result).toEqual(expectedResult); }); }); describe('003/customRequestType', () => { it('Should pass if the method detects a custom request', () => { // Arrange const event = { path: '/additionalImageRequestParameters/image.jpg' }; process.env = { REWRITE_MATCH_PATTERN: 'matchPattern', REWRITE_SUBSTITUTION: 'substitutionString' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseRequestType(event); // Assert const expectedResult = RequestTypes.CUSTOM; expect(result).toEqual(expectedResult); }); }); describe('004/elseCondition', () => { it('Should throw an error if the method cannot determine the request type based on the three groups given', () => { // Arrange const event = { path: '12x12e24d234r2ewxsad123d34r.bmp' }; process.env = {}; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); // Assert try { imageRequest.parseRequestType(event); } catch (error) { expect(error).toMatchObject({ status: StatusCodes.BAD_REQUEST, code: 'RequestTypeError', message: 'The type of request you are making could not be processed. Please ensure that your original image is of a supported file type (jpg, png, tiff, webp, svg) and that your image request is provided in the correct syntax. Refer to the documentation for additional guidance on forming image requests.' }); } }); }); }); describe('parseImageHeaders()', () => { const s3Client = new S3(); const secretsManager = new SecretsManager(); const secretProvider = new SecretProvider(secretsManager); it('001/Should return headers if headers are provided for a sample base64-encoded image request', () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJ2YWxpZEJ1Y2tldCIsImtleSI6InZhbGlkS2V5IiwiaGVhZGVycyI6eyJDYWNoZS1Db250cm9sIjoibWF4LWFnZT0zMTUzNjAwMCxwdWJsaWMifSwib3V0cHV0Rm9ybWF0IjoianBlZyJ9' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageHeaders(event, RequestTypes.DEFAULT); // Assert const expectedResult = { 'Cache-Control': 'max-age=31536000,public' }; expect(result).toEqual(expectedResult); }); it('001/Should return undefined if headers are not provided for a base64-encoded image request', () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJ2YWxpZEJ1Y2tldCIsImtleSI6InZhbGlkS2V5In0=' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageHeaders(event, RequestTypes.DEFAULT); // Assert expect(result).toEqual(undefined); }); it('001/Should return undefined for Thumbor or Custom requests', () => { // Arrange const event = { path: '/test.jpg' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.parseImageHeaders(event, RequestTypes.THUMBOR); // Assert expect(result).toEqual(undefined); }); }); describe('decodeRequest()', () => { const s3Client = new S3(); const secretsManager = new SecretsManager(); const secretProvider = new SecretProvider(secretsManager); describe('001/validRequestPathSpecified', () => { it('Should pass if a valid base64-encoded path has been specified', () => { // Arrange const event = { path: '/eyJidWNrZXQiOiJidWNrZXQtbmFtZS1oZXJlIiwia2V5Ijoia2V5LW5hbWUtaGVyZSJ9' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.decodeRequest(event); // Assert const expectedResult = { bucket: 'bucket-name-here', key: 'key-name-here' }; expect(result).toEqual(expectedResult); }); }); describe('002/invalidRequestPathSpecified', () => { it('Should throw an error if a valid base64-encoded path has not been specified', () => { // Arrange const event = { path: '/someNonBase64EncodedContentHere' }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); // Assert try { imageRequest.decodeRequest(event); } catch (error) { expect(error).toMatchObject({ status: StatusCodes.BAD_REQUEST, code: 'DecodeRequest::CannotDecodeRequest', message: 'The image request you provided could not be decoded. Please check that your request is base64 encoded properly and refer to the documentation for additional guidance.' }); } }); }); describe('003/noPathSpecified', () => { it('Should throw an error if no path is specified at all', () => { // Arrange const event = {}; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); // Assert try { imageRequest.decodeRequest(event); } catch (error) { expect(error).toMatchObject({ status: StatusCodes.BAD_REQUEST, code: 'DecodeRequest::CannotReadPath', message: 'The URL path you provided could not be read. Please ensure that it is properly formed according to the solution documentation.' }); } }); }); }); describe('getAllowedSourceBuckets()', () => { const s3Client = new S3(); const secretsManager = new SecretsManager(); const secretProvider = new SecretProvider(secretsManager); describe('001/sourceBucketsSpecified', () => { it('Should pass if the SOURCE_BUCKETS environment variable is not empty and contains valid inputs', () => { // Arrange process.env.SOURCE_BUCKETS = 'allowedBucket001, allowedBucket002'; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.getAllowedSourceBuckets(); // Assert const expectedResult = ['allowedBucket001', 'allowedBucket002']; expect(result).toEqual(expectedResult); }); }); describe('002/noSourceBucketsSpecified', () => { it('Should throw an error if the SOURCE_BUCKETS environment variable is empty or does not contain valid values', () => { // Arrange process.env = {}; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); // Assert try { imageRequest.getAllowedSourceBuckets(); } catch (error) { expect(error).toMatchObject({ status: StatusCodes.BAD_REQUEST, code: 'GetAllowedSourceBuckets::NoSourceBuckets', message: 'The SOURCE_BUCKETS variable could not be read. Please check that it is not empty and contains at least one source bucket, or multiple buckets separated by commas. Spaces can be provided between commas and bucket names, these will be automatically parsed out when decoding.' }); } }); }); }); describe('getOutputFormat()', () => { const s3Client = new S3(); const secretsManager = new SecretsManager(); const secretProvider = new SecretProvider(secretsManager); const OLD_ENV = process.env; beforeEach(() => { process.env = { ...OLD_ENV }; }); afterAll(() => { process.env = OLD_ENV; }); describe('001/AcceptsHeaderIncludesWebP', () => { it('Should pass if it returns "webp" for an accepts header which includes webp', () => { // Arrange const event = { headers: { Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3' } }; process.env.AUTO_WEBP = 'Yes'; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.getOutputFormat(event); // Assert expect(result).toEqual('webp'); }); }); describe('002/AcceptsHeaderDoesNotIncludeWebP', () => { it('Should pass if it returns null for an accepts header which does not include webp', () => { // Arrange const event = { headers: { Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/apng,*/*;q=0.8,application/signed-exchange;v=b3' } }; process.env.AUTO_WEBP = 'Yes'; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.getOutputFormat(event); // Assert expect(result).toBeNull(); }); }); describe('003/AutoWebPDisabled', () => { it('Should pass if it returns null when AUTO_WEBP is disabled with accepts header including webp', () => { // Arrange const event = { headers: { Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3' } }; process.env.AUTO_WEBP = 'No'; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.getOutputFormat(event); // Assert expect(result).toBeNull(); }); }); describe('004/AutoWebPUnset', () => { it('Should pass if it returns null when AUTO_WEBP is not set with accepts header including webp', () => { // Arrange const event = { headers: { Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3' } }; // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.getOutputFormat(event); // Assert expect(result).toBeNull(); }); }); }); describe('inferImageType()', () => { const s3Client = new S3(); const secretsManager = new SecretsManager(); const secretProvider = new SecretProvider(secretsManager); describe('001/shouldInferImageType', () => { it('Should pass if it returns "image/jpeg"', () => { // Arrange const imageBuffer = Buffer.from([0xff, 0xd8, 0xff, 0xee, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); // Act const imageRequest = new ImageRequest(s3Client, secretProvider); const result = imageRequest.inferImageType(imageBuffer); // Assert expect(result).toEqual('image/jpeg'); }); }); describe('002/shouldNotInferImageType', () => { it('Should pass throw an exception', () => { // Arrange const imageBuffer = Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); try { // Act const imageRequest = new ImageRequest(s3Client, secretProvider); imageRequest.inferImageType(imageBuffer); } catch (error) { // Assert expect(error.status).toEqual(500); expect(error.code).toEqual('RequestTypeError'); expect(error.message).toEqual( 'The file does not have an extension and the file type could not be inferred. Please ensure that your original image is of a supported file type (jpg, png, tiff, webp, svg). Refer to the documentation for additional guidance on forming image requests.' ); } }); }); });
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * An interface representing ErrorDetails. */ export interface ErrorDetails { code?: string; target?: string; message?: string; } /** * An interface representing ErrorModel. */ export interface ErrorModel { code?: string; message?: string; target?: string; details?: ErrorDetails[]; innerError?: string; } /** * The response body contains the status of the specified asynchronous operation, indicating * whether it has succeeded, is in progress, or has failed. Note that this status is distinct from * the HTTP status code returned for the Get Operation Status operation itself. If the asynchronous * operation succeeded, the response body includes the HTTP status code for the successful request. * If the asynchronous operation failed, the response body includes the HTTP status code for the * failed request and error information regarding the failure. */ export interface AzureAsyncOperationResult { /** * Status of the Azure async operation. Possible values are: 'InProgress', 'Succeeded', and * 'Failed'. Possible values include: 'InProgress', 'Succeeded', 'Failed' */ status?: NetworkOperationStatus; error?: ErrorModel; } /** * Common resource representation. */ export interface Resource extends BaseResource { /** * Resource ID. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource location. */ location?: string; /** * Resource tags. */ tags?: { [propertyName: string]: string }; } /** * Reference to another subresource. */ export interface SubResource extends BaseResource { /** * Resource ID. */ id?: string; } /** * Tags object for patch operations. */ export interface TagsObject { /** * Resource tags. */ tags?: { [propertyName: string]: string }; } /** * Defines an Network Experiment Profile and lists of Experiments */ export interface Profile extends Resource { /** * Resource status. Possible values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', * 'Disabled', 'Deleting' */ resourceState?: NetworkExperimentResourceState; /** * The state of the Experiment. Possible values include: 'Enabled', 'Disabled' */ enabledState?: State; /** * Gets a unique read-only string that changes whenever the resource is updated. */ etag?: string; } /** * Defines the endpoint properties */ export interface Endpoint { /** * The name of the endpoint */ name?: string; /** * The endpoint URL */ endpoint?: string; } /** * Defines modifiable attributes of a Profile */ export interface ProfileUpdateModel { /** * The enabled state of the Profile. Possible values include: 'Enabled', 'Disabled' */ enabledState?: State; /** * Resource tags. */ tags?: { [propertyName: string]: string }; } /** * Defines modifiable attributes of an Experiment */ export interface ExperimentUpdateModel { /** * Resource tags. */ tags?: { [propertyName: string]: string }; /** * The description of the intent or details of the Experiment */ description?: string; /** * The state of the Experiment. Possible values include: 'Enabled', 'Disabled' */ enabledState?: State; } /** * Defines the properties of an Experiment */ export interface Experiment extends Resource { /** * The description of the details or intents of the Experiment */ description?: string; /** * The endpoint A of an experiment */ endpointA?: Endpoint; /** * The endpoint B of an experiment */ endpointB?: Endpoint; /** * The state of the Experiment. Possible values include: 'Enabled', 'Disabled' */ enabledState?: State; /** * Resource status. Possible values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', * 'Disabled', 'Deleting' */ resourceState?: NetworkExperimentResourceState; /** * The description of Experiment status from the server side * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: string; /** * The uri to the Script used in the Experiment * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly scriptFileUri?: string; } /** * Defines the properties of a latency metric used in the latency scorecard */ export interface LatencyMetric { /** * The name of the Latency Metric * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The end time of the Latency Scorecard in UTC * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly endDateTimeUTC?: string; /** * The metric value of the A endpoint * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly aValue?: number; /** * The metric value of the B endpoint * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bValue?: number; /** * The difference in value between endpoint A and B * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly delta?: number; /** * The percent difference between endpoint A and B * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly deltaPercent?: number; /** * The lower end of the 95% confidence interval for endpoint A * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly aCLower95CI?: number; /** * The upper end of the 95% confidence interval for endpoint A * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly aHUpper95CI?: number; /** * The lower end of the 95% confidence interval for endpoint B * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bCLower95CI?: number; /** * The upper end of the 95% confidence interval for endpoint B * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly bUpper95CI?: number; } /** * Defines the LatencyScorecard */ export interface LatencyScorecard extends Resource { /** * The unique identifier of the Latency Scorecard * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly latencyScorecardId?: string; /** * The name of the Latency Scorecard * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly latencyScorecardName?: string; /** * The description of the Latency Scorecard * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * The A endpoint in the scorecard * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly endpointA?: string; /** * The B endpoint in the scorecard * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly endpointB?: string; /** * The start time of the Latency Scorecard in UTC * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly startDateTimeUTC?: Date; /** * The end time of the Latency Scorecard in UTC * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly endDateTimeUTC?: Date; /** * The country associated with the Latency Scorecard. Values are country ISO codes as specified * here- https://www.iso.org/iso-3166-country-codes.html * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly country?: string; /** * The latency metrics of the Latency Scorecard */ latencyMetrics?: LatencyMetric[]; } /** * Defines a timeseries datapoint used in a timeseries */ export interface TimeseriesDataPoint { /** * The DateTime of the Timeseries data point in UTC */ dateTimeUTC?: string; /** * The Value of the Timeseries data point */ value?: number; } /** * Defines the Timeseries */ export interface Timeseries extends Resource { /** * The endpoint associated with the Timeseries data point */ endpoint?: string; /** * The start DateTime of the Timeseries in UTC */ startDateTimeUTC?: string; /** * The end DateTime of the Timeseries in UTC */ endDateTimeUTC?: string; /** * The aggregation interval of the Timeseries. Possible values include: 'Hourly', 'Daily' */ aggregationInterval?: AggregationInterval; /** * The type of Timeseries. Possible values include: 'MeasurementCounts', 'LatencyP50', * 'LatencyP75', 'LatencyP95' */ timeseriesType?: TimeseriesType; /** * The country associated with the Timeseries. Values are country ISO codes as specified here- * https://www.iso.org/iso-3166-country-codes.html */ country?: string; /** * The set of data points for the timeseries */ timeseriesData?: TimeseriesDataPoint[]; } /** * Defines the properties of a preconfigured endpoint */ export interface PreconfiguredEndpoint extends Resource { /** * The description of the endpoint */ description?: string; /** * The endpoint that is preconfigured */ endpoint?: string; /** * The type of endpoint. Possible values include: 'AFD', 'AzureRegion', 'CDN', 'ATM' */ endpointType?: EndpointType; /** * The preconfigured endpoint backend */ backend?: string; } /** * Error response indicates Front Door service is not able to process the incoming request. The * reason is provided in the error message. */ export interface ErrorResponse { /** * Error code. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly code?: string; /** * Error message indicating why the operation failed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; } /** * A rules engine configuration containing a list of rules that will run to modify the runtime * behavior of the request and response. */ export interface RulesEngine extends BaseResource { /** * A list of rules that define a particular Rules Engine Configuration. */ rules?: RulesEngineRule[]; /** * Resource status. Possible values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', * 'Disabled', 'Deleting' */ resourceState?: FrontDoorResourceState; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource ID. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; } /** * Front Door represents a collection of backend endpoints to route traffic to along with rules * that specify how traffic is sent there. */ export interface FrontDoor extends Resource { /** * A friendly name for the frontDoor */ friendlyName?: string; /** * Routing rules associated with this Front Door. */ routingRules?: RoutingRule[]; /** * Load balancing settings associated with this Front Door instance. */ loadBalancingSettings?: LoadBalancingSettingsModel[]; /** * Health probe settings associated with this Front Door instance. */ healthProbeSettings?: HealthProbeSettingsModel[]; /** * Backend pools available to routing rules. */ backendPools?: BackendPool[]; /** * Frontend endpoints available to routing rules. */ frontendEndpoints?: FrontendEndpoint[]; /** * Settings for all backendPools */ backendPoolsSettings?: BackendPoolsSettings; /** * Operational status of the Front Door load balancer. Permitted values are 'Enabled' or * 'Disabled'. Possible values include: 'Enabled', 'Disabled' */ enabledState?: FrontDoorEnabledState; /** * Resource status of the Front Door. Possible values include: 'Creating', 'Enabling', 'Enabled', * 'Disabling', 'Disabled', 'Deleting' */ resourceState?: FrontDoorResourceState; /** * Provisioning state of the Front Door. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: string; /** * The host that each frontendEndpoint must CNAME to. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly cname?: string; /** * The Id of the frontdoor. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly frontdoorId?: string; /** * Rules Engine Configurations available to routing rules. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly rulesEngines?: RulesEngine[]; } /** * A routing rule represents a specification for traffic to treat and where to send it, along with * health probe information. */ export interface RoutingRule extends SubResource { /** * Frontend endpoints associated with this rule */ frontendEndpoints?: SubResource[]; /** * Protocol schemes to match for this rule */ acceptedProtocols?: FrontDoorProtocol[]; /** * The route patterns of the rule. */ patternsToMatch?: string[]; /** * Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled'. Possible * values include: 'Enabled', 'Disabled' */ enabledState?: RoutingRuleEnabledState; /** * A reference to the routing configuration. */ routeConfiguration?: RouteConfigurationUnion; /** * A reference to a specific Rules Engine Configuration to apply to this route. */ rulesEngine?: SubResource; /** * Resource status. Possible values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', * 'Disabled', 'Deleting' */ resourceState?: FrontDoorResourceState; /** * Resource name. */ name?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * Load balancing settings for a backend pool */ export interface LoadBalancingSettingsModel extends SubResource { /** * The number of samples to consider for load balancing decisions */ sampleSize?: number; /** * The number of samples within the sample period that must succeed */ successfulSamplesRequired?: number; /** * The additional latency in milliseconds for probes to fall into the lowest latency bucket */ additionalLatencyMilliseconds?: number; /** * Resource status. Possible values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', * 'Disabled', 'Deleting' */ resourceState?: FrontDoorResourceState; /** * Resource name. */ name?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * Load balancing settings for a backend pool */ export interface HealthProbeSettingsModel extends SubResource { /** * The path to use for the health probe. Default is / */ path?: string; /** * Protocol scheme to use for this probe. Possible values include: 'Http', 'Https' */ protocol?: FrontDoorProtocol; /** * The number of seconds between health probes. */ intervalInSeconds?: number; /** * Configures which HTTP method to use to probe the backends defined under backendPools. Possible * values include: 'GET', 'HEAD'. Default value: 'HEAD'. */ healthProbeMethod?: FrontDoorHealthProbeMethod; /** * Whether to enable health probes to be made against backends defined under backendPools. Health * probes can only be disabled if there is a single enabled backend in single enabled backend * pool. Possible values include: 'Enabled', 'Disabled' */ enabledState?: HealthProbeEnabled; /** * Resource status. Possible values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', * 'Disabled', 'Deleting' */ resourceState?: FrontDoorResourceState; /** * Resource name. */ name?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * A backend pool is a collection of backends that can be routed to. */ export interface BackendPool extends SubResource { /** * The set of backends for this pool */ backends?: Backend[]; /** * Load balancing settings for a backend pool */ loadBalancingSettings?: SubResource; /** * L7 health probe settings for a backend pool */ healthProbeSettings?: SubResource; /** * Resource status. Possible values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', * 'Disabled', 'Deleting' */ resourceState?: FrontDoorResourceState; /** * Resource name. */ name?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * The Key Vault containing the SSL certificate */ export interface KeyVaultCertificateSourceParametersVault { /** * Resource ID. */ id?: string; } /** * Https settings for a domain */ export interface CustomHttpsConfiguration { /** * Defines the source of the SSL certificate. Possible values include: 'AzureKeyVault', * 'FrontDoor' */ certificateSource: FrontDoorCertificateSource; /** * The minimum TLS version required from the clients to establish an SSL handshake with Front * Door. Possible values include: '1.0', '1.2' */ minimumTlsVersion: MinimumTLSVersion; /** * The Key Vault containing the SSL certificate */ vault?: KeyVaultCertificateSourceParametersVault; /** * The name of the Key Vault secret representing the full certificate PFX */ secretName?: string; /** * The version of the Key Vault secret representing the full certificate PFX */ secretVersion?: string; /** * Defines the type of the certificate used for secure connections to a frontendEndpoint. * Possible values include: 'Dedicated' */ certificateType?: FrontDoorCertificateType; } /** * A frontend endpoint used for routing. */ export interface FrontendEndpoint extends SubResource { /** * The host name of the frontendEndpoint. Must be a domain name. */ hostName?: string; /** * Whether to allow session affinity on this host. Valid options are 'Enabled' or 'Disabled'. * Possible values include: 'Enabled', 'Disabled' */ sessionAffinityEnabledState?: SessionAffinityEnabledState; /** * UNUSED. This field will be ignored. The TTL to use in seconds for session affinity, if * applicable. */ sessionAffinityTtlSeconds?: number; /** * Defines the Web Application Firewall policy for each host (if applicable) */ webApplicationFirewallPolicyLink?: FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink; /** * Resource status. Possible values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', * 'Disabled', 'Deleting' */ resourceState?: FrontDoorResourceState; /** * Provisioning status of Custom Https of the frontendEndpoint. Possible values include: * 'Enabling', 'Enabled', 'Disabling', 'Disabled', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly customHttpsProvisioningState?: CustomHttpsProvisioningState; /** * Provisioning substate shows the progress of custom HTTPS enabling/disabling process step by * step. Possible values include: 'SubmittingDomainControlValidationRequest', * 'PendingDomainControlValidationREquestApproval', 'DomainControlValidationRequestApproved', * 'DomainControlValidationRequestRejected', 'DomainControlValidationRequestTimedOut', * 'IssuingCertificate', 'DeployingCertificate', 'CertificateDeployed', 'DeletingCertificate', * 'CertificateDeleted' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly customHttpsProvisioningSubstate?: CustomHttpsProvisioningSubstate; /** * The configuration specifying how to enable HTTPS * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly customHttpsConfiguration?: CustomHttpsConfiguration; /** * Resource name. */ name?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * Settings that apply to all backend pools. */ export interface BackendPoolsSettings { /** * Whether to enforce certificate name check on HTTPS requests to all backend pools. No effect on * non-HTTPS requests. Possible values include: 'Enabled', 'Disabled'. Default value: 'Enabled'. */ enforceCertificateNameCheck?: EnforceCertificateNameCheckEnabledState; /** * Send and receive timeout on forwarding request to the backend. When timeout is reached, the * request fails and returns. */ sendRecvTimeoutSeconds?: number; } /** * The properties needed to update a Front Door */ export interface FrontDoorUpdateParameters { /** * A friendly name for the frontDoor */ friendlyName?: string; /** * Routing rules associated with this Front Door. */ routingRules?: RoutingRule[]; /** * Load balancing settings associated with this Front Door instance. */ loadBalancingSettings?: LoadBalancingSettingsModel[]; /** * Health probe settings associated with this Front Door instance. */ healthProbeSettings?: HealthProbeSettingsModel[]; /** * Backend pools available to routing rules. */ backendPools?: BackendPool[]; /** * Frontend endpoints available to routing rules. */ frontendEndpoints?: FrontendEndpoint[]; /** * Settings for all backendPools */ backendPoolsSettings?: BackendPoolsSettings; /** * Operational status of the Front Door load balancer. Permitted values are 'Enabled' or * 'Disabled'. Possible values include: 'Enabled', 'Disabled' */ enabledState?: FrontDoorEnabledState; } /** * Parameters required for content purge. */ export interface PurgeParameters { /** * The path to the content to be purged. Can describe a file path or a wild card directory. */ contentPaths: string[]; } /** * Result of the request to list Routing Rules. It contains a list of Routing Rule objects and a * URL link to get the next set of results. */ export interface RoutingRuleListResult { /** * List of Routing Rules within a Front Door. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly value?: RoutingRule[]; /** * URL to get the next set of RoutingRule objects if there are any. */ nextLink?: string; } /** * Contains the possible cases for RouteConfiguration. */ export type RouteConfigurationUnion = RouteConfiguration | ForwardingConfiguration | RedirectConfiguration; /** * Base class for all types of Route. */ export interface RouteConfiguration { /** * Polymorphic Discriminator */ odatatype: "RouteConfiguration"; } /** * Routing rules to apply to an endpoint */ export interface RoutingRuleUpdateParameters { /** * Frontend endpoints associated with this rule */ frontendEndpoints?: SubResource[]; /** * Protocol schemes to match for this rule */ acceptedProtocols?: FrontDoorProtocol[]; /** * The route patterns of the rule. */ patternsToMatch?: string[]; /** * Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled'. Possible * values include: 'Enabled', 'Disabled' */ enabledState?: RoutingRuleEnabledState; /** * A reference to the routing configuration. */ routeConfiguration?: RouteConfigurationUnion; /** * A reference to a specific Rules Engine Configuration to apply to this route. */ rulesEngine?: SubResource; } /** * Caching settings for a caching-type route. To disable caching, do not provide a * cacheConfiguration object. */ export interface CacheConfiguration { /** * Treatment of URL query terms when forming the cache key. Possible values include: 'StripNone', * 'StripAll', 'StripOnly', 'StripAllExcept' */ queryParameterStripDirective?: FrontDoorQuery; /** * query parameters to include or exclude (comma separated). */ queryParameters?: string; /** * Whether to use dynamic compression for cached content. Possible values include: 'Enabled', * 'Disabled' */ dynamicCompression?: DynamicCompressionEnabled; /** * The duration for which the content needs to be cached. Allowed format is in ISO 8601 format * (http://en.wikipedia.org/wiki/ISO_8601#Durations). HTTP requires the value to be no more than * a year */ cacheDuration?: string; } /** * Describes Forwarding Route. */ export interface ForwardingConfiguration { /** * Polymorphic Discriminator */ odatatype: "#Microsoft.Azure.FrontDoor.Models.FrontdoorForwardingConfiguration"; /** * A custom path used to rewrite resource paths matched by this rule. Leave empty to use incoming * path. */ customForwardingPath?: string; /** * Protocol this rule will use when forwarding traffic to backends. Possible values include: * 'HttpOnly', 'HttpsOnly', 'MatchRequest' */ forwardingProtocol?: FrontDoorForwardingProtocol; /** * The caching configuration associated with this rule. */ cacheConfiguration?: CacheConfiguration; /** * A reference to the BackendPool which this rule routes to. */ backendPool?: SubResource; } /** * Describes Redirect Route. */ export interface RedirectConfiguration { /** * Polymorphic Discriminator */ odatatype: "#Microsoft.Azure.FrontDoor.Models.FrontdoorRedirectConfiguration"; /** * The redirect type the rule will use when redirecting traffic. Possible values include: * 'Moved', 'Found', 'TemporaryRedirect', 'PermanentRedirect' */ redirectType?: FrontDoorRedirectType; /** * The protocol of the destination to where the traffic is redirected. Possible values include: * 'HttpOnly', 'HttpsOnly', 'MatchRequest' */ redirectProtocol?: FrontDoorRedirectProtocol; /** * Host to redirect. Leave empty to use the incoming host as the destination host. */ customHost?: string; /** * The full path to redirect. Path cannot be empty and must start with /. Leave empty to use the * incoming path as destination path. */ customPath?: string; /** * Fragment to add to the redirect URL. Fragment is the part of the URL that comes after #. Do * not include the #. */ customFragment?: string; /** * The set of query strings to be placed in the redirect URL. Setting this value would replace * any existing query string; leave empty to preserve the incoming query string. Query string * must be in <key>=<value> format. The first ? and & will be added automatically so do not * include them in the front, but do separate multiple query strings with &. */ customQueryString?: string; } /** * Backend address of a frontDoor load balancer. */ export interface Backend { /** * Location of the backend (IP address or FQDN) */ address?: string; /** * The Alias of the Private Link resource. Populating this optional field indicates that this * backend is 'Private' */ privateLinkAlias?: string; /** * The Approval status for the connection to the Private Link. Possible values include: * 'Pending', 'Approved', 'Rejected', 'Disconnected', 'Timeout' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly privateEndpointStatus?: PrivateEndpointStatus; /** * A custom message to be included in the approval request to connect to the Private Link */ privateLinkApprovalMessage?: string; /** * The HTTP TCP port number. Must be between 1 and 65535. */ httpPort?: number; /** * The HTTPS TCP port number. Must be between 1 and 65535. */ httpsPort?: number; /** * Whether to enable use of this backend. Permitted values are 'Enabled' or 'Disabled'. Possible * values include: 'Enabled', 'Disabled' */ enabledState?: BackendEnabledState; /** * Priority to use for load balancing. Higher priorities will not be used for load balancing if * any lower priority backend is healthy. */ priority?: number; /** * Weight of this endpoint for load balancing purposes. */ weight?: number; /** * The value to use as the host header sent to the backend. If blank or unspecified, this * defaults to the incoming host. */ backendHostHeader?: string; } /** * Result of the request to list load balancing settings. It contains a list of load balancing * settings objects and a URL link to get the next set of results. */ export interface LoadBalancingSettingsListResult { /** * List of Backend Pools within a Front Door. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly value?: LoadBalancingSettingsModel[]; /** * URL to get the next set of LoadBalancingSettings objects if there are any. */ nextLink?: string; } /** * Round-Robin load balancing settings for a backend pool */ export interface LoadBalancingSettingsUpdateParameters { /** * The number of samples to consider for load balancing decisions */ sampleSize?: number; /** * The number of samples within the sample period that must succeed */ successfulSamplesRequired?: number; /** * The additional latency in milliseconds for probes to fall into the lowest latency bucket */ additionalLatencyMilliseconds?: number; } /** * Result of the request to list HealthProbeSettings. It contains a list of HealthProbeSettings * objects and a URL link to get the next set of results. */ export interface HealthProbeSettingsListResult { /** * List of HealthProbeSettings within a Front Door. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly value?: HealthProbeSettingsModel[]; /** * URL to get the next set of HealthProbeSettings objects if there are any. */ nextLink?: string; } /** * L7 health probe settings for a backend pool */ export interface HealthProbeSettingsUpdateParameters { /** * The path to use for the health probe. Default is / */ path?: string; /** * Protocol scheme to use for this probe. Possible values include: 'Http', 'Https' */ protocol?: FrontDoorProtocol; /** * The number of seconds between health probes. */ intervalInSeconds?: number; /** * Configures which HTTP method to use to probe the backends defined under backendPools. Possible * values include: 'GET', 'HEAD'. Default value: 'HEAD'. */ healthProbeMethod?: FrontDoorHealthProbeMethod; /** * Whether to enable health probes to be made against backends defined under backendPools. Health * probes can only be disabled if there is a single enabled backend in single enabled backend * pool. Possible values include: 'Enabled', 'Disabled' */ enabledState?: HealthProbeEnabled; } /** * A collection of backends that can be routed to. */ export interface BackendPoolUpdateParameters { /** * The set of backends for this pool */ backends?: Backend[]; /** * Load balancing settings for a backend pool */ loadBalancingSettings?: SubResource; /** * L7 health probe settings for a backend pool */ healthProbeSettings?: SubResource; } /** * Result of the request to list Backend Pools. It contains a list of Backend Pools objects and a * URL link to get the next set of results. */ export interface BackendPoolListResult { /** * List of Backend Pools within a Front Door. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly value?: BackendPool[]; /** * URL to get the next set of BackendPool objects if there are any. */ nextLink?: string; } /** * Defines the Web Application Firewall policy for each host (if applicable) */ export interface FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink { /** * Resource ID. */ id?: string; } /** * Frontend endpoint used in routing rule */ export interface FrontendEndpointUpdateParameters { /** * The host name of the frontendEndpoint. Must be a domain name. */ hostName?: string; /** * Whether to allow session affinity on this host. Valid options are 'Enabled' or 'Disabled'. * Possible values include: 'Enabled', 'Disabled' */ sessionAffinityEnabledState?: SessionAffinityEnabledState; /** * UNUSED. This field will be ignored. The TTL to use in seconds for session affinity, if * applicable. */ sessionAffinityTtlSeconds?: number; /** * Defines the Web Application Firewall policy for each host (if applicable) */ webApplicationFirewallPolicyLink?: FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink; } /** * An action that can manipulate an http header. */ export interface HeaderAction { /** * Which type of manipulation to apply to the header. Possible values include: 'Append', * 'Delete', 'Overwrite' */ headerActionType: HeaderActionType; /** * The name of the header this action will apply to. */ headerName: string; /** * The value to update the given header name with. This value is not used if the actionType is * Delete. */ value?: string; } /** * Define a match condition */ export interface RulesEngineMatchCondition { /** * Match Variable. Possible values include: 'IsMobile', 'RemoteAddr', 'RequestMethod', * 'QueryString', 'PostArgs', 'RequestUri', 'RequestPath', 'RequestFilename', * 'RequestFilenameExtension', 'RequestHeader', 'RequestBody', 'RequestScheme' */ rulesEngineMatchVariable: RulesEngineMatchVariable; /** * Name of selector in RequestHeader or RequestBody to be matched */ selector?: string; /** * Describes operator to apply to the match condition. Possible values include: 'Any', 'IPMatch', * 'GeoMatch', 'Equal', 'Contains', 'LessThan', 'GreaterThan', 'LessThanOrEqual', * 'GreaterThanOrEqual', 'BeginsWith', 'EndsWith' */ rulesEngineOperator: RulesEngineOperator; /** * Describes if this is negate condition or not */ negateCondition?: boolean; /** * Match values to match against. The operator will apply to each value in here with OR * semantics. If any of them match the variable with the given operator this match condition is * considered a match. */ rulesEngineMatchValue: string[]; /** * List of transforms */ transforms?: Transform[]; } /** * One or more actions that will execute, modifying the request and/or response. */ export interface RulesEngineAction { /** * A list of header actions to apply from the request from AFD to the origin. */ requestHeaderActions?: HeaderAction[]; /** * A list of header actions to apply from the response from AFD to the client. */ responseHeaderActions?: HeaderAction[]; /** * Override the route configuration. */ routeConfigurationOverride?: RouteConfigurationUnion; } /** * Contains a list of match conditions, and an action on how to modify the request/response. If * multiple rules match, the actions from one rule that conflict with a previous rule overwrite for * a singular action, or append in the case of headers manipulation. */ export interface RulesEngineRule { /** * A name to refer to this specific rule. */ name: string; /** * A priority assigned to this rule. */ priority: number; /** * Actions to perform on the request and response if all of the match conditions are met. */ action: RulesEngineAction; /** * A list of match conditions that must meet in order for the actions of this rule to run. Having * no match conditions means the actions will always run. */ matchConditions?: RulesEngineMatchCondition[]; /** * If this rule is a match should the rules engine continue running the remaining rules or stop. * If not present, defaults to Continue. Possible values include: 'Continue', 'Stop' */ matchProcessingBehavior?: MatchProcessingBehavior; } /** * Rules Engine Configuration to apply to a Routing Rule. */ export interface RulesEngineUpdateParameters { /** * A list of rules that define a particular Rules Engine Configuration. */ rules?: RulesEngineRule[]; } /** * Input of the custom domain to be validated for DNS mapping. */ export interface ValidateCustomDomainInput { /** * The host name of the custom domain. Must be a domain name. */ hostName: string; } /** * Output of custom domain validation. */ export interface ValidateCustomDomainOutput { /** * Indicates whether the custom domain is valid or not. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly customDomainValidated?: boolean; /** * The reason why the custom domain is not valid. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly reason?: string; /** * Error message describing why the custom domain is not valid. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; } /** * Input of CheckNameAvailability API. */ export interface CheckNameAvailabilityInput { /** * The resource name to validate. */ name: string; /** * The type of the resource whose name is to be validated. Possible values include: * 'Microsoft.Network/frontDoors', 'Microsoft.Network/frontDoors/frontendEndpoints' */ type: ResourceType; } /** * Output of check name availability API. */ export interface CheckNameAvailabilityOutput { /** * Indicates whether the name is available. Possible values include: 'Available', 'Unavailable' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nameAvailability?: Availability; /** * The reason why the name is not available. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly reason?: string; /** * The detailed error message describing why the name is not available. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; } /** * Defines top-level WebApplicationFirewallPolicy configuration settings. */ export interface PolicySettings { /** * Describes if the policy is in enabled or disabled state. Defaults to Enabled if not specified. * Possible values include: 'Disabled', 'Enabled' */ enabledState?: PolicyEnabledState; /** * Describes if it is in detection mode or prevention mode at policy level. Possible values * include: 'Prevention', 'Detection' */ mode?: PolicyMode; /** * If action type is redirect, this field represents redirect URL for the client. */ redirectUrl?: string; /** * If the action type is block, customer can override the response status code. */ customBlockResponseStatusCode?: number; /** * If the action type is block, customer can override the response body. The body must be * specified in base64 encoding. */ customBlockResponseBody?: string; } /** * Define a match condition. */ export interface MatchCondition { /** * Request variable to compare with. Possible values include: 'RemoteAddr', 'RequestMethod', * 'QueryString', 'PostArgs', 'RequestUri', 'RequestHeader', 'RequestBody', 'Cookies', * 'SocketAddr' */ matchVariable: MatchVariable; /** * Match against a specific key from the QueryString, PostArgs, RequestHeader or Cookies * variables. Default is null. */ selector?: string; /** * Comparison type to use for matching with the variable value. Possible values include: 'Any', * 'IPMatch', 'GeoMatch', 'Equal', 'Contains', 'LessThan', 'GreaterThan', 'LessThanOrEqual', * 'GreaterThanOrEqual', 'BeginsWith', 'EndsWith', 'RegEx' */ operator: Operator; /** * Describes if the result of this condition should be negated. */ negateCondition?: boolean; /** * List of possible match values. */ matchValue: string[]; /** * List of transforms. */ transforms?: TransformType[]; } /** * Defines contents of a web application rule */ export interface CustomRule { /** * Describes the name of the rule. */ name?: string; /** * Describes priority of the rule. Rules with a lower value will be evaluated before rules with a * higher value. */ priority: number; /** * Describes if the custom rule is in enabled or disabled state. Defaults to Enabled if not * specified. Possible values include: 'Disabled', 'Enabled' */ enabledState?: CustomRuleEnabledState; /** * Describes type of rule. Possible values include: 'MatchRule', 'RateLimitRule' */ ruleType: RuleType; /** * Time window for resetting the rate limit count. Default is 1 minute. */ rateLimitDurationInMinutes?: number; /** * Number of allowed requests per client within the time window. */ rateLimitThreshold?: number; /** * List of match conditions. */ matchConditions: MatchCondition[]; /** * Describes what action to be applied when rule matches. Possible values include: 'Allow', * 'Block', 'Log', 'Redirect' */ action: ActionType; } /** * Defines contents of custom rules */ export interface CustomRuleList { /** * List of rules */ rules?: CustomRule[]; } /** * Exclude variables from managed rule evaluation. */ export interface ManagedRuleExclusion { /** * The variable type to be excluded. Possible values include: 'RequestHeaderNames', * 'RequestCookieNames', 'QueryStringArgNames', 'RequestBodyPostArgNames' */ matchVariable: ManagedRuleExclusionMatchVariable; /** * Comparison operator to apply to the selector when specifying which elements in the collection * this exclusion applies to. Possible values include: 'Equals', 'Contains', 'StartsWith', * 'EndsWith', 'EqualsAny' */ selectorMatchOperator: ManagedRuleExclusionSelectorMatchOperator; /** * Selector value for which elements in the collection this exclusion applies to. */ selector: string; } /** * Defines a managed rule group override setting. */ export interface ManagedRuleOverride { /** * Identifier for the managed rule. */ ruleId: string; /** * Describes if the managed rule is in enabled or disabled state. Defaults to Disabled if not * specified. Possible values include: 'Disabled', 'Enabled' */ enabledState?: ManagedRuleEnabledState; /** * Describes the override action to be applied when rule matches. Possible values include: * 'Allow', 'Block', 'Log', 'Redirect' */ action?: ActionType; /** * Describes the exclusions that are applied to this specific rule. */ exclusions?: ManagedRuleExclusion[]; } /** * Defines a managed rule group override setting. */ export interface ManagedRuleGroupOverride { /** * Describes the managed rule group to override. */ ruleGroupName: string; /** * Describes the exclusions that are applied to all rules in the group. */ exclusions?: ManagedRuleExclusion[]; /** * List of rules that will be disabled. If none specified, all rules in the group will be * disabled. */ rules?: ManagedRuleOverride[]; } /** * Defines a managed rule set. */ export interface ManagedRuleSet { /** * Defines the rule set type to use. */ ruleSetType: string; /** * Defines the version of the rule set to use. */ ruleSetVersion: string; /** * Describes the exclusions that are applied to all rules in the set. */ exclusions?: ManagedRuleExclusion[]; /** * Defines the rule group overrides to apply to the rule set. */ ruleGroupOverrides?: ManagedRuleGroupOverride[]; } /** * Defines the list of managed rule sets for the policy. */ export interface ManagedRuleSetList { /** * List of rule sets. */ managedRuleSets?: ManagedRuleSet[]; } /** * Defines the Resource ID for a Frontend Endpoint. */ export interface FrontendEndpointLink { /** * Resource ID. */ id?: string; } /** * Defines web application firewall policy. */ export interface WebApplicationFirewallPolicy extends Resource { /** * Describes settings for the policy. */ policySettings?: PolicySettings; /** * Describes custom rules inside the policy. */ customRules?: CustomRuleList; /** * Describes managed rules inside the policy. */ managedRules?: ManagedRuleSetList; /** * Describes Frontend Endpoints associated with this Web Application Firewall policy. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly frontendEndpointLinks?: FrontendEndpointLink[]; /** * Provisioning state of the policy. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: string; /** * Resource status of the policy. Possible values include: 'Creating', 'Enabling', 'Enabled', * 'Disabling', 'Disabled', 'Deleting' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly resourceState?: PolicyResourceState; /** * Gets a unique read-only string that changes whenever the resource is updated. */ etag?: string; } /** * Describes a managed rule definition. */ export interface ManagedRuleDefinition { /** * Identifier for the managed rule. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly ruleId?: string; /** * Describes the default state for the managed rule. Possible values include: 'Disabled', * 'Enabled' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly defaultState?: ManagedRuleEnabledState; /** * Describes the default action to be applied when the managed rule matches. Possible values * include: 'Allow', 'Block', 'Log', 'Redirect' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly defaultAction?: ActionType; /** * Describes the functionality of the managed rule. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; } /** * Describes a managed rule group. */ export interface ManagedRuleGroupDefinition { /** * Name of the managed rule group. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly ruleGroupName?: string; /** * Description of the managed rule group. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; /** * List of rules within the managed rule group. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly rules?: ManagedRuleDefinition[]; } /** * Describes the a managed rule set definition. */ export interface ManagedRuleSetDefinition extends Resource { /** * Provisioning state of the managed rule set. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: string; /** * Id of the managed rule set. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly ruleSetId?: string; /** * Type of the managed rule set. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly ruleSetType?: string; /** * Version of the managed rule set type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly ruleSetVersion?: string; /** * Rule groups of the managed rule set. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly ruleGroups?: ManagedRuleGroupDefinition[]; } /** * Optional Parameters. */ export interface ReportsGetLatencyScorecardsOptionalParams extends msRest.RequestOptionsBase { /** * The end DateTime of the Latency Scorecard in UTC */ endDateTimeUTC?: string; /** * The country associated with the Latency Scorecard. Values are country ISO codes as specified * here- https://www.iso.org/iso-3166-country-codes.html */ country?: string; } /** * Optional Parameters. */ export interface ReportsGetTimeseriesOptionalParams extends msRest.RequestOptionsBase { /** * The specific endpoint */ endpoint?: string; /** * The country associated with the Timeseries. Values are country ISO codes as specified here- * https://www.iso.org/iso-3166-country-codes.html */ country?: string; } /** * An interface representing FrontDoorManagementClientOptions. */ export interface FrontDoorManagementClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * Defines a list of Profiles. It contains a list of Profile objects and a URL link to get the next * set of results. * @extends Array<Profile> */ export interface ProfileList extends Array<Profile> { /** * URL to get the next set of Profile objects if there are any. */ nextLink?: string; } /** * @interface * Defines a list of preconfigured endpoints. * @extends Array<PreconfiguredEndpoint> */ export interface PreconfiguredEndpointList extends Array<PreconfiguredEndpoint> { /** * URL to get the next set of PreconfiguredEndpoints if there are any. */ nextLink?: string; } /** * @interface * Defines a list of Experiments. It contains a list of Experiment objects and a URL link to get * the next set of results. * @extends Array<Experiment> */ export interface ExperimentList extends Array<Experiment> { /** * URL to get the next set of Experiment objects if there are any. */ nextLink?: string; } /** * @interface * Result of the request to list Front Doors. It contains a list of Front Door objects and a URL * link to get the next set of results. * @extends Array<FrontDoor> */ export interface FrontDoorListResult extends Array<FrontDoor> { /** * URL to get the next set of Front Door objects if there are any. */ nextLink?: string; } /** * @interface * Result of the request to list frontend endpoints. It contains a list of Frontend endpoint * objects and a URL link to get the next set of results. * @extends Array<FrontendEndpoint> */ export interface FrontendEndpointsListResult extends Array<FrontendEndpoint> { /** * URL to get the next set of frontend endpoints if there are any. */ nextLink?: string; } /** * @interface * Result of the request to list Rules Engine Configurations. It contains a list of RulesEngine * objects and a URL link to get the next set of results. * @extends Array<RulesEngine> */ export interface RulesEngineListResult extends Array<RulesEngine> { /** * URL to get the next set of RulesEngine objects if there are any. */ nextLink?: string; } /** * @interface * Defines a list of WebApplicationFirewallPolicies. It contains a list of * WebApplicationFirewallPolicy objects and a URL link to get the next set of results. * @extends Array<WebApplicationFirewallPolicy> */ export interface WebApplicationFirewallPolicyList extends Array<WebApplicationFirewallPolicy> { /** * URL to get the next set of WebApplicationFirewallPolicy objects if there are any. */ nextLink?: string; } /** * @interface * List of managed rule set definitions available for use in a policy. * @extends Array<ManagedRuleSetDefinition> */ export interface ManagedRuleSetDefinitionList extends Array<ManagedRuleSetDefinition> { /** * URL to retrieve next set of managed rule set definitions. */ nextLink?: string; } /** * Defines values for NetworkOperationStatus. * Possible values include: 'InProgress', 'Succeeded', 'Failed' * @readonly * @enum {string} */ export type NetworkOperationStatus = 'InProgress' | 'Succeeded' | 'Failed'; /** * Defines values for NetworkExperimentResourceState. * Possible values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', 'Disabled', 'Deleting' * @readonly * @enum {string} */ export type NetworkExperimentResourceState = 'Creating' | 'Enabling' | 'Enabled' | 'Disabling' | 'Disabled' | 'Deleting'; /** * Defines values for State. * Possible values include: 'Enabled', 'Disabled' * @readonly * @enum {string} */ export type State = 'Enabled' | 'Disabled'; /** * Defines values for AggregationInterval. * Possible values include: 'Hourly', 'Daily' * @readonly * @enum {string} */ export type AggregationInterval = 'Hourly' | 'Daily'; /** * Defines values for TimeseriesType. * Possible values include: 'MeasurementCounts', 'LatencyP50', 'LatencyP75', 'LatencyP95' * @readonly * @enum {string} */ export type TimeseriesType = 'MeasurementCounts' | 'LatencyP50' | 'LatencyP75' | 'LatencyP95'; /** * Defines values for EndpointType. * Possible values include: 'AFD', 'AzureRegion', 'CDN', 'ATM' * @readonly * @enum {string} */ export type EndpointType = 'AFD' | 'AzureRegion' | 'CDN' | 'ATM'; /** * Defines values for FrontDoorResourceState. * Possible values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', 'Disabled', 'Deleting' * @readonly * @enum {string} */ export type FrontDoorResourceState = 'Creating' | 'Enabling' | 'Enabled' | 'Disabling' | 'Disabled' | 'Deleting'; /** * Defines values for CustomHttpsProvisioningState. * Possible values include: 'Enabling', 'Enabled', 'Disabling', 'Disabled', 'Failed' * @readonly * @enum {string} */ export type CustomHttpsProvisioningState = 'Enabling' | 'Enabled' | 'Disabling' | 'Disabled' | 'Failed'; /** * Defines values for CustomHttpsProvisioningSubstate. * Possible values include: 'SubmittingDomainControlValidationRequest', * 'PendingDomainControlValidationREquestApproval', 'DomainControlValidationRequestApproved', * 'DomainControlValidationRequestRejected', 'DomainControlValidationRequestTimedOut', * 'IssuingCertificate', 'DeployingCertificate', 'CertificateDeployed', 'DeletingCertificate', * 'CertificateDeleted' * @readonly * @enum {string} */ export type CustomHttpsProvisioningSubstate = 'SubmittingDomainControlValidationRequest' | 'PendingDomainControlValidationREquestApproval' | 'DomainControlValidationRequestApproved' | 'DomainControlValidationRequestRejected' | 'DomainControlValidationRequestTimedOut' | 'IssuingCertificate' | 'DeployingCertificate' | 'CertificateDeployed' | 'DeletingCertificate' | 'CertificateDeleted'; /** * Defines values for FrontDoorCertificateSource. * Possible values include: 'AzureKeyVault', 'FrontDoor' * @readonly * @enum {string} */ export type FrontDoorCertificateSource = 'AzureKeyVault' | 'FrontDoor'; /** * Defines values for MinimumTLSVersion. * Possible values include: '1.0', '1.2' * @readonly * @enum {string} */ export type MinimumTLSVersion = '1.0' | '1.2'; /** * Defines values for FrontDoorCertificateType. * Possible values include: 'Dedicated' * @readonly * @enum {string} */ export type FrontDoorCertificateType = 'Dedicated'; /** * Defines values for EnforceCertificateNameCheckEnabledState. * Possible values include: 'Enabled', 'Disabled' * @readonly * @enum {string} */ export type EnforceCertificateNameCheckEnabledState = 'Enabled' | 'Disabled'; /** * Defines values for FrontDoorEnabledState. * Possible values include: 'Enabled', 'Disabled' * @readonly * @enum {string} */ export type FrontDoorEnabledState = 'Enabled' | 'Disabled'; /** * Defines values for FrontDoorProtocol. * Possible values include: 'Http', 'Https' * @readonly * @enum {string} */ export type FrontDoorProtocol = 'Http' | 'Https'; /** * Defines values for RoutingRuleEnabledState. * Possible values include: 'Enabled', 'Disabled' * @readonly * @enum {string} */ export type RoutingRuleEnabledState = 'Enabled' | 'Disabled'; /** * Defines values for FrontDoorForwardingProtocol. * Possible values include: 'HttpOnly', 'HttpsOnly', 'MatchRequest' * @readonly * @enum {string} */ export type FrontDoorForwardingProtocol = 'HttpOnly' | 'HttpsOnly' | 'MatchRequest'; /** * Defines values for FrontDoorQuery. * Possible values include: 'StripNone', 'StripAll', 'StripOnly', 'StripAllExcept' * @readonly * @enum {string} */ export type FrontDoorQuery = 'StripNone' | 'StripAll' | 'StripOnly' | 'StripAllExcept'; /** * Defines values for DynamicCompressionEnabled. * Possible values include: 'Enabled', 'Disabled' * @readonly * @enum {string} */ export type DynamicCompressionEnabled = 'Enabled' | 'Disabled'; /** * Defines values for FrontDoorRedirectType. * Possible values include: 'Moved', 'Found', 'TemporaryRedirect', 'PermanentRedirect' * @readonly * @enum {string} */ export type FrontDoorRedirectType = 'Moved' | 'Found' | 'TemporaryRedirect' | 'PermanentRedirect'; /** * Defines values for FrontDoorRedirectProtocol. * Possible values include: 'HttpOnly', 'HttpsOnly', 'MatchRequest' * @readonly * @enum {string} */ export type FrontDoorRedirectProtocol = 'HttpOnly' | 'HttpsOnly' | 'MatchRequest'; /** * Defines values for PrivateEndpointStatus. * Possible values include: 'Pending', 'Approved', 'Rejected', 'Disconnected', 'Timeout' * @readonly * @enum {string} */ export type PrivateEndpointStatus = 'Pending' | 'Approved' | 'Rejected' | 'Disconnected' | 'Timeout'; /** * Defines values for BackendEnabledState. * Possible values include: 'Enabled', 'Disabled' * @readonly * @enum {string} */ export type BackendEnabledState = 'Enabled' | 'Disabled'; /** * Defines values for FrontDoorHealthProbeMethod. * Possible values include: 'GET', 'HEAD' * @readonly * @enum {string} */ export type FrontDoorHealthProbeMethod = 'GET' | 'HEAD'; /** * Defines values for HealthProbeEnabled. * Possible values include: 'Enabled', 'Disabled' * @readonly * @enum {string} */ export type HealthProbeEnabled = 'Enabled' | 'Disabled'; /** * Defines values for SessionAffinityEnabledState. * Possible values include: 'Enabled', 'Disabled' * @readonly * @enum {string} */ export type SessionAffinityEnabledState = 'Enabled' | 'Disabled'; /** * Defines values for HeaderActionType. * Possible values include: 'Append', 'Delete', 'Overwrite' * @readonly * @enum {string} */ export type HeaderActionType = 'Append' | 'Delete' | 'Overwrite'; /** * Defines values for RulesEngineMatchVariable. * Possible values include: 'IsMobile', 'RemoteAddr', 'RequestMethod', 'QueryString', 'PostArgs', * 'RequestUri', 'RequestPath', 'RequestFilename', 'RequestFilenameExtension', 'RequestHeader', * 'RequestBody', 'RequestScheme' * @readonly * @enum {string} */ export type RulesEngineMatchVariable = 'IsMobile' | 'RemoteAddr' | 'RequestMethod' | 'QueryString' | 'PostArgs' | 'RequestUri' | 'RequestPath' | 'RequestFilename' | 'RequestFilenameExtension' | 'RequestHeader' | 'RequestBody' | 'RequestScheme'; /** * Defines values for RulesEngineOperator. * Possible values include: 'Any', 'IPMatch', 'GeoMatch', 'Equal', 'Contains', 'LessThan', * 'GreaterThan', 'LessThanOrEqual', 'GreaterThanOrEqual', 'BeginsWith', 'EndsWith' * @readonly * @enum {string} */ export type RulesEngineOperator = 'Any' | 'IPMatch' | 'GeoMatch' | 'Equal' | 'Contains' | 'LessThan' | 'GreaterThan' | 'LessThanOrEqual' | 'GreaterThanOrEqual' | 'BeginsWith' | 'EndsWith'; /** * Defines values for Transform. * Possible values include: 'Lowercase', 'Uppercase', 'Trim', 'UrlDecode', 'UrlEncode', * 'RemoveNulls' * @readonly * @enum {string} */ export type Transform = 'Lowercase' | 'Uppercase' | 'Trim' | 'UrlDecode' | 'UrlEncode' | 'RemoveNulls'; /** * Defines values for MatchProcessingBehavior. * Possible values include: 'Continue', 'Stop' * @readonly * @enum {string} */ export type MatchProcessingBehavior = 'Continue' | 'Stop'; /** * Defines values for ResourceType. * Possible values include: 'Microsoft.Network/frontDoors', * 'Microsoft.Network/frontDoors/frontendEndpoints' * @readonly * @enum {string} */ export type ResourceType = 'Microsoft.Network/frontDoors' | 'Microsoft.Network/frontDoors/frontendEndpoints'; /** * Defines values for Availability. * Possible values include: 'Available', 'Unavailable' * @readonly * @enum {string} */ export type Availability = 'Available' | 'Unavailable'; /** * Defines values for PolicyEnabledState. * Possible values include: 'Disabled', 'Enabled' * @readonly * @enum {string} */ export type PolicyEnabledState = 'Disabled' | 'Enabled'; /** * Defines values for PolicyMode. * Possible values include: 'Prevention', 'Detection' * @readonly * @enum {string} */ export type PolicyMode = 'Prevention' | 'Detection'; /** * Defines values for CustomRuleEnabledState. * Possible values include: 'Disabled', 'Enabled' * @readonly * @enum {string} */ export type CustomRuleEnabledState = 'Disabled' | 'Enabled'; /** * Defines values for RuleType. * Possible values include: 'MatchRule', 'RateLimitRule' * @readonly * @enum {string} */ export type RuleType = 'MatchRule' | 'RateLimitRule'; /** * Defines values for MatchVariable. * Possible values include: 'RemoteAddr', 'RequestMethod', 'QueryString', 'PostArgs', 'RequestUri', * 'RequestHeader', 'RequestBody', 'Cookies', 'SocketAddr' * @readonly * @enum {string} */ export type MatchVariable = 'RemoteAddr' | 'RequestMethod' | 'QueryString' | 'PostArgs' | 'RequestUri' | 'RequestHeader' | 'RequestBody' | 'Cookies' | 'SocketAddr'; /** * Defines values for Operator. * Possible values include: 'Any', 'IPMatch', 'GeoMatch', 'Equal', 'Contains', 'LessThan', * 'GreaterThan', 'LessThanOrEqual', 'GreaterThanOrEqual', 'BeginsWith', 'EndsWith', 'RegEx' * @readonly * @enum {string} */ export type Operator = 'Any' | 'IPMatch' | 'GeoMatch' | 'Equal' | 'Contains' | 'LessThan' | 'GreaterThan' | 'LessThanOrEqual' | 'GreaterThanOrEqual' | 'BeginsWith' | 'EndsWith' | 'RegEx'; /** * Defines values for TransformType. * Possible values include: 'Lowercase', 'Uppercase', 'Trim', 'UrlDecode', 'UrlEncode', * 'RemoveNulls' * @readonly * @enum {string} */ export type TransformType = 'Lowercase' | 'Uppercase' | 'Trim' | 'UrlDecode' | 'UrlEncode' | 'RemoveNulls'; /** * Defines values for ActionType. * Possible values include: 'Allow', 'Block', 'Log', 'Redirect' * @readonly * @enum {string} */ export type ActionType = 'Allow' | 'Block' | 'Log' | 'Redirect'; /** * Defines values for ManagedRuleExclusionMatchVariable. * Possible values include: 'RequestHeaderNames', 'RequestCookieNames', 'QueryStringArgNames', * 'RequestBodyPostArgNames' * @readonly * @enum {string} */ export type ManagedRuleExclusionMatchVariable = 'RequestHeaderNames' | 'RequestCookieNames' | 'QueryStringArgNames' | 'RequestBodyPostArgNames'; /** * Defines values for ManagedRuleExclusionSelectorMatchOperator. * Possible values include: 'Equals', 'Contains', 'StartsWith', 'EndsWith', 'EqualsAny' * @readonly * @enum {string} */ export type ManagedRuleExclusionSelectorMatchOperator = 'Equals' | 'Contains' | 'StartsWith' | 'EndsWith' | 'EqualsAny'; /** * Defines values for ManagedRuleEnabledState. * Possible values include: 'Disabled', 'Enabled' * @readonly * @enum {string} */ export type ManagedRuleEnabledState = 'Disabled' | 'Enabled'; /** * Defines values for PolicyResourceState. * Possible values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', 'Disabled', 'Deleting' * @readonly * @enum {string} */ export type PolicyResourceState = 'Creating' | 'Enabling' | 'Enabled' | 'Disabling' | 'Disabled' | 'Deleting'; /** * Defines values for LatencyScorecardAggregationInterval. * Possible values include: 'Daily', 'Weekly', 'Monthly' * @readonly * @enum {string} */ export type LatencyScorecardAggregationInterval = 'Daily' | 'Weekly' | 'Monthly'; /** * Defines values for TimeseriesAggregationInterval. * Possible values include: 'Hourly', 'Daily' * @readonly * @enum {string} */ export type TimeseriesAggregationInterval = 'Hourly' | 'Daily'; /** * Contains response data for the list operation. */ export type NetworkExperimentProfilesListResponse = ProfileList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProfileList; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type NetworkExperimentProfilesListByResourceGroupResponse = ProfileList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProfileList; }; }; /** * Contains response data for the get operation. */ export type NetworkExperimentProfilesGetResponse = Profile & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Profile; }; }; /** * Contains response data for the createOrUpdate operation. */ export type NetworkExperimentProfilesCreateOrUpdateResponse = Profile & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Profile; }; }; /** * Contains response data for the update operation. */ export type NetworkExperimentProfilesUpdateResponse = Profile & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Profile; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type NetworkExperimentProfilesBeginCreateOrUpdateResponse = Profile & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Profile; }; }; /** * Contains response data for the beginUpdate operation. */ export type NetworkExperimentProfilesBeginUpdateResponse = Profile & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Profile; }; }; /** * Contains response data for the listNext operation. */ export type NetworkExperimentProfilesListNextResponse = ProfileList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProfileList; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type NetworkExperimentProfilesListByResourceGroupNextResponse = ProfileList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProfileList; }; }; /** * Contains response data for the list operation. */ export type PreconfiguredEndpointsListResponse = PreconfiguredEndpointList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PreconfiguredEndpointList; }; }; /** * Contains response data for the listNext operation. */ export type PreconfiguredEndpointsListNextResponse = PreconfiguredEndpointList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PreconfiguredEndpointList; }; }; /** * Contains response data for the listByProfile operation. */ export type ExperimentsListByProfileResponse = ExperimentList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ExperimentList; }; }; /** * Contains response data for the get operation. */ export type ExperimentsGetResponse = Experiment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Experiment; }; }; /** * Contains response data for the createOrUpdate operation. */ export type ExperimentsCreateOrUpdateResponse = Experiment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Experiment; }; }; /** * Contains response data for the update operation. */ export type ExperimentsUpdateResponse = Experiment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Experiment; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type ExperimentsBeginCreateOrUpdateResponse = Experiment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Experiment; }; }; /** * Contains response data for the beginUpdate operation. */ export type ExperimentsBeginUpdateResponse = Experiment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Experiment; }; }; /** * Contains response data for the listByProfileNext operation. */ export type ExperimentsListByProfileNextResponse = ExperimentList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ExperimentList; }; }; /** * Contains response data for the getLatencyScorecards operation. */ export type ReportsGetLatencyScorecardsResponse = LatencyScorecard & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: LatencyScorecard; }; }; /** * Contains response data for the getTimeseries operation. */ export type ReportsGetTimeseriesResponse = Timeseries & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Timeseries; }; }; /** * Contains response data for the checkFrontDoorNameAvailability operation. */ export type CheckFrontDoorNameAvailabilityResponse = CheckNameAvailabilityOutput & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CheckNameAvailabilityOutput; }; }; /** * Contains response data for the checkFrontDoorNameAvailabilityWithSubscription operation. */ export type CheckFrontDoorNameAvailabilityWithSubscriptionResponse = CheckNameAvailabilityOutput & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CheckNameAvailabilityOutput; }; }; /** * Contains response data for the list operation. */ export type FrontDoorsListResponse = FrontDoorListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FrontDoorListResult; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type FrontDoorsListByResourceGroupResponse = FrontDoorListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FrontDoorListResult; }; }; /** * Contains response data for the get operation. */ export type FrontDoorsGetResponse = FrontDoor & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FrontDoor; }; }; /** * Contains response data for the createOrUpdate operation. */ export type FrontDoorsCreateOrUpdateResponse = FrontDoor & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FrontDoor; }; }; /** * Contains response data for the validateCustomDomain operation. */ export type FrontDoorsValidateCustomDomainResponse = ValidateCustomDomainOutput & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ValidateCustomDomainOutput; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type FrontDoorsBeginCreateOrUpdateResponse = FrontDoor & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FrontDoor; }; }; /** * Contains response data for the listNext operation. */ export type FrontDoorsListNextResponse = FrontDoorListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FrontDoorListResult; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type FrontDoorsListByResourceGroupNextResponse = FrontDoorListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FrontDoorListResult; }; }; /** * Contains response data for the listByFrontDoor operation. */ export type FrontendEndpointsListByFrontDoorResponse = FrontendEndpointsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FrontendEndpointsListResult; }; }; /** * Contains response data for the get operation. */ export type FrontendEndpointsGetResponse = FrontendEndpoint & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FrontendEndpoint; }; }; /** * Contains response data for the listByFrontDoorNext operation. */ export type FrontendEndpointsListByFrontDoorNextResponse = FrontendEndpointsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FrontendEndpointsListResult; }; }; /** * Contains response data for the listByFrontDoor operation. */ export type RulesEnginesListByFrontDoorResponse = RulesEngineListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RulesEngineListResult; }; }; /** * Contains response data for the get operation. */ export type RulesEnginesGetResponse = RulesEngine & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RulesEngine; }; }; /** * Contains response data for the createOrUpdate operation. */ export type RulesEnginesCreateOrUpdateResponse = RulesEngine & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RulesEngine; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type RulesEnginesBeginCreateOrUpdateResponse = RulesEngine & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RulesEngine; }; }; /** * Contains response data for the listByFrontDoorNext operation. */ export type RulesEnginesListByFrontDoorNextResponse = RulesEngineListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RulesEngineListResult; }; }; /** * Contains response data for the list operation. */ export type PoliciesListResponse = WebApplicationFirewallPolicyList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WebApplicationFirewallPolicyList; }; }; /** * Contains response data for the get operation. */ export type PoliciesGetResponse = WebApplicationFirewallPolicy & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WebApplicationFirewallPolicy; }; }; /** * Contains response data for the createOrUpdate operation. */ export type PoliciesCreateOrUpdateResponse = WebApplicationFirewallPolicy & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WebApplicationFirewallPolicy; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type PoliciesBeginCreateOrUpdateResponse = WebApplicationFirewallPolicy & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WebApplicationFirewallPolicy; }; }; /** * Contains response data for the listNext operation. */ export type PoliciesListNextResponse = WebApplicationFirewallPolicyList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WebApplicationFirewallPolicyList; }; }; /** * Contains response data for the list operation. */ export type ManagedRuleSetsListResponse = ManagedRuleSetDefinitionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ManagedRuleSetDefinitionList; }; }; /** * Contains response data for the listNext operation. */ export type ManagedRuleSetsListNextResponse = ManagedRuleSetDefinitionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ManagedRuleSetDefinitionList; }; };
the_stack
import http from "http"; import type { AddressInfo } from "net"; import test, { Test } from "tape-promise/tape"; import { v4 as uuidv4 } from "uuid"; import express from "express"; import bodyParser from "body-parser"; import { Configuration, DefaultApi as BesuApi, IPluginHtlcEthBesuErc20Options, PluginFactoryHtlcEthBesuErc20, NewContractRequest, InitializeRequest, RefundRequest, WithdrawRequest, GetStatusRequest, GetSingleStatusRequest, } from "@hyperledger/cactus-plugin-htlc-eth-besu-erc20"; import { EthContractInvocationType, PluginFactoryLedgerConnector, PluginLedgerConnectorBesu, Web3SigningCredential, Web3SigningCredentialType, } from "@hyperledger/cactus-plugin-ledger-connector-besu"; import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; import { LogLevelDesc, IListenOptions, Servers, } from "@hyperledger/cactus-common"; import { PluginRegistry } from "@hyperledger/cactus-core"; import { PluginImportType } from "@hyperledger/cactus-core-api"; import { BesuTestLedger, pruneDockerAllIfGithubAction, } from "@hyperledger/cactus-test-tooling"; import TestTokenJSON from "../../../../solidity/token-erc20-contract/Test_Token.json"; import DemoHelperJSON from "../../../../solidity/token-erc20-contract/DemoHelpers.json"; import HashTimeLockJSON from "../../../../../../../cactus-plugin-htlc-eth-besu-erc20/src/main/solidity/contracts/HashedTimeLockContract.json"; import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core"; import { PluginHtlcEthBesuErc20 } from "@hyperledger/cactus-plugin-htlc-eth-besu-erc20"; const connectorId = uuidv4(); const logLevel: LogLevelDesc = "INFO"; const expiration = 2147483648; const secret = "0x3853485acd2bfc3c632026ee365279743af107a30492e3ceaa7aefc30c2a048a"; const estimatedGas = 6721975; const receiver = "0x627306090abaB3A6e1400e9345bC60c78a8BEf57"; const hashLock = "0x3c335ba7f06a8b01d0596589f73c19069e21c81e5013b91f408165d1bf623d32"; const firstHighNetWorthAccount = "0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1"; const privateKey = "0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d"; const web3SigningCredential: Web3SigningCredential = { ethAccount: firstHighNetWorthAccount, secret: privateKey, type: Web3SigningCredentialType.PrivateKeyHex, } as Web3SigningCredential; const testCase = "Test cactus-plugin-htlc-eth-besu-erc20 openapi validation"; test("BEFORE " + testCase, async (t: Test) => { const pruning = pruneDockerAllIfGithubAction({ logLevel }); await t.doesNotReject(pruning, "Pruning did not throw OK"); t.end(); }); test(testCase, async (t: Test) => { const timeout = (ms: number) => { return new Promise((resolve) => setTimeout(resolve, ms)); }; t.comment("Starting Besu Test Ledger"); const besuTestLedger = new BesuTestLedger({ logLevel }); test.onFailure(async () => { await besuTestLedger.stop(); await besuTestLedger.destroy(); }); test.onFinish(async () => { await besuTestLedger.stop(); await besuTestLedger.destroy(); }); await besuTestLedger.start(); const rpcApiHttpHost = await besuTestLedger.getRpcApiHttpHost(); const rpcApiWsHost = await besuTestLedger.getRpcApiWsHost(); const keychainId = uuidv4(); const keychainPlugin = new PluginKeychainMemory({ instanceId: uuidv4(), keychainId, // pre-provision keychain with mock backend holding the private key of the // test account that we'll reference while sending requests with the // signing credential pointing to this keychain entry. backend: new Map([ [TestTokenJSON.contractName, JSON.stringify(TestTokenJSON)], ]), logLevel, }); keychainPlugin.set( DemoHelperJSON.contractName, JSON.stringify(DemoHelperJSON), ); keychainPlugin.set( HashTimeLockJSON.contractName, JSON.stringify(HashTimeLockJSON), ); const factory = new PluginFactoryLedgerConnector({ pluginImportType: PluginImportType.Local, }); const pluginRegistry = new PluginRegistry({}); const connector: PluginLedgerConnectorBesu = await factory.create({ rpcApiHttpHost, rpcApiWsHost, logLevel, instanceId: connectorId, pluginRegistry: new PluginRegistry({ plugins: [keychainPlugin] }), }); pluginRegistry.add(connector); const pluginOptions: IPluginHtlcEthBesuErc20Options = { logLevel, instanceId: uuidv4(), pluginRegistry, }; const factoryHTLC = new PluginFactoryHtlcEthBesuErc20({ pluginImportType: PluginImportType.Local, }); const pluginHtlc = await factoryHTLC.create(pluginOptions); pluginRegistry.add(pluginHtlc); const expressApp = express(); expressApp.use(bodyParser.json({ limit: "250mb" })); const server = http.createServer(expressApp); const listenOptions: IListenOptions = { hostname: "localhost", port: 0, server, }; const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; test.onFinish(async () => await Servers.shutdown(server)); const { address, port } = addressInfo; const apiHost = `http://${address}:${port}`; const configuration = new Configuration({ basePath: apiHost }); const api = new BesuApi(configuration); const OAS = (pluginHtlc as PluginHtlcEthBesuErc20).getOpenApiSpec(); await installOpenapiValidationMiddleware({ logLevel, app: expressApp, apiSpec: OAS, }); await pluginHtlc.getOrCreateWebServices(); await pluginHtlc.registerWebServices(expressApp); const fInitialize = "initializeV1"; const fNew = "newContractV1"; const fRefund = "refundV1"; const fWithdraw = "withdrawV1"; const fStatus = "getStatusV1"; const fSingleStatus = "getSingleStatusV1"; const cOk = "without bad request error"; const cWithoutParams = "not sending all required parameters"; const cInvalidParams = "sending invalid parameters"; let hashTimeLockAddress: string; let timestamp: number; let tokenAddress: string; let txId: string; test(`${testCase} - ${fInitialize} - ${cOk}`, async (t2: Test) => { const parameters = { connectorId, keychainId, constructorArgs: [], web3SigningCredential, gas: estimatedGas, }; const res = await api.initializeV1(parameters); t2.ok(res, "initialize called successfully"); t2.equal( res.status, 200, `Endpoint ${fInitialize}: response.status === 200 OK`, ); hashTimeLockAddress = res.data.transactionReceipt.contractAddress as string; t2.end(); }); test(`${testCase} - ${fInitialize} - ${cWithoutParams}`, async (t2: Test) => { const parameters = { // connectorId, keychainId, constructorArgs: [], web3SigningCredential, gas: estimatedGas, }; try { await api.initializeV1((parameters as any) as InitializeRequest); } catch (e) { t2.equal( e.response.status, 400, `Endpoint ${fInitialize} without required connectorId: response.status === 400 OK`, ); const fields = e.response.data.map((param: any) => param.path.replace(".body.", ""), ); t2.ok( fields.includes("connectorId"), "Rejected because connectorId is required", ); } t2.end(); }); test(`${testCase} - ${fInitialize} - ${cInvalidParams}`, async (t2: Test) => { const parameters = { connectorId, keychainId, constructorArgs: [], web3SigningCredential, gas: estimatedGas, fake: 4, }; try { await api.initializeV1((parameters as any) as InitializeRequest); } catch (e) { t2.equal( e.response.status, 400, `Endpoint ${fInitialize} with fake=4: response.status === 400 OK`, ); const fields = e.response.data.map((param: any) => param.path.replace(".body.", ""), ); t2.ok( fields.includes("fake"), "Rejected because fake is not a valid parameter", ); } t2.end(); }); test(`${testCase} - ${fNew} - ${cOk}`, async (t2: Test) => { const deployOutToken = await connector.deployContract({ contractName: TestTokenJSON.contractName, contractAbi: TestTokenJSON.abi, bytecode: TestTokenJSON.bytecode, web3SigningCredential, keychainId, constructorArgs: ["100", "token", "2", "TKN"], gas: estimatedGas, }); t2.ok(deployOutToken, "deployOutToken is truthy OK"); t2.ok( deployOutToken.transactionReceipt, "deployOutToken.transactionReceipt is truthy OK", ); t2.ok( deployOutToken.transactionReceipt.contractAddress, "deployOutToken.transactionReceipt.contractAddress is truthy OK", ); tokenAddress = deployOutToken.transactionReceipt.contractAddress as string; const deployOutDemo = await connector.deployContract({ contractName: DemoHelperJSON.contractName, contractAbi: DemoHelperJSON.abi, bytecode: DemoHelperJSON.bytecode, web3SigningCredential, keychainId, constructorArgs: [], gas: estimatedGas, }); t2.ok(deployOutDemo, "deployOutToken is truthy OK"); const { success } = await connector.invokeContract({ contractName: TestTokenJSON.contractName, keychainId, signingCredential: web3SigningCredential, invocationType: EthContractInvocationType.Send, methodName: "approve", params: [hashTimeLockAddress, "10"], gas: estimatedGas, }); t2.equal(success, true, "approve() transactionReceipt.status is true OK"); const { callOutput } = await connector.invokeContract({ contractName: DemoHelperJSON.contractName, keychainId, signingCredential: web3SigningCredential, invocationType: EthContractInvocationType.Call, methodName: "getTimestamp", params: [], }); t2.ok(callOutput, "callOutput() output.callOutput is truthy OK"); timestamp = callOutput as number; timestamp = +timestamp + +10; t2.comment("Call to newContract endpoint"); const parameters = { contractAddress: hashTimeLockAddress, inputAmount: 10, outputAmount: 1, expiration: timestamp, hashLock, tokenAddress, receiver, outputNetwork: "BTC", outputAddress: "1AcVYm7M3kkJQH28FXAvyBFQzFRL6xPKu8", connectorId, keychainId, web3SigningCredential, gas: estimatedGas, }; const res = await api.newContractV1(parameters); t2.ok(res, "newContract called successfully"); t2.equal(res.status, 200, `Endpoint ${fNew}: response.status === 200 OK`); t2.end(); }); test(`${testCase} - ${fNew} - ${cWithoutParams}`, async (t2: Test) => { const parameters = { // contractAddress: hashTimeLockAddress, inputAmount: 10, outputAmount: 1, expiration: timestamp, hashLock, tokenAddress, receiver, outputNetwork: "BTC", outputAddress: "1AcVYm7M3kkJQH28FXAvyBFQzFRL6xPKu8", connectorId, keychainId, web3SigningCredential, gas: estimatedGas, }; try { await api.newContractV1((parameters as any) as NewContractRequest); } catch (e) { t2.equal( e.response.status, 400, `Endpoint ${fNew} without required contractAddress: response.status === 400 OK`, ); const fields = e.response.data.map((param: any) => param.path.replace(".body.", ""), ); t2.ok( fields.includes("contractAddress"), "Rejected because contractAddress is required", ); } t2.end(); }); test(`${testCase} - ${fNew} - ${cInvalidParams}`, async (t2: Test) => { const parameters = { contractAddress: hashTimeLockAddress, inputAmount: 10, outputAmount: 1, expiration: timestamp, hashLock, tokenAddress, receiver, outputNetwork: "BTC", outputAddress: "1AcVYm7M3kkJQH28FXAvyBFQzFRL6xPKu8", connectorId, keychainId, web3SigningCredential, gas: estimatedGas, fake: 4, }; try { await api.newContractV1((parameters as any) as NewContractRequest); } catch (e) { t2.equal( e.response.status, 400, `Endpoint ${fNew} with fake=4: response.status === 400 OK`, ); const fields = e.response.data.map((param: any) => param.path.replace(".body.", ""), ); t2.ok( fields.includes("fake"), "Rejected because fake is not a valid parameter", ); } t2.end(); }); test(`${testCase} - ${fRefund} - ${cOk}`, async (t2: Test) => { const responseTxId = await connector.invokeContract({ contractName: DemoHelperJSON.contractName, keychainId, signingCredential: web3SigningCredential, invocationType: EthContractInvocationType.Call, methodName: "getTxId", params: [ firstHighNetWorthAccount, receiver, 10, hashLock, timestamp, tokenAddress, ], }); t2.ok(responseTxId.callOutput, "result is truthy OK"); txId = responseTxId.callOutput as string; await timeout(6000); const parameters = { id: txId, web3SigningCredential, connectorId, keychainId, }; const res = await api.refundV1(parameters); t2.equal( res.status, 200, `Endpoint ${fRefund}: response.status === 200 OK`, ); t2.end(); }); test(`${testCase} - ${fRefund} - ${cWithoutParams}`, async (t2: Test) => { const parameters = { // id, web3SigningCredential, connectorId, keychainId, }; try { await api.refundV1((parameters as any) as RefundRequest); } catch (e) { t2.equal( e.response.status, 400, `Endpoint ${fRefund} without required id: response.status === 400 OK`, ); const fields = e.response.data.map((param: any) => param.path.replace(".body.", ""), ); t2.ok(fields.includes("id"), "Rejected because id is required"); } t2.end(); }); test(`${testCase} - ${fRefund} - ${cInvalidParams}`, async (t2: Test) => { const parameters = { id: "", web3SigningCredential, connectorId, keychainId, fake: 4, }; try { await api.refundV1((parameters as any) as RefundRequest); } catch (e) { t2.equal( e.response.status, 400, `Endpoint ${fRefund} with fake=4: response.status === 400 OK`, ); const fields = e.response.data.map((param: any) => param.path.replace(".body.", ""), ); t2.ok( fields.includes("fake"), "Rejected because fake is not a valid parameter", ); } t2.end(); }); test(`${testCase} - ${fWithdraw} - ${cOk}`, async (t2: Test) => { const deployOutToken = await connector.deployContract({ contractName: TestTokenJSON.contractName, contractAbi: TestTokenJSON.abi, bytecode: TestTokenJSON.bytecode, web3SigningCredential, keychainId, constructorArgs: ["100", "token", "2", "TKN"], gas: estimatedGas, }); t2.ok( deployOutToken.transactionReceipt.contractAddress, "deployContract() output.transactionReceipt.contractAddress is truthy OK", ); const tokenAddress = deployOutToken.transactionReceipt .contractAddress as string; await connector.deployContract({ contractName: DemoHelperJSON.contractName, contractAbi: DemoHelperJSON.abi, bytecode: DemoHelperJSON.bytecode, web3SigningCredential, keychainId, constructorArgs: [], gas: estimatedGas, }); await connector.invokeContract({ contractName: TestTokenJSON.contractName, keychainId, signingCredential: web3SigningCredential, invocationType: EthContractInvocationType.Send, methodName: "approve", params: [hashTimeLockAddress, "10"], gas: estimatedGas, }); await api.newContractV1({ contractAddress: hashTimeLockAddress, inputAmount: 10, outputAmount: 1, expiration, hashLock, tokenAddress, receiver, outputNetwork: "BTC", outputAddress: "1AcVYm7M3kkJQH28FXAvyBFQzFRL6xPKu8", connectorId, keychainId, web3SigningCredential, gas: estimatedGas, }); const responseTxId = await connector.invokeContract({ contractName: DemoHelperJSON.contractName, keychainId, signingCredential: web3SigningCredential, invocationType: EthContractInvocationType.Call, methodName: "getTxId", params: [ firstHighNetWorthAccount, receiver, 10, hashLock, expiration, tokenAddress, ], }); t2.ok(responseTxId.callOutput, "result is truthy OK"); const id = responseTxId.callOutput as string; const withdrawRequest: WithdrawRequest = { id, secret, web3SigningCredential, connectorId, keychainId, }; const resWithdraw = await api.withdrawV1(withdrawRequest); t2.equal( resWithdraw.status, 200, `Endpoint ${fWithdraw}: response.status === 200 OK`, ); t2.end(); }); test(`${testCase} - ${fWithdraw} - ${cWithoutParams}`, async (t2: Test) => { const parameters = { // id, secret, web3SigningCredential, connectorId, keychainId, }; try { await api.withdrawV1((parameters as any) as WithdrawRequest); } catch (e) { t2.equal( e.response.status, 400, `Endpoint ${fWithdraw} without required id: response.status === 400 OK`, ); const fields = e.response.data.map((param: any) => param.path.replace(".body.", ""), ); t2.ok(fields.includes("id"), "Rejected because id is required"); } t2.end(); }); test(`${testCase} - ${fWithdraw} - ${cInvalidParams}`, async (t2: Test) => { const parameters = { id: "", secret, web3SigningCredential, connectorId, keychainId, fake: 4, }; try { await api.withdrawV1((parameters as any) as WithdrawRequest); } catch (e) { t2.equal( e.response.status, 400, `Endpoint ${fWithdraw} with fake=4: response.status === 400 OK`, ); const fields = e.response.data.map((param: any) => param.path.replace(".body.", ""), ); t2.ok( fields.includes("fake"), "Rejected because fake is not a valid parameter", ); } t2.end(); }); test(`${testCase} - ${fStatus} - ${cOk}`, async (t2: Test) => { const ids = [txId as string]; const parameters = { ids, web3SigningCredential, connectorId, keychainId, }; const res = await api.getStatusV1(parameters); t2.equal( res.status, 200, `Endpoint ${fStatus}: response.status === 200 OK`, ); t2.end(); }); test(`${testCase} - ${fStatus} - ${cWithoutParams}`, async (t2: Test) => { const parameters = { // ids, web3SigningCredential, connectorId, keychainId, }; try { await api.getStatusV1((parameters as any) as GetStatusRequest); } catch (e) { t2.equal( e.response.status, 400, `Endpoint ${fStatus} without required id: response.status === 400 OK`, ); const fields = e.response.data.map((param: any) => param.path.replace(".body.", ""), ); t2.ok(fields.includes("ids"), "Rejected because ids is required"); } t2.end(); }); test(`${testCase} - ${fStatus} - ${cInvalidParams}`, async (t2: Test) => { const parameters = { ids: [""], web3SigningCredential, connectorId, keychainId, fake: 4, }; try { await api.getStatusV1((parameters as any) as GetStatusRequest); } catch (e) { t2.equal( e.response.status, 400, `Endpoint ${fStatus} with fake=4: response.status === 400 OK`, ); const fields = e.response.data.map((param: any) => param.path.replace(".body.", ""), ); t2.ok( fields.includes("fake"), "Rejected because fake is not a valid parameter", ); } t2.end(); }); test(`${testCase} - ${fSingleStatus} - ${cOk}`, async (t2: Test) => { const parameters = { id: txId, web3SigningCredential, connectorId, keychainId, }; const res = await api.getSingleStatusV1(parameters); t2.equal( res.status, 200, `Endpoint ${fSingleStatus}: response.status === 200 OK`, ); t2.end(); }); test(`${testCase} - ${fSingleStatus} - ${cWithoutParams}`, async (t2: Test) => { const parameters = { // id: callOutput, web3SigningCredential, connectorId, keychainId, }; try { await api.getSingleStatusV1( (parameters as any) as GetSingleStatusRequest, ); } catch (e) { t2.equal( e.response.status, 400, `Endpoint ${fSingleStatus} without required id: response.status === 400 OK`, ); const fields = e.response.data.map((param: any) => param.path.replace(".body.", ""), ); t2.ok(fields.includes("id"), "Rejected because id is required"); } t2.end(); }); test(`${testCase} - ${fSingleStatus} - ${cInvalidParams}`, async (t2: Test) => { const parameters = { id: "", web3SigningCredential, connectorId, keychainId, fake: 4, }; try { // eslint-disable-next-line prettier/prettier await api.getSingleStatusV1((parameters as any) as GetSingleStatusRequest); } catch (e) { t2.equal( e.response.status, 400, `Endpoint ${fSingleStatus} with fake=4: response.status === 400 OK`, ); const fields = e.response.data.map((param: any) => param.path.replace(".body.", ""), ); t2.ok( fields.includes("fake"), "Rejected because fake is not a valid parameter", ); } t2.end(); }); t.end(); }); test("AFTER " + testCase, async (t: Test) => { const pruning = pruneDockerAllIfGithubAction({ logLevel }); await t.doesNotReject(pruning, "Pruning did not throw OK"); t.end(); });
the_stack
import { Position, SourceNode } from 'source-map'; // Matches <%= expr %>. This does not support structural JavaScript (for/if/...). const kInterpolateRe = /<%=([\s\S]+?)%>/g; // Matches <%# text %>. It's a comment and will be entirely ignored. const kCommentRe = /<%#([\s\S]+?)%>/g; // Used to match template delimiters. // <%- expr %>: HTML escape the value. // <% ... %>: Structural template code. const kEscapeRe = /<%-([\s\S]+?)%>/g; const kEvaluateRe = /<%([\s\S]+?)%>/g; /** Used to map characters to HTML entities. */ const kHtmlEscapes: { [char: string]: string } = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '`': '&#96;', }; // Used to match HTML entities and HTML characters. const reUnescapedHtml = new RegExp(`[${Object.keys(kHtmlEscapes).join('')}]`, 'g'); // Options to pass to template. export interface TemplateOptions { sourceURL?: string; sourceMap?: boolean; module?: boolean | { exports: {} }; sourceRoot?: string; fileName?: string; } function _positionFor(content: string, offset: number): Position { let line = 1; let column = 0; for (let i = 0; i < offset - 1; i++) { if (content[i] == '\n') { line++; column = 0; } else { column++; } } return { line, column, }; } /** * A simple AST for templates. There's only one level of AST nodes, but it's still useful * to have the information you're looking for. */ export interface TemplateAst { fileName: string; content: string; children: TemplateAstNode[]; } /** * The base, which contains positions. */ export interface TemplateAstBase { start: Position; end: Position; } /** * A static content node. */ export interface TemplateAstContent extends TemplateAstBase { kind: 'content'; content: string; } /** * A comment node. */ export interface TemplateAstComment extends TemplateAstBase { kind: 'comment'; text: string; } /** * An evaluate node, which is the code between `<% ... %>`. */ export interface TemplateAstEvaluate extends TemplateAstBase { kind: 'evaluate'; expression: string; } /** * An escape node, which is the code between `<%- ... %>`. */ export interface TemplateAstEscape extends TemplateAstBase { kind: 'escape'; expression: string; } /** * An interpolation node, which is the code between `<%= ... %>`. */ export interface TemplateAstInterpolate extends TemplateAstBase { kind: 'interpolate'; expression: string; } export type TemplateAstNode = | TemplateAstContent | TemplateAstEvaluate | TemplateAstComment | TemplateAstEscape | TemplateAstInterpolate; /** * Given a source text (and a fileName), returns a TemplateAst. */ export function templateParser(sourceText: string, fileName: string): TemplateAst { const children = []; // Compile the regexp to match each delimiter. const reExpressions = [kEscapeRe, kCommentRe, kInterpolateRe, kEvaluateRe]; const reDelimiters = RegExp(reExpressions.map((x) => x.source).join('|') + '|$', 'g'); const parsed = sourceText.split(reDelimiters); let offset = 0; // Optimization that uses the fact that the end of a node is always the beginning of the next // node, so we keep the positioning of the nodes in memory. let start = _positionFor(sourceText, offset); let end: Position | null; const increment = reExpressions.length + 1; for (let i = 0; i < parsed.length; i += increment) { const [content, escape, comment, interpolate, evaluate] = parsed.slice(i, i + increment); if (content) { end = _positionFor(sourceText, offset + content.length); offset += content.length; children.push({ kind: 'content', content, start, end } as TemplateAstContent); start = end; } if (escape) { end = _positionFor(sourceText, offset + escape.length + 5); offset += escape.length + 5; children.push({ kind: 'escape', expression: escape, start, end } as TemplateAstEscape); start = end; } if (comment) { end = _positionFor(sourceText, offset + comment.length + 5); offset += comment.length + 5; children.push({ kind: 'comment', text: comment, start, end } as TemplateAstComment); start = end; } if (interpolate) { end = _positionFor(sourceText, offset + interpolate.length + 5); offset += interpolate.length + 5; children.push({ kind: 'interpolate', expression: interpolate, start, end, } as TemplateAstInterpolate); start = end; } if (evaluate) { end = _positionFor(sourceText, offset + evaluate.length + 5); offset += evaluate.length + 5; children.push({ kind: 'evaluate', expression: evaluate, start, end } as TemplateAstEvaluate); start = end; } } return { fileName, content: sourceText, children, }; } /** * Fastest implementation of the templating algorithm. It only add strings and does not bother * with source maps. */ function templateFast(ast: TemplateAst, options?: TemplateOptions): string { const module = options && options.module ? 'module.exports.default =' : ''; const reHtmlEscape = reUnescapedHtml.source.replace(/[']/g, "\\\\\\'"); return ` return ${module} function(obj) { obj || (obj = {}); let __t; let __p = ''; const __escapes = ${JSON.stringify(kHtmlEscapes)}; const __escapesre = new RegExp('${reHtmlEscape}', 'g'); const __e = function(s) { return s ? s.replace(__escapesre, function(key) { return __escapes[key]; }) : ''; }; with (obj) { ${ast.children .map((node) => { switch (node.kind) { case 'content': return `__p += ${JSON.stringify(node.content)};`; case 'interpolate': return `__p += ((__t = (${node.expression})) == null) ? '' : __t;`; case 'escape': return `__p += __e(${node.expression});`; case 'evaluate': return node.expression; } }) .join('\n')} } return __p; }; `; } /** * Templating algorithm with source map support. The map is outputted as //# sourceMapUrl=... */ function templateWithSourceMap(ast: TemplateAst, options?: TemplateOptions): string { const sourceUrl = ast.fileName; const module = options && options.module ? 'module.exports.default =' : ''; const reHtmlEscape = reUnescapedHtml.source.replace(/[']/g, "\\\\\\'"); const preamble = new SourceNode(1, 0, sourceUrl, '').add( new SourceNode(1, 0, sourceUrl, [ `return ${module} function(obj) {\n`, ' obj || (obj = {});\n', ' let __t;\n', ' let __p = "";\n', ` const __escapes = ${JSON.stringify(kHtmlEscapes)};\n`, ` const __escapesre = new RegExp('${reHtmlEscape}', 'g');\n`, `\n`, ` const __e = function(s) { `, ` return s ? s.replace(__escapesre, function(key) { return __escapes[key]; }) : '';`, ` };\n`, ` with (obj) {\n`, ]), ); const end = ast.children.length ? ast.children[ast.children.length - 1].end : { line: 0, column: 0 }; const nodes = ast.children .reduce((chunk, node) => { let code: string | SourceNode | (SourceNode | string)[] = ''; switch (node.kind) { case 'content': code = [ new SourceNode(node.start.line, node.start.column, sourceUrl, '__p = __p'), ...node.content.split('\n').map((line, i, arr) => { return new SourceNode( node.start.line + i, i == 0 ? node.start.column : 0, sourceUrl, '\n + ' + JSON.stringify(line + (i == arr.length - 1 ? '' : '\n')), ); }), new SourceNode(node.end.line, node.end.column, sourceUrl, ';\n'), ]; break; case 'interpolate': code = [ new SourceNode(node.start.line, node.start.column, sourceUrl, '__p += ((__t = '), ...node.expression.split('\n').map((line, i, arr) => { return new SourceNode( node.start.line + i, i == 0 ? node.start.column : 0, sourceUrl, line + (i == arr.length - 1 ? '' : '\n'), ); }), new SourceNode(node.end.line, node.end.column, sourceUrl, ') == null ? "" : __t);\n'), ]; break; case 'escape': code = [ new SourceNode(node.start.line, node.start.column, sourceUrl, '__p += __e('), ...node.expression.split('\n').map((line, i, arr) => { return new SourceNode( node.start.line + i, i == 0 ? node.start.column : 0, sourceUrl, line + (i == arr.length - 1 ? '' : '\n'), ); }), new SourceNode(node.end.line, node.end.column, sourceUrl, ');\n'), ]; break; case 'evaluate': code = [ ...node.expression.split('\n').map((line, i, arr) => { return new SourceNode( node.start.line + i, i == 0 ? node.start.column : 0, sourceUrl, line + (i == arr.length - 1 ? '' : '\n'), ); }), new SourceNode(node.end.line, node.end.column, sourceUrl, '\n'), ]; break; } return chunk.add(new SourceNode(node.start.line, node.start.column, sourceUrl, code)); }, preamble) .add( new SourceNode(end.line, end.column, sourceUrl, [' };\n', '\n', ' return __p;\n', '}\n']), ); const code = nodes.toStringWithSourceMap({ file: sourceUrl, sourceRoot: (options && options.sourceRoot) || '.', }); // Set the source content in the source map, otherwise the sourceUrl is not enough // to find the content. code.map.setSourceContent(sourceUrl, ast.content); return ( code.code + '\n//# sourceMappingURL=data:application/json;base64,' + Buffer.from(code.map.toString()).toString('base64') ); } /** * An equivalent of EJS templates, which is based on John Resig's `tmpl` implementation * (http://ejohn.org/blog/javascript-micro-templating/) and Laura Doktorova's doT.js * (https://github.com/olado/doT). * * This version differs from lodash by removing support from ES6 quasi-literals, and making the * code slightly simpler to follow. It also does not depend on any third party, which is nice. * * Finally, it supports SourceMap, if you ever need to debug, which is super nice. * * @param content The template content. * @param options Optional Options. See TemplateOptions for more description. * @return {(input: T) => string} A function that accept an input object and returns the content * of the template with the input applied. */ export function template<T>(content: string, options?: TemplateOptions): (input: T) => string { const sourceUrl = (options && options.sourceURL) || 'ejs'; const ast = templateParser(content, sourceUrl); let source: string; // If there's no need for source map support, we revert back to the fast implementation. if (options && options.sourceMap) { source = templateWithSourceMap(ast, options); } else { source = templateFast(ast, options); } // We pass a dummy module in case the module option is passed. If `module: true` is passed, we // need to only use the source, not the function itself. Otherwise expect a module object to be // passed, and we use that one. const fn = Function('module', source); const module = options && options.module ? (options.module === true ? { exports: {} } : options.module) : null; const result = fn(module); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; return result; }
the_stack
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { NgModel } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { MatSnackBar } from '@angular/material/snack-bar'; import { ActivatedRoute, Router } from '@angular/router'; import { AuthService } from '@app/features/auth/auth.service'; import { BomManualLicenseDetailsDialogComponent } from '@app/features/bill-of-materials/bom-manual-licenses/bom-manual-license-details/bom-manual-license-details-dialog.component'; import { DeploymentTypeService } from '@app/shared/+state/deploymentType/deployment-type.service'; import { OutputFormatTypeService } from '@app/shared/+state/outputFormatType/output-format-type.service'; import { PackageManagerService } from '@app/shared/+state/packageManager/package-manager.service'; import { ProjectService } from '@app/shared/+state/project/project.service'; import { ProjectDevelopmentTypeService } from '@app/shared/+state/projectDevelopmentType/project-development-type.service'; import { ProjectStatusTypeService } from '@app/shared/+state/projectStatusType/project-status-type.service'; import { ScanService } from '@app/shared/+state/scan/scan.service'; import { SystemConfigurationService } from '@app/shared/+state/systemConfiguration/system-configuration.service'; import { BomManualLicense, BomManualLicenseApiService, DeploymentType, License, LicenseApiService, OutputFormatType, PackageManager, Project, ProjectApiService, ProjectDevelopmentType, ProjectDistinctLicenseDto, ProjectDistinctSeverityDto, ProjectDistinctVulnerabilityDto, ProjectStatusType, ScanApiService, SystemConfiguration, } from '@app/shared/api'; import { AppDialogComponent } from '@app/shared/app-components/app-dialog/app-dialog.component'; import IBreadcrumb from '@app/shared/app-components/breadcrumbs/IBreadcrumb'; import { getDefaultValue } from '@app/shared/helpers'; import { compareLookupModels } from '@app/shared/helpers/lookup-model'; import { ProjectDetailsTabChangedMessageService } from '@app/shared/services/ProjectDetailsTabChangedMessageService'; import { ToolTipsCacheService } from '@app/shared/services/ToolTipsCacheService'; import * as _ from 'lodash'; import { untilDestroyed } from 'ngx-take-until-destroy'; import { combineLatest, Observable } from 'rxjs'; import { first, debounceTime } from 'rxjs/operators'; @Component({ selector: 'app-project-details', templateUrl: './project-details.component.html', styleUrls: ['./project-details.component.scss'], }) export class ProjectDetailsComponent implements OnInit, OnDestroy { @ViewChild('gitUrlModel') gitUrlModel; constructor( private projectService: ProjectService, private scanApiService: ScanApiService, private scanService: ScanService, private route: ActivatedRoute, private router: Router, private snackBar: MatSnackBar, private dialog: MatDialog, private packageManagerService: PackageManagerService, private outputFormatTypeService: OutputFormatTypeService, private deploymentTypeService: DeploymentTypeService, private projectDevelopmentTypeService: ProjectDevelopmentTypeService, private projectStatusTypeService: ProjectStatusTypeService, private projectApiService: ProjectApiService, private licenseApiService: LicenseApiService, private bomManualLicenseApiService: BomManualLicenseApiService, private authService: AuthService, private tabChangedMessageService: ProjectDetailsTabChangedMessageService, private toolTipsCacheService: ToolTipsCacheService, private systemConfigService: SystemConfigurationService, ) { this.projectStatusType$ = this.projectStatusTypeService.entities$; this.outputFormatType$ = this.outputFormatTypeService.entities$; this.packageManagers$ = this.packageManagerService.entities$; this.deploymentType$ = this.deploymentTypeService.entities$; this.projectDevelopmentType$ = this.projectDevelopmentTypeService.entities$; } breadcrumbs: IBreadcrumb[]; compareLookupModels = compareLookupModels; defaultManualLicense: BomManualLicense; deploymentType$: Observable<OutputFormatType[]>; isProjectOwner = false; licenseData$: Observable<ProjectDistinctLicenseDto[]>; licenses$: Observable<License[]>; manualLicenses$: Observable<BomManualLicense[]>; newProject = false; outputFormatType$: Observable<OutputFormatType[]>; packageManagers$: Observable<PackageManager[]>; project: Project; projectDevelopmentType$: Observable<OutputFormatType[]>; projectId = null; projectStatusType$: Observable<ProjectStatusType[]>; selectedTabIndex?: number; severityData$: Observable<ProjectDistinctSeverityDto[]>; systemConfiguration: Observable<SystemConfiguration>; tooltips = null; vulnerabilityData$: Observable<ProjectDistinctVulnerabilityDto[]>; addManualLicense() { if (this.project.name && this.project.currentVersion) { const manualLicense = {} as BomManualLicense; manualLicense.productName = this.project.name; manualLicense.productVersion = this.project.currentVersion; const data: any = { project: { id: this.projectId }, manualLicense, prePopulatedProductName: true, prePopulatedProductVersion: true, isDefaultLicense: true, }; const dialogRef = this.dialog.open(BomManualLicenseDetailsDialogComponent, { minWidth: '512px', data, }); dialogRef.afterClosed().subscribe(() => { // Refresh results this.refreshManualLicenses(); }); } else { alert('Please add a project name and version before configuring a license.'); } } afterOptionValuesLoaded({ packageManagerCode = null, projectStatusCode = null, outputFormatCode = null, deploymentTypeCode = null, projectDevelopmentTypeCode = null, } = {}) { this.setupBreadcrumbs(); combineLatest([ this.projectStatusTypeService.entities$, this.outputFormatTypeService.entities$, this.packageManagerService.entities$, this.deploymentTypeService.entities$, this.projectDevelopmentTypeService.entities$, ]) .pipe(untilDestroyed(this)) .subscribe((result) => { if (_.every(result, (r) => _.size(r))) { this.project.projectStatus = getDefaultValue(result[0], projectStatusCode) as ProjectStatusType; this.project.outputFormat = getDefaultValue(result[1], outputFormatCode) as OutputFormatType; this.project.packageManager = getDefaultValue(result[2], packageManagerCode) as PackageManager; this.project.deploymentType = getDefaultValue(result[3], deploymentTypeCode) as DeploymentType; this.project.developmentType = getDefaultValue( result[4], projectDevelopmentTypeCode, ) as ProjectDevelopmentType; } }); } ngOnDestroy(): void {} async ngOnInit() { this.systemConfiguration = this.systemConfigService.apiService.systemConfigurationIdGet('default'); this.licenses$ = this.licenseApiService.licenseGet(); this.projectId = this.route.snapshot.paramMap.get('projectId'); this.toolTipsCacheService // can't use ProjectDetailsComponent.name, after minification this name is no more relevant. .getToolTipsForPage('ProjectDetailsComponent') .pipe(untilDestroyed(this)) .subscribe((tooltips) => { this.tooltips = tooltips; }); if (this.projectId === 'new') { this.newProject = true; this.projectId = null; } else { this.projectId = Number(this.projectId); } this.projectStatusTypeService.getAll(); this.outputFormatTypeService.getAll(); this.packageManagerService.getWithQuery({ sort: 'description,ASC' }); this.deploymentTypeService.getAll(); this.projectDevelopmentTypeService.getAll(); if (this.newProject) { const { userInfo } = this.authService; this.project = { outputEmail: userInfo.email, owner: userInfo.displayName, userId: userInfo.id, } as Project; this.afterOptionValuesLoaded(); } else { this.projectService.setFilter(this.projectId); // ngrx entity data service and entity service this.projectService.filteredEntities$ // subscribe to observables, look at entity-metadata.ts .pipe(untilDestroyed(this)) .subscribe((projects) => { // unsubscribe, subscribe is async, can be called a lot if (projects.length > 0) { this.project = { ...projects[0] }; this.setProjectDetailVisibility(); this.licenseData$ = this.projectService.apiService.projectIdStatsLicensesGet(`${this.project.id}`); this.vulnerabilityData$ = this.projectService.apiService.projectIdStatsVulnerabilitiesGet( `${this.project.id}`, ); this.severityData$ = this.projectService.apiService.projectIdStatsSeveritiesGet(`${this.project.id}`); this.afterOptionValuesLoaded({ packageManagerCode: this.project.packageManager.code, outputFormatCode: this.project.outputFormat.code, projectStatusCode: this.project.projectStatus.code, deploymentTypeCode: this.project.deploymentType.code, projectDevelopmentTypeCode: this.project.developmentType.code, }); this.refreshManualLicenses(); } else { if (this.projectId) { this.projectService.getByKey(this.projectId); } } }); this.gitUrlModel?.control.valueChanges.subscribe((value: string) => { console.log('top'); if (value === undefined || value.length === 0) { return; } if (value.startsWith('http')) { this.gitUrlModel.control.setErrors({ githubUrlDoesExist: true }); } // this.http.get<Product>('/api/product/' + value).subscribe(product => { // this.partNumberModel.control.setErrors({"partnumberExists": true}) // }, // error => {}); }); } this.route.queryParams.subscribe((queryParams) => { this.selectedTabIndex = queryParams.tab; }); } onSubmit() { if (this.newProject) { this.projectApiService .projectPost(this.project) .pipe(first()) .subscribe( (project) => { this.project = { ...project }; this.newProject = false; this.snackBar.open(`Project ${project.name}`, 'OK', { duration: 3000, horizontalPosition: 'right', verticalPosition: 'top', }); this.setupBreadcrumbs(); return this.router.navigate(['/project', project.id]); }, (error) => { this.dialog.open(AppDialogComponent, { data: { title: 'Error', message: JSON.stringify(error) }, }); }, ); } else { this.projectService .update(this.project) .pipe(first()) .subscribe( (project) => { this.project = { ...project }; this.snackBar.open(`Project ${project.name}`, 'OK', { duration: 5000, horizontalPosition: 'right', verticalPosition: 'top', }); }, (error) => { this.dialog.open(AppDialogComponent, { data: { title: 'Error', message: JSON.stringify(error) }, }); }, ); } } onTabChanged(ev) { const { index, tab: { textLabel: title }, } = ev; this.tabChangedMessageService.send({ tabIndex: index, tabTitle: title }); } refreshManualLicenses() { this.manualLicenses$ = this.bomManualLicenseApiService .bomManualLicenseGet( null, `project||eq||${this.project.id}`, null, null, null, null, null, null, null, null, null, ) .pipe(untilDestroyed(this)); this.manualLicenses$.subscribe((items) => { const result = items.filter((item) => item.isDefault === true); if (result && result.length > 0) { this.defaultManualLicense = result[0]; } }); } setProjectDetailVisibility() { if (this.project) { this.isProjectOwner = this.authService.isProjectOwner(this.project); } } setupBreadcrumbs() { const projectListType = this.projectService.breadcrumbProjectType(this.project); this.breadcrumbs = [ ...projectListType, { url: '', title: this.project && this.project.name ? this.project.name : '*New Project', }, ]; } }
the_stack
import {ChevronDownIcon} from '@sanity/icons' import React, { cloneElement, forwardRef, useCallback, useEffect, useMemo, useReducer, useRef, useState, } from 'react' import {EMPTY_ARRAY} from '../../constants' import {_hasFocus, _raf, focusFirstDescendant} from '../../helpers' import {useForwardedRef, useResponsiveProp} from '../../hooks' import {Box, BoxProps, Button, Card, PopoverProps, Stack, Text, TextInput} from '../../primitives' import {AnimatedSpinnerIcon, ListBox, ResultsPopover, Root} from './autocomplete.styles' import {AutocompleteOption} from './autocompleteOption' import {autocompleteReducer} from './autocompleteReducer' import { EMPTY_RECORD, AUTOCOMPLETE_LISTBOX_IGNORE_KEYS, AUTOCOMPLETE_POPOVER_FALLBACK_PLACEMENTS, AUTOCOMPLETE_POPOVER_MARGINS, AUTOCOMPLETE_POPOVER_PLACEMENT, } from './constants' import {AutocompleteOpenButtonProps, BaseAutocompleteOption} from './types' /** * @public */ export interface AutocompleteProps<Option extends BaseAutocompleteOption> { border?: boolean customValidity?: string filterOption?: (query: string, option: Option) => boolean fontSize?: number | number[] icon?: React.ComponentType | React.ReactNode id: string /** * @beta */ listBox?: BoxProps loading?: boolean onChange?: (value: string) => void onQueryChange?: (query: string | null) => void onSelect?: (value: string) => void /** * @beta */ openButton?: boolean | AutocompleteOpenButtonProps options?: Option[] padding?: number | number[] popover?: Omit<PopoverProps, 'content' | 'onMouseEnter' | 'onMouseLeave' | 'open'> prefix?: React.ReactNode radius?: number | number[] /** * @beta */ relatedElements?: HTMLElement[] renderOption?: (option: Option) => React.ReactElement /** * @beta */ renderPopover?: ( props: { content: React.ReactElement | null hidden: boolean inputElement: HTMLInputElement | null onMouseEnter: () => void onMouseLeave: () => void }, ref: React.Ref<HTMLDivElement> ) => React.ReactNode renderValue?: (value: string, option?: Option) => string suffix?: React.ReactNode value?: string } const defaultRenderValue = (value: string, option?: BaseAutocompleteOption) => option ? option.value : value const defaultFilterOption = (query: string, option: BaseAutocompleteOption) => option.value.toLowerCase().indexOf(query.toLowerCase()) > -1 const InnerAutocomplete = forwardRef(function InnerAutocomplete< Option extends BaseAutocompleteOption >( props: AutocompleteProps<Option> & Omit< React.HTMLProps<HTMLInputElement>, | 'aria-activedescendant' | 'aria-autocomplete' | 'aria-expanded' | 'aria-owns' | 'as' | 'autoCapitalize' | 'autoComplete' | 'autoCorrect' | 'id' | 'inputMode' | 'onChange' | 'onSelect' | 'prefix' | 'ref' | 'role' | 'spellCheck' | 'type' | 'value' >, ref: React.Ref<HTMLInputElement> ) { const { border = true, customValidity, disabled, filterOption: filterOptionProp, fontSize = 2, icon, id, listBox = {}, loading, onBlur, onChange, onFocus, onQueryChange, onSelect, openButton, options: optionsProp, padding: paddingProp = 3, popover = {}, prefix, radius = 3, readOnly, relatedElements, renderOption: renderOptionProp, renderPopover, renderValue = defaultRenderValue, value: valueProp, ...restProps } = props const [state, dispatch] = useReducer(autocompleteReducer, { activeValue: valueProp || null, focused: false, listFocused: false, query: null, value: valueProp || null, }) const {activeValue, focused, listFocused, query, value} = state const defaultRenderOption = useCallback( ({value}: BaseAutocompleteOption) => ( <Card data-as="button" padding={paddingProp} radius={2} tone="inherit"> <Text size={fontSize} textOverflow="ellipsis"> {value} </Text> </Card> ), [fontSize, paddingProp] ) const renderOption = typeof renderOptionProp === 'function' ? renderOptionProp : defaultRenderOption const filterOption = typeof filterOptionProp === 'function' ? filterOptionProp : defaultFilterOption const [rootElement, setRootElement] = useState<HTMLDivElement | null>(null) const [resultsPopoverElement, setResultsPopoverElement] = useState<HTMLDivElement | null>(null) const inputElementRef = useRef<HTMLInputElement | null>(null) const listBoxElementRef = useRef<HTMLDivElement | null>(null) const focusedElementRef = useRef<HTMLElement | null>(null) const valueRef = useRef(value) const valuePropRef = useRef(valueProp) const forwardedRef = useForwardedRef(ref) const popoverMouseWithinRef = useRef(false) const listBoxId = `${id}-listbox` const options = Array.isArray(optionsProp) ? optionsProp : EMPTY_ARRAY const padding = useResponsiveProp(paddingProp) const currentOption = useMemo( () => (value !== null ? options.find((o) => o.value === value) : undefined), [options, value] ) const filteredOptions = useMemo( () => options.filter((option) => (query ? filterOption(query, option) : true)), [filterOption, options, query] ) const filteredOptionsLen = filteredOptions.length const activeItemId = activeValue ? `${id}-option-${activeValue}` : undefined const expanded = (query !== null && loading) || (focused && query !== null) const handleRootBlur = useCallback( (event: React.FocusEvent<HTMLInputElement>) => { setTimeout(() => { // NOTE: This is a workaround for a bug that may happen in Chrome (clicking the scrollbar // closes the results in certain situations): // - Do not handle blur if the mouse is within the popover if (popoverMouseWithinRef.current) { return } const elements: HTMLElement[] = (relatedElements || []).concat( rootElement ? [rootElement] : [], resultsPopoverElement ? [resultsPopoverElement] : [] ) let focusInside = false if (document.activeElement) { for (const e of elements) { if (e === document.activeElement || e.contains(document.activeElement)) { focusInside = true break } } } if (focusInside === false) { dispatch({type: 'root/blur'}) popoverMouseWithinRef.current = false if (onQueryChange) onQueryChange(null) if (onBlur) onBlur(event) } }, 0) }, [onBlur, onQueryChange, relatedElements, resultsPopoverElement, rootElement] ) const handleRootFocus = useCallback((event: React.FocusEvent) => { const listBoxElement = listBoxElementRef.current const focusedElement = event.target instanceof HTMLElement ? event.target : null focusedElementRef.current = focusedElement const nextListFocused = Boolean( listBoxElement && focusedElement && listBoxElement.contains(focusedElement) ) dispatch({type: 'root/setListFocused', listFocused: nextListFocused}) }, []) const handleOptionSelect = useCallback( (v: string) => { dispatch({type: 'value/change', value: v}) popoverMouseWithinRef.current = false if (onSelect) onSelect(v) valueRef.current = v if (onChange) onChange(v) if (onQueryChange) onQueryChange(null) inputElementRef.current?.focus() }, [onChange, onSelect, onQueryChange] ) const handleRootKeyDown = useCallback( (event: React.KeyboardEvent<HTMLElement>) => { if (event.key === 'ArrowDown') { event.preventDefault() if (!filteredOptionsLen) return const activeOption = filteredOptions.find((o) => o.value === activeValue) const activeIndex = activeOption ? filteredOptions.indexOf(activeOption) : -1 const nextActiveOption = filteredOptions[(activeIndex + 1) % filteredOptionsLen] if (nextActiveOption) { dispatch({type: 'root/setActiveValue', value: nextActiveOption.value, listFocused: true}) } return } if (event.key === 'ArrowUp') { event.preventDefault() if (!filteredOptionsLen) return const activeOption = filteredOptions.find((o) => o.value === activeValue) const activeIndex = activeOption ? filteredOptions.indexOf(activeOption) : -1 const nextActiveOption = filteredOptions[ activeIndex === -1 ? filteredOptionsLen - 1 : (filteredOptionsLen + activeIndex - 1) % filteredOptionsLen ] if (nextActiveOption) { dispatch({type: 'root/setActiveValue', value: nextActiveOption.value, listFocused: true}) } return } if (event.key === 'Escape') { dispatch({type: 'root/escape'}) popoverMouseWithinRef.current = false if (onQueryChange) onQueryChange(null) inputElementRef.current?.focus() return } const target = event.target as Node const listEl = listBoxElementRef.current if ( (listEl === target || listEl?.contains(target)) && !AUTOCOMPLETE_LISTBOX_IGNORE_KEYS.includes(event.key) ) { inputElementRef.current?.focus() return } }, [activeValue, filteredOptions, filteredOptionsLen, onQueryChange] ) const handleInputChange = useCallback( (event: React.ChangeEvent<HTMLInputElement>) => { const nextQuery = event.currentTarget.value dispatch({type: 'input/change', query: nextQuery}) if (onQueryChange) onQueryChange(nextQuery) }, [onQueryChange] ) const handleInputFocus = useCallback( (event: React.FocusEvent<HTMLInputElement>) => { if (!focused) { dispatch({type: 'input/focus'}) if (onFocus) onFocus(event) } }, [focused, onFocus] ) const handlePopoverMouseEnter = useCallback(() => { popoverMouseWithinRef.current = true }, []) const handlePopoverMouseLeave = useCallback(() => { popoverMouseWithinRef.current = false }, []) const handleClearButtonClick = useCallback(() => { dispatch({type: 'root/clear'}) valueRef.current = '' if (onChange) onChange('') if (onQueryChange) onQueryChange(null) inputElementRef.current?.focus() }, [onChange, onQueryChange]) const handleClearButtonFocus = useCallback(() => { dispatch({type: 'input/focus'}) }, []) // Change the value when `value` prop changes useEffect(() => { if (valueProp !== valuePropRef.current) { valuePropRef.current = valueProp if (valueProp !== undefined) { dispatch({type: 'value/change', value: valueProp}) valueRef.current = valueProp } return } if (valueProp !== value) { dispatch({type: 'value/change', value: valueProp || null}) } }, [valueProp, value]) // Reset active item when closing useEffect(() => { if (!focused) { if (valueRef.current) { dispatch({type: 'root/setActiveValue', value: valueRef.current}) } } }, [focused]) // Focus the selected item useEffect(() => { const listElement = listBoxElementRef.current if (!listElement) return const activeOption = filteredOptions.find((o) => o.value === activeValue) if (activeOption) { const activeIndex = filteredOptions.indexOf(activeOption) const activeItemElement = listElement.childNodes[activeIndex] as HTMLLIElement | undefined if (activeItemElement) { if (_hasFocus(activeItemElement)) { // already focused return } focusFirstDescendant(activeItemElement) } } }, [activeValue, filteredOptions]) const setRef = useCallback( (el: HTMLInputElement | null) => { inputElementRef.current = el forwardedRef.current = el }, [forwardedRef] ) const clearButton = useMemo(() => { if (!loading && !disabled && value) { return { 'aria-label': 'Clear', onFocus: handleClearButtonFocus, } } return undefined }, [disabled, handleClearButtonFocus, loading, value]) const openButtonBoxPadding = useMemo(() => padding.map((v) => v - 2), [padding]) const openButtonPadding = useMemo(() => padding.map((v) => v - 1), [padding]) const openButtonProps: AutocompleteOpenButtonProps = useMemo( () => (typeof openButton === 'object' ? openButton : EMPTY_RECORD), [openButton] ) const handleOpenClick = useCallback( (event: React.MouseEvent<HTMLButtonElement>) => { dispatch({ type: 'root/open', query: value ? renderValue(value, currentOption) : '', }) if (openButtonProps.onClick) openButtonProps.onClick(event) _raf(() => inputElementRef.current?.focus()) }, [currentOption, openButtonProps, renderValue, value] ) const openButtonNode = useMemo( () => !disabled && !readOnly && openButton ? ( <Box aria-hidden={expanded} padding={openButtonBoxPadding}> <Button aria-label="Open" disabled={expanded} fontSize={fontSize} icon={ChevronDownIcon} mode="bleed" padding={openButtonPadding} {...openButtonProps} onClick={handleOpenClick} /> </Box> ) : undefined, [ disabled, expanded, fontSize, handleOpenClick, openButton, openButtonBoxPadding, openButtonPadding, openButtonProps, readOnly, ] ) const inputValue = useMemo(() => { if (query === null) { if (value !== null) { return renderValue(value, currentOption) } return '' } return query }, [currentOption, query, renderValue, value]) const input = ( <TextInput {...restProps} aria-activedescendant={activeItemId} aria-autocomplete="list" aria-expanded={expanded} aria-owns={listBoxId} autoCapitalize="off" autoComplete="off" autoCorrect="off" border={border} clearButton={clearButton} customValidity={customValidity} disabled={disabled} fontSize={fontSize} icon={icon} iconRight={loading && AnimatedSpinnerIcon} id={id} inputMode="search" onChange={handleInputChange} onClear={handleClearButtonClick} onFocus={handleInputFocus} padding={padding} prefix={prefix} radius={radius} readOnly={readOnly} ref={setRef} role="combobox" spellCheck={false} suffix={openButtonNode} value={inputValue} /> ) const handleListBoxKeyDown = useCallback( (event: React.KeyboardEvent<HTMLDivElement>) => { // If the focus is currently in the list, move focus to the input element if (event.key === 'Tab') { if (listFocused) inputElementRef.current?.focus() } }, [listFocused] ) const content = useMemo(() => { if (filteredOptions.length === 0) return null return ( <ListBox onKeyDown={handleListBoxKeyDown} padding={1} {...listBox} tabIndex={-1}> <Stack as="ul" aria-multiselectable={false} id={listBoxId} ref={listBoxElementRef} role="listbox" space={1} > {filteredOptions.map((option) => { const active = activeValue !== null ? option.value === activeValue : currentOption === option return ( <AutocompleteOption id={`${id}-option-${option.value}`} key={option.value} onSelect={handleOptionSelect} selected={active} value={option.value} > {cloneElement(renderOption(option), { disabled: loading, selected: active, tabIndex: listFocused && active ? 0 : -1, })} </AutocompleteOption> ) })} </Stack> </ListBox> ) }, [ activeValue, currentOption, filteredOptions, handleOptionSelect, handleListBoxKeyDown, id, listBox, listBoxId, listFocused, loading, renderOption, ]) const results = useMemo(() => { if (renderPopover) { return renderPopover( { content, hidden: !expanded, inputElement: inputElementRef.current, onMouseEnter: handlePopoverMouseEnter, onMouseLeave: handlePopoverMouseLeave, }, setResultsPopoverElement ) } if (filteredOptionsLen === 0) { return null } return ( <ResultsPopover __unstable_margins={AUTOCOMPLETE_POPOVER_MARGINS} arrow={false} constrainSize content={content} fallbackPlacements={AUTOCOMPLETE_POPOVER_FALLBACK_PLACEMENTS} matchReferenceWidth onMouseEnter={handlePopoverMouseEnter} onMouseLeave={handlePopoverMouseLeave} open={expanded} placement={AUTOCOMPLETE_POPOVER_PLACEMENT} portal radius={radius} ref={setResultsPopoverElement} referenceElement={inputElementRef.current} {...popover} /> ) }, [ content, expanded, filteredOptionsLen, handlePopoverMouseEnter, handlePopoverMouseLeave, popover, radius, renderPopover, ]) return ( <Root data-ui="Autocomplete" onBlur={handleRootBlur} onFocus={handleRootFocus} onKeyDown={handleRootKeyDown} ref={setRootElement} > {input} {results} </Root> ) }) /** * @public */ export const Autocomplete = InnerAutocomplete as <Option extends BaseAutocompleteOption>( props: AutocompleteProps<Option> & Omit< React.HTMLProps<HTMLInputElement>, | 'aria-activedescendant' | 'aria-autocomplete' | 'aria-expanded' | 'aria-owns' | 'as' | 'autoCapitalize' | 'autoComplete' | 'autoCorrect' | 'id' | 'inputMode' | 'onChange' | 'onSelect' | 'prefix' | 'ref' | 'role' | 'spellCheck' | 'type' | 'value' > & { ref?: React.Ref<HTMLInputElement> } ) => React.ReactElement
the_stack
import {assert} from 'chai'; import * as mm from '../lib'; import * as path from 'path'; const t = assert; const samplePath = path.join(__dirname, 'samples'); // https://github.com/Borewit/music-metadata/pull/544 describe('Add, change and fix some mappings #pr-544', () => { describe('Movement Name', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.movement, 'Movement Name', 'metadata.common.movement'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.movement, 'Movement Name', 'metadata.common.movement'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.movement, 'Movement Name', 'metadata.common.movement'); }); }); }); describe('Movement Index', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.movementIndex, {no: 1, of: 4}, 'metadata.common.movementIndex'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.movementIndex, {no: 1, of: 4}, 'metadata.common.movementIndex'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.movementIndex, {no: 1, of: 4}, 'metadata.common.movementIndex'); }); }); }); describe('Show Movement', () => { // Not exists in MP3 (Written as comment) /*it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.showMovement, true, 'metadata.common.showMovement'); }); });*/ // No possibility found to write id3v22 test file // Not exists in MP3 (Written as comment) /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.showMovement, true, 'metadata.common.showMovement'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.showMovement, true, 'metadata.common.showMovement'); }); }); }); describe('Work', () => { // Not exists in MP3 (Written as comment) /*it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.work, 'Work', 'metadata.common.work'); }); });*/ // No possibility found to write id3v22 test file // Not exists in MP3 (Written as comment) /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.work, 'Work', 'metadata.common.work'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.work, 'Work', 'metadata.common.work'); }); }); }); describe('Podcast', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.podcast, true, 'metadata.common.podcast'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.podcast, true, 'metadata.common.podcast'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.podcast, true, 'metadata.common.podcast'); }); }); }); describe('Podcast Category', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.category, ['Podcast Category'], 'metadata.common.category'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.category, ['Podcast Category'], 'metadata.common.category'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.category, ['Podcast Category'], 'metadata.common.category'); }); }); }); describe('Podcast Identifier', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.podcastId, '1234', 'metadata.common.podcastId'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.podcastId, '1234', 'metadata.common.podcastId'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.podcastId, '1234', 'metadata.common.podcastId'); }); }); }); describe('Podcast Keywords', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.keywords, ['Podcast Keywords'], 'metadata.common.keywords'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.keywords, ['Podcast Keywords'], 'metadata.common.keywords'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.keywords, ['Podcast Keywords'], 'metadata.common.keywords'); }); }); }); describe('Podcast Url', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.podcasturl, 'http://podcast.url', 'metadata.common.podcasturl'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.podcasturl, 'http://podcast.url', 'metadata.common.podcasturl'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.podcasturl, 'http://podcast.url', 'metadata.common.podcasturl'); }); }); }); describe('Short Description', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.subtitle, ['Short Description'], 'metadata.common.subscription'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.subtitle, ['Short Description'], 'metadata.common.subtitle'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.description, ['Short Description'], 'metadata.common.subscription'); }); }); }); describe('Long Description', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.description, ['Long Description'], 'metadata.common.description'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.description, ['Long Description'], 'metadata.common.description'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.longDescription, 'Long Description', 'metadata.common.description'); }); }); }); describe('Album Artist Sort', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.albumartistsort, 'Album Artist Sort', 'metadata.common.albumartistsort'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.albumartistsort, 'Album Artist Sort', 'metadata.common.albumartistsort'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.albumartistsort, 'Album Artist Sort', 'metadata.common.albumartistsort'); }); }); }); describe('Album Sort', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.albumsort, 'Album Sort', 'metadata.common.albumsort'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.albumsort, 'Album Sort', 'metadata.common.albumsort'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.albumsort, 'Album Sort', 'metadata.common.albumsort'); }); }); }); describe('Artist Sort', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.artistsort, 'Artist Sort', 'metadata.common.artistsort'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.artistsort, 'Artist Sort', 'metadata.common.artistsort'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.artistsort, 'Artist Sort', 'metadata.common.artistsort'); }); }); }); describe('Composer Sort', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.composersort, 'Composer Sort', 'metadata.common.composersort'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.composersort, 'Composer Sort', 'metadata.common.composersort'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.composersort, 'Composer Sort', 'metadata.common.composersort'); }); }); }); describe('Title Sort', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.titlesort, 'Title Sort', 'metadata.common.titlesort'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.titlesort, 'Title Sort', 'metadata.common.titlesort'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.titlesort, 'Title Sort', 'metadata.common.titlesort'); }); }); }); describe('Copyright', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.copyright, 'Copyright', 'metadata.common.copyright'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.copyright, 'Copyright', 'metadata.common.copyright'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.copyright, 'Copyright', 'metadata.common.copyright'); }); }); }); describe('Compilation', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.compilation, true, 'metadata.common.compilation'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.compilation, true, 'metadata.common.compilation'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.compilation, true, 'metadata.common.compilation'); }); }); }); describe('Comment', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.comment, ['Tagged with Mp3tag v3.01'], 'metadata.common.comment'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.comment, ['Tagged with Mp3tag v3.01'], 'metadata.common.comment'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.deepEqual(metadata.common.comment, ['Tagged with Mp3tag v3.01'], 'metadata.common.comment'); }); }); }); describe('Release time', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.date, '2020-06-29T00:00:00.000Z', 'metadata.common.date'); t.strictEqual(metadata.common.year, 2020, 'metadata.common.year'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.date, '2020-06-29T00:00:00.000Z', 'metadata.common.date'); t.strictEqual(metadata.common.year, 2020, 'metadata.common.year'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.date, '2020-06-29T00:00:00.000Z', 'metadata.common.date'); t.strictEqual(metadata.common.year, 2020, 'metadata.common.year'); }); }); }); describe('Original Album', () => { it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.originalalbum, 'Original Album', 'metadata.common.originalalbum'); }); }); // No possibility found to write id3v22 test file /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.originalalbum, 'Original Album', 'metadata.common.originalalbum'); }); });*/ // Not exists in MP4 (Written as comment) /*it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.originalalbum, 'Original Album', 'metadata.common.originalalbum'); }); });*/ }); describe('iTunes Video Quality', () => { // Not exists in MP3 (Written as comment) /*it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.hdVideo, 2, 'metadata.common.hdVideo'); }); });*/ // No possibility found to write id3v22 test file // Not exists in MP3 (Written as comment) /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.hdVideo, 2, 'metadata.common.hdVideo'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.hdVideo, 2, 'metadata.common.hdVideo'); }); }); }); describe('iTunes Media Type', () => { // Not exists in MP3 (Written as comment) /*it('mp3-id3v24', () => { const filename = 'mp3/pr-544-id3v24.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.stik, 9, 'metadata.common.stik'); }); });*/ // No possibility found to write id3v22 test file // Not exists in MP3 (Written as comment) /*it('mp3-id3v22', () => { const filename = 'mp3/pr-544-id3v22.mp3'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.stik, 9, 'metadata.common.stik'); }); });*/ it('mp4', () => { const filename = 'mp4/pr-544.m4a'; const filePath = path.join(samplePath, filename); return mm.parseFile(filePath).then(metadata => { t.strictEqual(metadata.common.stik, 9, 'metadata.common.stik'); }); }); }); });
the_stack
import Vue, { VNode } from 'vue' declare global { interface NumberConstructor { ['@@vueTag']: number } interface StringConstructor { ['@@vueTag']: string } interface BooleanConstructor { ['@@vueTag']: boolean } namespace JSX { interface Element extends VNode { } interface ElementClass extends Vue { } interface ElementAttributesProperty { $props: {}; } interface SVGAttributes extends HTMLAttributes { accentHeight?:number | string; accumulate?:"none" | "sum"; additive?:"replace" | "sum"; alignmentBaseline?:"auto" | "baseline" | "before-edge" | "text-before-edge" | "middle" | "central" | "after-edge" | "text-after-edge" | "ideographic" | "alphabetic" | "hanging" | "mathematical" | "inherit"; allowReorder?:"no" | "yes"; alphabetic?:number | string; amplitude?:number | string; arabicForm?:"initial" | "medial" | "terminal" | "isolated"; ascent?:number | string; attributeName?:string; attributeType?:string; autoReverse?:number | string; azimuth?:number | string; baseFrequency?:number | string; baselineShift?:number | string; baseProfile?:number | string; bbox?:number | string; begin?:number | string; bias?:number | string; by?:number | string; calcMode?:number | string; capHeight?:number | string; clip?:number | string; clipPath?:string; clipPathUnits?:number | string; clipRule?:number | string; colorInterpolation?:number | string; colorInterpolationFilters?:"auto" | "sRGB" | "linearRGB" | "inherit"; colorProfile?:number | string; colorRendering?:number | string; contentScriptType?:number | string; contentStyleType?:number | string; cursor?:number | string; cx?:number | string; cy?:number | string; d?:string; decelerate?:number | string; descent?:number | string; diffuseConstant?:number | string; direction?:number | string; display?:number | string; divisor?:number | string; dominantBaseline?:number | string; dur?:number | string; dx?:number | string; dy?:number | string; edgeMode?:number | string; elevation?:number | string; enableBackground?:number | string; end?:number | string; exponent?:number | string; externalResourcesRequired?:number | string; fill?:string; fillOpacity?:number | string; fillRule?:"nonzero" | "evenodd" | "inherit"; filter?:string; filterRes?:number | string; filterUnits?:number | string; floodColor?:number | string; floodOpacity?:number | string; focusable?:number | string; fontFamily?:string; fontSize?:number | string; fontSizeAdjust?:number | string; fontStretch?:number | string; fontStyle?:number | string; fontVariant?:number | string; fontWeight?:number | string; format?:number | string; from?:number | string; fx?:number | string; fy?:number | string; g1?:number | string; g2?:number | string; glyphName?:number | string; glyphOrientationHorizontal?:number | string; glyphOrientationVertical?:number | string; glyphRef?:number | string; gradientTransform?:string; gradientUnits?:string; hanging?:number | string; horizAdvX?:number | string; horizOriginX?:number | string; ideographic?:number | string; imageRendering?:number | string; in2?:number | string; in?:string; intercept?:number | string; k1?:number | string; k2?:number | string; k3?:number | string; k4?:number | string; k?:number | string; kernelMatrix?:number | string; kernelUnitLength?:number | string; kerning?:number | string; keyPoints?:number | string; keySplines?:number | string; keyTimes?:number | string; lengthAdjust?:number | string; letterSpacing?:number | string; lightingColor?:number | string; limitingConeAngle?:number | string; local?:number | string; markerEnd?:string; markerHeight?:number | string; markerMid?:string; markerStart?:string; markerUnits?:number | string; markerWidth?:number | string; mask?:string; maskContentUnits?:number | string; maskUnits?:number | string; mathematical?:number | string; mode?:number | string; numOctaves?:number | string; offset?:number | string; opacity?:number | string; operator?:number | string; order?:number | string; orient?:number | string; orientation?:number | string; origin?:number | string; overflow?:number | string; overlinePosition?:number | string; overlineThickness?:number | string; paintOrder?:number | string; panose1?:number | string; pathLength?:number | string; patternContentUnits?:string; patternTransform?:number | string; patternUnits?:string; pointerEvents?:number | string; points?:string; pointsAtX?:number | string; pointsAtY?:number | string; pointsAtZ?:number | string; preserveAlpha?:number | string; preserveAspectRatio?:string; primitiveUnits?:number | string; r?:number | string; radius?:number | string; refX?:number | string; refY?:number | string; renderingIntent?:number | string; repeatCount?:number | string; repeatDur?:number | string; requiredExtensions?:number | string; requiredFeatures?:number | string; restart?:number | string; result?:string; rotate?:number | string; rx?:number | string; ry?:number | string; scale?:number | string; seed?:number | string; shapeRendering?:number | string; slope?:number | string; spacing?:number | string; specularConstant?:number | string; specularExponent?:number | string; speed?:number | string; spreadMethod?:string; startOffset?:number | string; stdDeviation?:number | string; stemh?:number | string; stemv?:number | string; stitchTiles?:number | string; stopColor?:string; stopOpacity?:number | string; strikethroughPosition?:number | string; strikethroughThickness?:number | string; string?:number | string; stroke?:string; strokeDasharray?:string | number; strokeDashoffset?:string | number; strokeLinecap?:"butt" | "round" | "square" | "inherit"; strokeLinejoin?:"miter" | "round" | "bevel" | "inherit"; strokeMiterlimit?:string; strokeOpacity?:number | string; strokeWidth?:number | string; surfaceScale?:number | string; systemLanguage?:number | string; tableValues?:number | string; targetX?:number | string; targetY?:number | string; textAnchor?:string; textDecoration?:number | string; textLength?:number | string; textRendering?:number | string; to?:number | string; transform?:string; u1?:number | string; u2?:number | string; underlinePosition?:number | string; underlineThickness?:number | string; unicode?:number | string; unicodeBidi?:number | string; unicodeRange?:number | string; unitsPerEm?:number | string; vAlphabetic?:number | string; values?:string; vectorEffect?:number | string; version?:string; vertAdvY?:number | string; vertOriginX?:number | string; vertOriginY?:number | string; vHanging?:number | string; vIdeographic?:number | string; viewBox?:string; viewTarget?:number | string; visibility?:number | string; vMathematical?:number | string; widths?:number | string; wordSpacing?:number | string; writingMode?:number | string; x1?:number | string; x2?:number | string; x?:number | string; xChannelSelector?:string; xHeight?:number | string; xlinkActuate?:string; xlinkArcrole?:string; xlinkHref?:string; xlinkRole?:string; xlinkShow?:string; xlinkTitle?:string; xlinkType?:string; xmlBase?:string; xmlLang?:string; xmlns?:string; xmlnsXlink?:string; xmlSpace?:string; y1?:number | string; y2?:number | string; y?:number | string; yChannelSelector?:string; z?:number | string; zoomAndPan?:string; } interface PathAttributes { d:string; } interface EventHandler<E extends Event> { (event:E):void; } type ClipboardEventHandler = EventHandler<ClipboardEvent>; type CompositionEventHandler = EventHandler<CompositionEvent>; type DragEventHandler = EventHandler<DragEvent>; type FocusEventHandler = EventHandler<FocusEvent>; type KeyboardEventHandler = EventHandler<KeyboardEvent>; type MouseEventHandler = EventHandler<MouseEvent>; type TouchEventHandler = EventHandler<TouchEvent>; type UIEventHandler = EventHandler<UIEvent>; type WheelEventHandler = EventHandler<WheelEvent>; type AnimationEventHandler = EventHandler<AnimationEvent>; type TransitionEventHandler = EventHandler<TransitionEvent>; type GenericEventHandler = EventHandler<Event>; interface DOMAttributes { // Image Events onLoad?:GenericEventHandler; // Clipboard Events onCopy?:ClipboardEventHandler; onCut?:ClipboardEventHandler; onPaste?:ClipboardEventHandler; // Composition Events onCompositionEnd?:CompositionEventHandler; onCompositionStart?:CompositionEventHandler; onCompositionUpdate?:CompositionEventHandler; // Focus Events onFocus?:FocusEventHandler; onBlur?:FocusEventHandler; // Form Events onChange?:GenericEventHandler; onInput?:GenericEventHandler; onSearch?:GenericEventHandler; onSubmit?:GenericEventHandler; // Keyboard Events onKeyDown?:KeyboardEventHandler; onKeyPress?:KeyboardEventHandler; onKeyUp?:KeyboardEventHandler; // Media Events onAbort?:GenericEventHandler; onCanPlay?:GenericEventHandler; onCanPlayThrough?:GenericEventHandler; onDurationChange?:GenericEventHandler; onEmptied?:GenericEventHandler; onEncrypted?:GenericEventHandler; onEnded?:GenericEventHandler; onLoadedData?:GenericEventHandler; onLoadedMetadata?:GenericEventHandler; onLoadStart?:GenericEventHandler; onPause?:GenericEventHandler; onPlay?:GenericEventHandler; onPlaying?:GenericEventHandler; onProgress?:GenericEventHandler; onRateChange?:GenericEventHandler; onSeeked?:GenericEventHandler; onSeeking?:GenericEventHandler; onStalled?:GenericEventHandler; onSuspend?:GenericEventHandler; onTimeUpdate?:GenericEventHandler; onVolumeChange?:GenericEventHandler; onWaiting?:GenericEventHandler; // MouseEvents onClick?:MouseEventHandler; onContextMenu?:MouseEventHandler; onDblClick?: MouseEventHandler; onDrag?:DragEventHandler; onDragEnd?:DragEventHandler; onDragEnter?:DragEventHandler; onDragExit?:DragEventHandler; onDragLeave?:DragEventHandler; onDragOver?:DragEventHandler; onDragStart?:DragEventHandler; onDrop?:DragEventHandler; onMouseDown?:MouseEventHandler; onMouseEnter?:MouseEventHandler; onMouseLeave?:MouseEventHandler; onMouseMove?:MouseEventHandler; onMouseOut?:MouseEventHandler; onMouseOver?:MouseEventHandler; onMouseUp?:MouseEventHandler; // Selection Events onSelect?:GenericEventHandler; // Touch Events onTouchCancel?:TouchEventHandler; onTouchEnd?:TouchEventHandler; onTouchMove?:TouchEventHandler; onTouchStart?:TouchEventHandler; // UI Events onScroll?:UIEventHandler; // Wheel Events onWheel?:WheelEventHandler; // Animation Events onAnimationStart?:AnimationEventHandler; onAnimationEnd?:AnimationEventHandler; onAnimationIteration?:AnimationEventHandler; // Transition Events onTransitionEnd?:TransitionEventHandler; } interface HTMLAttributes extends DOMAttributes { // Standard HTML Attributes accept?:string; acceptCharset?:string; accessKey?:string; action?:string; allowFullScreen?:boolean; allowTransparency?:boolean; alt?:string; async?:boolean; autocomplete?:string; autofocus?:boolean; autoPlay?:boolean; capture?:boolean; cellPadding?:number | string; cellSpacing?:number | string; charSet?:string; challenge?:string; checked?:boolean; class?:string | { [key:string]: boolean }; className?:string | { [key:string]: boolean }; cols?:number; colSpan?:number; content?:string; contentEditable?:boolean; contextMenu?:string; controls?:boolean; coords?:string; crossOrigin?:string; data?:string; dateTime?:string; default?:boolean; defer?:boolean; dir?:string; disabled?:boolean; download?:any; draggable?:boolean; encType?:string; form?:string; formAction?:string; formEncType?:string; formMethod?:string; formNoValidate?:boolean; formTarget?:string; frameBorder?:number | string; headers?:string; height?:number | string; hidden?:boolean; high?:number; href?:string; hrefLang?:string; for?:string; httpEquiv?:string; icon?:string; id?:string; inputMode?:string; integrity?:string; is?:string; keyParams?:string; keyType?:string; kind?:string; label?:string; lang?:string; list?:string; loop?:boolean; low?:number; manifest?:string; marginHeight?:number; marginWidth?:number; max?:number | string; maxLength?:number; media?:string; mediaGroup?:string; method?:string; min?:number | string; minLength?:number; multiple?:boolean; muted?:boolean; name?:string; noValidate?:boolean; open?:boolean; optimum?:number; pattern?:string; placeholder?:string; poster?:string; preload?:string; radioGroup?:string; readOnly?:boolean; rel?:string; required?:boolean; role?:string; rows?:number; rowSpan?:number; sandbox?:string; scope?:string; scoped?:boolean; scrolling?:string; seamless?:boolean; selected?:boolean; shape?:string; size?:number; sizes?:string; slot?:string; span?:number; spellCheck?:boolean; src?:string; srcset?:string; srcDoc?:string; srcLang?:string; srcSet?:string; start?:number; step?:number | string; style?:any; summary?:string; tabIndex?:number; target?:string; title?:string; type?:string; useMap?:string; value?:string | string[]; width?:number | string; wmode?:string; wrap?:string; // RDFa Attributes about?:string; datatype?:string; inlist?:any; prefix?:string; property?:string; resource?:string; typeof?:string; vocab?:string; } interface IntrinsicElements { // HTML a:HTMLAttributes; abbr:HTMLAttributes; address:HTMLAttributes; area:HTMLAttributes; article:HTMLAttributes; aside:HTMLAttributes; audio:HTMLAttributes; b:HTMLAttributes; base:HTMLAttributes; bdi:HTMLAttributes; bdo:HTMLAttributes; big:HTMLAttributes; blockquote:HTMLAttributes; body:HTMLAttributes; br:HTMLAttributes; button:HTMLAttributes; canvas:HTMLAttributes; caption:HTMLAttributes; cite:HTMLAttributes; code:HTMLAttributes; col:HTMLAttributes; colgroup:HTMLAttributes; data:HTMLAttributes; datalist:HTMLAttributes; dd:HTMLAttributes; del:HTMLAttributes; details:HTMLAttributes; dfn:HTMLAttributes; dialog:HTMLAttributes; div:HTMLAttributes; dl:HTMLAttributes; dt:HTMLAttributes; em:HTMLAttributes; embed:HTMLAttributes; fieldset:HTMLAttributes; figcaption:HTMLAttributes; figure:HTMLAttributes; footer:HTMLAttributes; form:HTMLAttributes; h1:HTMLAttributes; h2:HTMLAttributes; h3:HTMLAttributes; h4:HTMLAttributes; h5:HTMLAttributes; h6:HTMLAttributes; head:HTMLAttributes; header:HTMLAttributes; hr:HTMLAttributes; html:HTMLAttributes; i:HTMLAttributes; iframe:HTMLAttributes; img:HTMLAttributes; input:HTMLAttributes; ins:HTMLAttributes; kbd:HTMLAttributes; keygen:HTMLAttributes; label:HTMLAttributes; legend:HTMLAttributes; li:HTMLAttributes; link:HTMLAttributes; main:HTMLAttributes; map:HTMLAttributes; mark:HTMLAttributes; menu:HTMLAttributes; menuitem:HTMLAttributes; meta:HTMLAttributes; meter:HTMLAttributes; nav:HTMLAttributes; noscript:HTMLAttributes; object:HTMLAttributes; ol:HTMLAttributes; optgroup:HTMLAttributes; option:HTMLAttributes; output:HTMLAttributes; p:HTMLAttributes; param:HTMLAttributes; picture:HTMLAttributes; pre:HTMLAttributes; progress:HTMLAttributes; q:HTMLAttributes; rp:HTMLAttributes; rt:HTMLAttributes; ruby:HTMLAttributes; s:HTMLAttributes; samp:HTMLAttributes; script:HTMLAttributes; section:HTMLAttributes; select:HTMLAttributes; slot:HTMLAttributes; small:HTMLAttributes; source:HTMLAttributes; span:HTMLAttributes; strong:HTMLAttributes; style:HTMLAttributes; sub:HTMLAttributes; summary:HTMLAttributes; sup:HTMLAttributes; table:HTMLAttributes; tbody:HTMLAttributes; td:HTMLAttributes; textarea:HTMLAttributes; tfoot:HTMLAttributes; th:HTMLAttributes; thead:HTMLAttributes; time:HTMLAttributes; title:HTMLAttributes; tr:HTMLAttributes; track:HTMLAttributes; u:HTMLAttributes; ul:HTMLAttributes; "var":HTMLAttributes; video:HTMLAttributes; wbr:HTMLAttributes; //SVG svg:SVGAttributes; animate:SVGAttributes; circle:SVGAttributes; clipPath:SVGAttributes; defs:SVGAttributes; ellipse:SVGAttributes; feBlend:SVGAttributes; feColorMatrix:SVGAttributes; feComponentTransfer:SVGAttributes; feComposite:SVGAttributes; feConvolveMatrix:SVGAttributes; feDiffuseLighting:SVGAttributes; feDisplacementMap:SVGAttributes; feFlood:SVGAttributes; feGaussianBlur:SVGAttributes; feImage:SVGAttributes; feMerge:SVGAttributes; feMergeNode:SVGAttributes; feMorphology:SVGAttributes; feOffset:SVGAttributes; feSpecularLighting:SVGAttributes; feTile:SVGAttributes; feTurbulence:SVGAttributes; filter:SVGAttributes; foreignObject:SVGAttributes; g:SVGAttributes; image:SVGAttributes; line:SVGAttributes; linearGradient:SVGAttributes; marker:SVGAttributes; mask:SVGAttributes; path:SVGAttributes; pattern:SVGAttributes; polygon:SVGAttributes; polyline:SVGAttributes; radialGradient:SVGAttributes; rect:SVGAttributes; stop:SVGAttributes; symbol:SVGAttributes; text:SVGAttributes; tspan:SVGAttributes; use:SVGAttributes; } interface IntrinsicAttributes { key?: string | number staticClass?: string ref?: string refInFor?: boolean slot?: string scopedSlots?: any } } }
the_stack
import * as React from 'react'; import * as actions from '../../actions'; import './index.less'; import { Button, Input, Transfer, Select } from 'antd'; import { CustomBreadcrumb, CommonHead, NavRouterLink } from '../../component/CustomComponent'; import { getCollectListColumns, collectBreadcrumb, getCollectFormColumns } from './config'; import { collectHead, empty } from '../../constants/common'; import { getServices } from '../../api/agent' import { IService } from '../../interface/agent'; import { ICollectTaskParams, ICollectTaskVo, ICollectTask, ICollectQueryFormColumns } from '../../interface/collect'; import { getCollectTask } from '../../api/collect' import { connect } from "react-redux"; import { BasicTable } from 'antd-advanced'; import { Dispatch } from 'redux'; import { judgeEmpty } from '../../lib/utils'; import { findDOMNode } from 'react-dom'; const mapStateToProps = (state: any) => ({ rdbPoints: state.resPermission.rdbPoints }) const mapDispatchToProps = (dispatch: Dispatch) => ({ setDrawerId: (drawerId: string, params?: any) => dispatch(actions.setDrawerId(drawerId, params)), }); type Props = ReturnType<typeof mapStateToProps> & ReturnType<typeof mapDispatchToProps>; @connect(mapStateToProps, mapDispatchToProps) export class CollectTaskList extends React.Component<Props> { public healthRef = null as any; public collectRef = null as any; constructor(props: any) { super(props) this.healthRef = React.createRef(); this.collectRef = React.createRef(); } public state = { loading: true, servicesList: [], collectTaskList: [], total: 0, hidefer: false, targetKeys: [], applyInput: '', direction: 'left', form: '', colectParams: { pageNo: 1, pageSize: 20, serviceIdList: [], // number[] 服务id logCollectTaskTypeList: [], // number[] 采集任务类型 0:常规流式采集 1:按指定时间范围采集 logCollectTaskHealthLevelList: [], //number[] 日志采集任务健康度 0:红 1:黄 2:绿色 logCollectTaskId: empty, // 日志采集任务id logCollectTaskName: empty, // 日志采集任务名 locCollectTaskCreateTimeEnd: empty, // 日志采集任务创建时间结束检索时间 locCollectTaskCreateTimeStart: empty, // 日志采集任务创建时间起始检索时间 } as ICollectTaskParams, } public collectListColumns() { const getData = () => this.getCollectData(this.state.colectParams); const columns = getCollectListColumns(this.props.setDrawerId, getData); return columns; } public filterApplyOption = (inputValue: any, option: any) => { return option.servicename.indexOf(inputValue) > -1; } public onApplyChange = (targetKeys: any, direction: any) => { this.setState({ targetKeys: [targetKeys] }) // this.setState({ applyInput: `已选择${targetKeys?.length}项`, hidefer: true, targetKeys, direction, }); }; public onApplySearch = (dir: any, value: any) => { // console.log('search:', dir, value); }; public onInputClick = () => { const { targetKeys, direction, servicesList } = this.state; let keys = [] as number[]; if (direction === 'right') { keys = targetKeys; } else if (direction === 'left') { if (targetKeys?.length === servicesList?.length) { keys = []; } else { keys = targetKeys; } } this.setState({ applyInput: keys?.length ? `已选择${keys?.length}项` : '', hidefer: true, targetKeys: keys, }); } public handleClickOutside(e: any) { // 组件已挂载且事件触发对象不在div内 let result = findDOMNode(this.refs.refTest)?.contains(e.target); if (!result) { this.setState({ hidefer: false }); } } public queryFormColumns() { const { servicesList, applyInput, hidefer, targetKeys, form } = this.state; const applyObj = { type: 'custom', title: '采集应用', dataIndex: 'serviceIdList', component: ( <div className='apply-box'> {/* <Input value={applyInput} placeholder='请选择' onClick={this.onInputClick} /> */} <Select // mode="multiple" onChange={this.onApplyChange} // onSearch={this.onApplyChange} > { servicesList.map((v: any) => { return <Select.Option key={v.id} value={v.id}>{v?.servicename}</Select.Option> }) } </Select> {/* <Transfer dataSource={servicesList} showSearch filterOption={this.filterApplyOption} targetKeys={targetKeys} onChange={this.onApplyChange} onSearch={this.onApplySearch} render={item => item.servicename} className="customTransfer" /> */} </div> ), }; const collectColumns = getCollectFormColumns(this.collectRef, this.healthRef, form); collectColumns.splice(0, 0, applyObj); return collectColumns; } public setServiceIdList = () => { const { servicesList, targetKeys } = this.state; const serviceIds = [] as number[]; servicesList.map((ele: IService, index) => { if (targetKeys?.includes(index as never)) { serviceIds.push(ele.id); } }); return serviceIds; } public onChangeParams = (values: ICollectQueryFormColumns, form: any) => { const { pageNo, pageSize } = this.state.colectParams; this.setState({ form, colectParams: { pageNo, pageSize, serviceIdList: this.state.targetKeys, // number[] 服务id logCollectTaskTypeList: values?.logCollectTaskTypeList || [], // number[] 采集任务类型 0:常规流式采集 1:按指定时间范围采集 logCollectTaskHealthLevelList: values?.logCollectTaskHealthLevelList || [], //number[] 日志采集任务健康度 0:红 1:黄 2:绿色 logCollectTaskId: judgeEmpty(values?.logCollectTaskId), // 日志采集任务id logCollectTaskName: values.logCollectTaskName, // 日志采集任务名 locCollectTaskCreateTimeStart: values?.locCollectTaskCreateTime?.length ? values.locCollectTaskCreateTime[0]?.valueOf() : '', locCollectTaskCreateTimeEnd: values?.locCollectTaskCreateTime?.length ? values.locCollectTaskCreateTime[1]?.valueOf() : '', } }) } public onSearchParams = () => { const { colectParams, targetKeys } = this.state; if (!colectParams.serviceIdList?.length && targetKeys?.length) { colectParams.serviceIdList = targetKeys; } this.getCollectData(this.state.colectParams); } public onResetParams = () => { const resetParams = { pageNo: 1, pageSize: 20, serviceIdList: [], // number[] 服务id logCollectTaskTypeList: [], // number[] 采集任务类型 0:常规流式采集 1:按指定时间范围采集 logCollectTaskHealthLevelList: [], //number[] 日志采集任务健康度 0:红 1:黄 2:绿色 logCollectTaskId: empty, // 日志采集任务id logCollectTaskName: empty, // 日志采集任务名 locCollectTaskCreateTimeEnd: empty, // 日志采集任务创建时间结束检索时间 locCollectTaskCreateTimeStart: empty, // 日志采集任务创建时间起始检索时间 } as ICollectTaskParams; this.setState({ colectParams: resetParams, targetKeys: [], applyInput: '', direction: 'left', }); this.getCollectData(resetParams); } public onPageChange = (current: number, size: number | undefined) => { const { colectParams, targetKeys } = this.state; const pageParams = { serviceIdList: targetKeys, logCollectTaskTypeList: colectParams?.logCollectTaskTypeList || [], logCollectTaskHealthLevelList: colectParams?.logCollectTaskHealthLevelList || [], logCollectTaskId: colectParams?.logCollectTaskId, logCollectTaskName: colectParams?.logCollectTaskName, locCollectTaskCreateTimeStart: colectParams?.locCollectTaskCreateTimeStart, locCollectTaskCreateTimeEnd: colectParams?.locCollectTaskCreateTimeEnd, } as ICollectTaskParams; this.setState({ colectParams: pageParams }); this.getCollectData(pageParams, current, size); } public getCollectData = (params: ICollectTaskParams, current?: number, size?: number) => { params.pageNo = current || 1; params.pageSize = size || 20; this.setState({ loading: true }); getCollectTask(params).then((res: ICollectTaskVo) => { const data = res?.resultSet?.map((ele: ICollectTask, index: number) => { return { key: index, ...ele } }); this.setState({ collectTaskList: data, loading: false, total: res.total, }); }).catch((err: any) => { this.setState({ loading: false }); }); } public getServicesData = () => { getServices().then((res: IService[]) => { const data = res.map((ele, index) => { return { ...ele, key: index, }; }); this.setState({ servicesList: data }); }).catch((err: any) => { // console.log(err); }); } public componentWillUnmount = () => { this.setState = () => { return }; document.removeEventListener('mousedown', (e) => this.handleClickOutside(e), false); } public componentDidMount() { const { colectParams } = this.state; this.getCollectData(colectParams); this.getServicesData(); document.addEventListener('mousedown', (e) => this.handleClickOutside(e), false); } public render() { const { loading, collectTaskList, total } = this.state; const { pageNo, pageSize } = this.state.colectParams; return ( <> <CustomBreadcrumb btns={collectBreadcrumb} /> <div className="list collect-list page-wrapper"> <CommonHead heads={collectHead} /> <BasicTable rowKey='logCollectTaskId' showReloadBtn={false} showQueryCollapseButton={true} loading={loading} reloadBtnPos="left" reloadBtnType="btn" filterType="none" hideContentBorder={true} showSearch={false} columns={this.collectListColumns()} dataSource={collectTaskList} isQuerySearchOnChange={false} queryFormColumns={this.queryFormColumns()} pagination={{ current: pageNo, pageSize: pageSize, total, showQuickJumper: true, showSizeChanger: true, pageSizeOptions: ['10', '20', '50', '100', '200', '500'], onChange: (current, size) => this.onPageChange(current, size), onShowSizeChange: (current, size) => this.onPageChange(current, size), showTotal: () => `共 ${total} 条`, }} queryFormProps={{ searchText: '查询', resetText: '重置', onChange: this.onChangeParams, onSearch: this.onSearchParams, onReset: this.onResetParams, }} customHeader={ <div className="t-btn"> <Button type="primary"> <NavRouterLink needToolTip element={'新增任务'} href="/collect/add-task" /> </Button> </div> } /> </div> </> ); } };
the_stack
import * as widgets from '@jupyter-widgets/base'; import {cloneDeep, extend, includes as contains, each, times, map, unzip as transpose} from 'lodash'; import {semver_range} from './version'; import {RendererModel} from './renderer'; import {ipysheet_init_cell_type} from './widget_cell_type' // @ts-ignore import Handsontable from 'handsontable'; // CSS import 'pikaday/css/pikaday.css'; import 'handsontable/dist/handsontable.min.css'; import '../style/base.css'; ipysheet_init_cell_type(); let CellRangeModel = widgets.WidgetModel.extend({ defaults: function() { return extend(CellRangeModel.__super__.defaults.call(this), { _model_name : 'CellRangeModel', _model_module : 'ipysheet', _model_module_version : semver_range, value : null, row_start: 1, column_start: 1, row_end: 1, column_end: 1, type: null, //'text', name: null, style: {}, renderer: null, read_only: false, choice: null, squeeze_row: true, squeeze_column: true, transpose: false, numeric_format: '0.000', date_format: 'YYYY/MM/DD', time_format: 'h:mm:ss a' }); }, }, { serializers: extend({ value: { deserialize: widgets.unpack_models } }, widgets.WidgetModel.serializers) }); let SheetModel = widgets.DOMWidgetModel.extend({ defaults: function() { return extend(SheetModel.__super__.defaults.call(this), { _model_name : 'SheetModel', _view_name : 'SheetView', _model_module : 'ipysheet', _view_module : 'ipysheet', _model_module_version : semver_range, _view_module_version : semver_range, rows: 3, columns: 4, cells: [], named_cells: {}, row_headers: true, column_headers: true, stretch_headers: 'all', column_width: null, column_resizing: true, row_resizing: true, search_token: '' }); }, initialize : function () { SheetModel.__super__.initialize.apply(this, arguments); this.data = [[]]; this.update_data_grid(false); this._updating_grid = false; this.on('change:rows change:columns', this.update_data_grid, this); this.on('change:cells', this.on_change_cells, this); this.on('data_change', this.grid_to_cell, this); each(this.get('cells'), (cell) => this.cell_bind(cell)) this.cells_to_grid() }, on_change_cells: function() { this._updating_grid = true; try { let previous_cells = this.previous('cells'); let cells = this.get('cells'); for(let i = 0; i < cells.length; i++) { let cell = cells[i]; if(!contains(previous_cells, cell)) { this.cell_bind(cell); } } this.cells_to_grid() //this.save_changes(); } finally { this._updating_grid = false; } this.grid_to_cell() }, cell_bind: function(cell) { cell.on_some_change(['value', 'style', 'type', 'renderer', 'read_only', 'choice', 'numeric_format', 'date_format', 'time_format'], () => { this.cells_to_grid(); }); }, cells_to_grid: function() { this.data = [[]]; this.update_data_grid(false); each(this.get('cells'), (cell) => { this._cell_data_to_grid(cell) }); this.trigger('data_change'); }, _cell_data_to_grid: function(cell) { cell.get('value'); for(let i = cell.get('row_start'); i <= cell.get('row_end'); i++) { for(let j = cell.get('column_start'); j <= cell.get('column_end'); j++) { let value = cell.get('value'); let cell_row = i - cell.get('row_start'); let cell_col = j - cell.get('column_start'); if((i >= this.data.length) || (j >= this.data[i].length)) continue; // skip cells that are out of the sheet let cell_data = this.data[i][j]; if(cell.get('transpose')) { if(!cell.get('squeeze_column')) value = value[cell_col] if(!cell.get('squeeze_row')) value = value[cell_row] } else { if(!cell.get('squeeze_row')) value = value[cell_row] if(!cell.get('squeeze_column')) value = value[cell_col] } if (value != null) cell_data.value = value; if (cell.get('type') != null) cell_data.options['type'] = cell.get('type'); if (cell.get('renderer') != null) cell_data.options['renderer'] = cell.get('renderer'); if (cell.get('read_only') != null) cell_data.options['readOnly'] = cell.get('read_only'); if (cell.get('choice') != null) cell_data.options['source'] = cell.get('choice') if (cell.get('numeric_format') && cell.get('type') == 'numeric') cell_data.options['numericFormat'] = {'pattern': cell.get('numeric_format')}; if (cell.get('date_format') && cell.get('type') == 'date') { cell_data.options['correctFormat'] = true; cell_data.options['dateFormat'] = cell.get('date_format') || cell_data.options['dateFormat']; } if (cell.get('time_format') && cell.get('type') == 'time') { cell_data.options['correctFormat'] = true; cell_data.options['timeFormat'] = cell.get('time_format') || cell_data.options['timeFormat']; } cell_data.options['style'] = extend({}, cell_data.options['style'], cell.get('style')); } } }, grid_to_cell: function() { if(this._updating_grid) { return; } this._updating_grid = true; try { each(this.get('cells'), (cell) => { let rows: any[] = []; for(let i = cell.get('row_start'); i <= cell.get('row_end'); i++) { let row: any[] = []; for(let j = cell.get('column_start'); j <= cell.get('column_end'); j++) { //let cell_row = i - cell.get('row_start'); //let cell_col = j - cell.get('column_start'); if((i >= this.data.length) || (j >= this.data[i].length)) continue; // skip cells that are out of the sheet let cell_data = this.data[i][j]; row.push(cell_data.value) /*cell.set('value', cell_data.value); cell.set('type', cell_data.options['type']); cell.set('style', cell_data.options['style']); cell.set('renderer', cell_data.options['renderer']); cell.set('read_only', cell_data.options['readOnly']); cell.set('choice', cell_data.options['source']); cell.set('format', cell_data.options['format']);*/ } if(cell.get('squeeze_column')) { row = row[0]; } rows.push(row); } if(cell.get('squeeze_row')) { rows = rows[0]; } if(cell.get('transpose')) { cell.set('value', transpose(rows)) } else { cell.set('value', rows) } cell.save_changes(); }); } finally { this._updating_grid = false; } }, update_data_grid: function(trigger_change_event=true) { // create a row x column array of arrays filled with null let rows = this.get('rows'); let columns = this.get('columns'); let empty_cell = () => { return {value: null, options:{}}; }; let empty_row = () => { return times(this.get('columns'), empty_cell); }; if(rows < this.data.length) { this.data = this.data.slice(0, rows); } else if(rows > this.data.length) { for(let i = this.data.length; i < rows; i++) { this.data.push(empty_row()); } } for(let i = 0; i < rows; i++) { let row = this.data[i]; if(columns < row.length) { row = row.slice(0, columns); } else if(columns > row.length) { for(let j = row.length; j < columns; j++) { row.push(empty_cell()); } } this.data[i] = row; } if (trigger_change_event) { this.trigger('data_change'); } } }, { serializers: extend({ cells: { deserialize: widgets.unpack_models }, data: { deserialize: widgets.unpack_models } }, widgets.DOMWidgetModel.serializers) }); // go from 2d array with objects to a 2d grid containing just attribute `attr` from those objects let extract2d = function(grid, attr) { return map(grid, function(column) { return map(column, function(value) { return value[attr]; }); }); }; // inverse of above let put_values2d = function(grid, values) { // TODO: the Math.min should not be needed, happens with the custom-build for(let i = 0; i < Math.min(grid.length, values.length); i++) { for(let j = 0; j < Math.min(grid[i].length, values[i].length); j++) { grid[i][j].value = values[i][j]; } } }; // calls the original renderer and then applies custom styling (Handsontable.renderers as any).registerRenderer('styled', function customRenderer(hotInstance, td, row, column, prop, value, cellProperties) { let name = cellProperties.original_renderer || cellProperties.type || 'text'; let original_renderer = (Handsontable.renderers as any).getRenderer(name); original_renderer.apply(this, arguments); each(cellProperties.style, function(value, key) { td.style[key] = value; }); }); let SheetView = widgets.DOMWidgetView.extend({ render: function() { // this.widget_view_promises = {} this.widget_views = {} this.el.classList.add("handsontable"); this.el.classList.add("jupyter-widgets"); this.table_container = document.createElement('div'); this.el.appendChild(this.table_container); // promise used for unittesting this._table_constructed = this.displayed.then(async () => { this.hot = await this._build_table(); this.model.on('data_change', this.on_data_change, this); this.model.on('change:column_headers change:row_headers', this._update_hot_settings, this); this.model.on('change:stretch_headers change:column_width', this._update_hot_settings, this); this.model.on('change:column_resizing change:row_resizing', this._update_hot_settings, this); this.model.on('change:search_token', this._search, this); this._search() }); }, processPhosphorMessage: function(msg) { SheetView.__super__.processPhosphorMessage.apply(this, arguments); switch (msg.type) { case 'resize': case 'after-show': this._table_constructed.then(() => { this.hot.render(); // working around table not re-rendering fully upon resize. this.hot._refreshBorders(null); }); break; } }, async _build_widgets_views() { let data = this.model.data; let rows = data.length; let cols = data[0].length; let widget_view_promises = {} for (let row = 0; row < rows; row++) { for (let col = 0; col < cols; col++) { let idx = [row, col].join(); if (data[row][col] && data[row][col].options['type'] == 'widget') { let widget = data[row][col].value; let previous_view = this.widget_views[idx]; if (previous_view) { if(previous_view.model.cid == widget.cid) { // if this a proper comparison? widget_view_promises[idx] = Promise.resolve(previous_view) } else { previous_view.remove() previous_view = null; } } if (!previous_view && widget) { widget_view_promises[idx] = this.create_child_view(widget); } } } } for (let key in this.widget_views) { if(this.widget_views.hasOwnProperty(key)) { // Ugly, this should be properly done let [row, col] = String(key).split(',').map(x => parseInt(x)); let widget_view = this.widget_views[key]; if(data[row][col] && data[row][col].value && data[row][col].value.cid == widget_view.model.cid) { // good, the previous widget_view should be reused } else { // we have a leftover view from the previous run widget_view.remove(); } } } this.widget_views = await widgets.resolvePromisesDict(widget_view_promises) }, async _build_table() { await this._build_widgets_views() return new Handsontable(this.table_container, extend({ data: this._get_cell_data(), rowHeaders: true, colHeaders: true, search: true, columnSorting: { sortEmptyCells: false, indicator: true, headerAction: true, compareFunctionFactory: this._compareFunctionFactory }, cells: (...args) => this._cell(...args), afterChange: (changes, source) => { this._on_change(changes, source); }, afterRemoveCol: (changes, source) => { this._on_change_grid(changes, source); }, afterRemoveRow: (changes, source) => { this._on_change_grid(changes, source); } }, this._hot_settings())); }, _compareFunctionFactory: function(sortOrder, columnMeta) { return function(value, nextValue) { let a, b; if (sortOrder == 'desc') { a = value; b = nextValue; } else { a = nextValue; b = value; } if (a instanceof widgets.WidgetModel) { a = a.get("value"); } if (b instanceof widgets.WidgetModel) { b = b.get("value"); } if (a == undefined || b == undefined) { return 0; } if (a < b) { return -1; } if (a > b) { return 1; } return 0; } }, _update_hot_settings: function() { this.hot.updateSettings(this._hot_settings()); }, _hot_settings: function() { return { colHeaders: this.model.get('column_headers'), rowHeaders: this.model.get('row_headers'), stretchH: this.model.get('stretch_headers'), colWidths: this.model.get('column_width') || undefined, manualColumnResize: this.model.get('column_resizing'), manualRowResize: this.model.get('row_resizing') }; }, _search: function(render=true, ignore_empty_string=false) { let token = this.model.get('search_token'); if (ignore_empty_string && token == '') { return; } this.hot.getPlugin('search').query(token); if (render) { this.hot.render(); } }, _get_cell_data: function() { return extract2d(this.model.data, 'value'); }, _cell: function(row, col) { let data = this.model.data; let cellProperties = cloneDeep(data[row][col].options); if(!((row < data.length) && (col < data[row].length))) { console.error('cell out of range'); } if(cellProperties['type'] == null) delete cellProperties['type']; if(cellProperties['style'] == null) delete cellProperties['style']; if(cellProperties['source'] == null) delete cellProperties['source']; if('renderer' in cellProperties) cellProperties.original_renderer = cellProperties['renderer']; cellProperties.renderer = 'styled'; if(this.widget_views[[row, col].join()]) { cellProperties.widget_view = this.widget_views[[row, col].join()] } return cellProperties; }, _on_change_grid: function(changes, source) { let data = this.hot.getSourceDataArray(); this.model.set({'rows': data.length, 'columns': data[0].length}); this.model.save_changes(); }, _on_change: function(changes, source) { if(this.hot === undefined || source == 'loadData' || source == 'ObserveChanges.change') { return; } if(source == 'alter') { let data = this.hot.getSourceDataArray(); this.model.set({'rows': data.length, 'columns': data[0].length}); this.model.save_changes(); return; } //this.hot.validateCells() //* //this.hot.validateCells(_.bind(function(valid){ // console.log('valid?', valid) // if(valid) { let data = this.model.data; let value_data = this.hot.getSourceDataArray(); put_values2d(data, value_data); this.model.trigger('data_change'); // } //}, this)) /**/ }, on_data_change: function() { // we create a promise here such that the unittests can wait till the data is really set this._last_data_set = new Promise(async (resolve, reject) => { let data = extract2d(this.model.data, 'value'); let rows = data.length; let cols = data[0].length; let rows_previous = this.hot.countRows(); let cols_previous = this.hot.countCols(); //* if(rows > rows_previous) { this.hot.alter('insert_row', rows-1, rows-rows_previous); } if(rows < this.hot.countRows()) { this.hot.alter('remove_row', rows-1, rows_previous-rows); } if(cols > cols_previous) { this.hot.alter('insert_col', cols-1, cols-cols_previous); } if(cols < cols_previous) { this.hot.alter('remove_col', cols-1, cols_previous-cols); }/**/ await this._build_widgets_views() this.hot.loadData(data); // if headers are not shows, loadData will make them show again, toggling // will fix this (handsontable bug?) this.hot.updateSettings({colHeaders: true, rowHeaders: true}); this.hot.updateSettings({ colHeaders: this.model.get('column_headers'), rowHeaders: this.model.get('row_headers') }); this._search(false, true); this.hot.render(); resolve(undefined); }) }, set_cell: function(row, column, value) { this.hot.setDataAtCell(row, column, value); }, get_cell: function(row, column) { return this.hot.getDataAtCell(row, column); } }); export { SheetModel, SheetView, CellRangeModel, RendererModel };
the_stack
import React from "react"; import {fireEvent, render, wait, cleanup, screen} from "@testing-library/react"; import Steps from "./steps"; import axiosMock from "axios"; import mocks from "../../api/__mocks__/mocks.data"; import data from "../../assets/mock-data/curation/steps.data"; import StepsConfig from "../../config/steps.config"; import {ErrorTooltips} from "../../config/tooltips.config"; jest.mock("axios"); describe("Steps settings component", () => { beforeEach(() => { mocks.advancedAPI(axiosMock); }); afterEach(() => { jest.clearAllMocks(); cleanup(); }); test("Verify rendering of edit Load step, tab switching, discard dialog on cancel, saving", async () => { const {baseElement, getByText, getByLabelText, getAllByLabelText, getByPlaceholderText} = render( <Steps {...data.editLoad} /> ); expect(getByText("Loading Step Settings")).toBeInTheDocument(); expect(getByLabelText("Close")).toBeInTheDocument(); // Default Basic tab expect(getByText("Basic").closest("div")).toHaveClass("ant-tabs-tab-active"); expect(getByText("Advanced").closest("div")).not.toHaveClass("ant-tabs-tab-active"); expect(baseElement.querySelector("#name")).toHaveValue("AdvancedLoad"); // Other Basic settings details tested in create-edit-*.test.tsx // Switch to Advanced tab await wait(() => { fireEvent.click(getByText("Advanced")); }); expect(getByText("Basic").closest("div")).not.toHaveClass("ant-tabs-tab-active"); expect(getByText("Advanced").closest("div")).toHaveClass("ant-tabs-tab-active"); expect(getByPlaceholderText("Please enter target permissions")).toHaveValue("data-hub-common,read,data-hub-common,update"); // Other Advanced settings details tested in advanced-settings.test.tsx // Change form content getByPlaceholderText("Please enter target permissions").focus(); fireEvent.change(getByPlaceholderText("Please enter target permissions"), {target: {value: "data-hub-common,read"}}); expect(getByPlaceholderText("Please enter target permissions")).toHaveValue("data-hub-common,read"); getByPlaceholderText("Please enter target permissions").blur(); // Switch to Basic tab and cancel await wait(() => { fireEvent.click(getByText("Basic")); }); expect(getByText("Basic").closest("div")).toHaveClass("ant-tabs-tab-active"); expect(getByText("Advanced").closest("div")).not.toHaveClass("ant-tabs-tab-active"); fireEvent.click(getAllByLabelText("Cancel")[0]); // Verify discard dialog expect(getByText("Discard changes?")).toBeInTheDocument(); expect(getByText("Yes")).toBeInTheDocument(); expect(getByText("No")).toBeInTheDocument(); const noButton = getByText("No"); noButton.onclick = jest.fn(); fireEvent.click(noButton); expect(noButton.onclick).toHaveBeenCalledTimes(1); const yesButton = getByText("Yes"); yesButton.onclick = jest.fn(); fireEvent.click(yesButton); expect(yesButton.onclick).toHaveBeenCalledTimes(1); // Save await wait(() => { fireEvent.click(getAllByLabelText("Save")[0]); }); const saveButton = getAllByLabelText("Save")[0]; saveButton.onclick = jest.fn(); fireEvent.click(saveButton); expect(saveButton.onclick).toHaveBeenCalledTimes(1); }); test("Verify rendering of edit Mapping step, tab disabling on form error, discard changes dialog on close", async () => { const {getByText, getByLabelText, getByPlaceholderText, getByTestId} = render( <Steps {...data.editMapping} /> ); expect(getByText("Mapping Step Settings")).toBeInTheDocument(); expect(getByLabelText("Close")).toBeInTheDocument(); // Mapping step has link to Details const detailsLink = getByLabelText("stepDetails"); detailsLink.onclick = jest.fn(); fireEvent.click(detailsLink); expect(detailsLink.onclick).toHaveBeenCalledTimes(1); // Default Basic tab expect(getByText("Basic").closest("div")).toHaveClass("ant-tabs-tab-active"); expect(getByText("Advanced").closest("div")).not.toHaveClass("ant-tabs-tab-active"); // Switch to Advanced tab, create error, verify other tab disabled await wait(() => { fireEvent.click(getByText("Advanced")); }); expect(getByPlaceholderText("Please enter target permissions")).toHaveValue("data-hub-common,read,data-hub-common,update"); fireEvent.change(getByPlaceholderText("Please enter target permissions"), {target: {value: "bad-value"}}); expect(getByPlaceholderText("Please enter target permissions")).toHaveValue("bad-value"); fireEvent.blur(getByPlaceholderText("Please enter target permissions")); //TODO: Test with reference rather than hardcoded string. expect(getByTestId("validationError")).toHaveTextContent("The format of the string is incorrect. The required format is role,capability,role,capability,...."); expect(getByText("Basic").closest("div")).toHaveClass("ant-tabs-tab-disabled"); fireEvent.mouseOver(getByText("Basic")); wait(() => expect(screen.getByText(ErrorTooltips.disabledTab)).toBeInTheDocument()); // Fix error, verify other tab enabled getByPlaceholderText("Please enter target permissions").focus(); fireEvent.change(getByPlaceholderText("Please enter target permissions"), {target: {value: "data-hub-common,read"}}); expect(getByPlaceholderText("Please enter target permissions")).toHaveValue("data-hub-common,read"); getByPlaceholderText("Please enter target permissions").blur(); expect(getByTestId("validationError")).toHaveTextContent(""); expect(getByText("Basic").closest("div")).not.toHaveClass("ant-tabs-tab-disabled"); // Close dialog, verify discard changes confirm dialog await wait(() => { fireEvent.click(getByLabelText("Close")); }); const yesButton = screen.getByRole("button", { name: /Yes/i }); const noButton = screen.getByRole("button", { name: /No/i }); expect(getByText("Discard changes?")).toBeInTheDocument(); expect(yesButton).toBeInTheDocument(); expect(noButton).toBeInTheDocument(); noButton.onclick = jest.fn(); fireEvent.click(noButton); expect(noButton.onclick).toHaveBeenCalledTimes(1); yesButton.onclick = jest.fn(); fireEvent.click(yesButton); expect(yesButton.onclick).toHaveBeenCalledTimes(1); }); test("Verify rendering of edit Matching step", async () => { const {getByText, getByLabelText} = render( <Steps {...data.editMatching} /> ); expect(getByText("Matching Step Settings")).toBeInTheDocument(); expect(getByLabelText("Close")).toBeInTheDocument(); }); test("Verify rendering of edit Merging step", async () => { const {getByText, getByLabelText, getByTestId, queryByText} = render( <Steps {...data.editMerging} /> ); expect(getByText("Merging Step Settings")).toBeInTheDocument(); expect(getByLabelText("Close")).toBeInTheDocument(); // Additional collection change doesn't trigger Discard Changes alert (DHFPROD-6660) await wait(() => { fireEvent.click(getByText("Advanced")); }); fireEvent.click(getByTestId("onMerge-edit")); await wait(() => { expect(getByLabelText("additionalColl-select-onMerge")).toBeInTheDocument(); }); let collectionInput = getByLabelText("additionalColl-select-onMerge").getElementsByTagName("input").item(0)!; fireEvent.input(collectionInput, {target: {value: "newCollection"}}); fireEvent.keyDown(collectionInput, {keyCode: 13, key: "Enter"}); fireEvent.click(getByTestId("onMerge-keep")); expect(getByText("newCollection")).toBeInTheDocument(); fireEvent.click(getByTestId("AdvancedMatching-cancel-settings")); expect(queryByText("Discard changes?")).not.toBeInTheDocument(); }); test("Verify rendering of Custom step", async () => { const {getByText, getByLabelText} = render( <Steps {...data.editCustom} /> ); expect(getByText("Custom Step Settings")).toBeInTheDocument(); expect(getByLabelText("Close")).toBeInTheDocument(); }); test("Verify rendering of new Load step", async () => { const testName = "stepName"; // New non-mapping steps have the following default collections: Step Name const {getByText, getByLabelText, getByPlaceholderText, getByTestId} = render( <Steps {...data.newLoad} /> ); expect(getByText("New Loading Step")).toBeInTheDocument(); expect(getByLabelText("Close")).toBeInTheDocument(); // Advanced tab disabled since Basic tab has empty required fields expect(getByText("Basic").closest("div")).toHaveClass("ant-tabs-tab-active"); expect(getByText("Advanced").closest("div")).toHaveClass("ant-tabs-tab-disabled"); // Enter required name const nameField = getByPlaceholderText("Enter name"); expect(nameField).toBeInTheDocument(); nameField.focus(); fireEvent.change(nameField, {target: {value: testName}}); expect(nameField).toHaveValue(testName); nameField.blur(); // Switch to enabled Advanced tab, check default collections await wait(() => { fireEvent.click(getByText("Advanced")); }); expect(getByTestId("defaultCollections-" + testName)).toBeInTheDocument(); // Check other defaults expect(getByText("Target Database")).toBeInTheDocument(); expect(getByText(StepsConfig.stagingDb)).toBeInTheDocument(); expect(getByText("Target Collections")).toBeInTheDocument(); const targetColl = document.querySelector((".formItemTargetCollections .ant-select-search__field"))!; expect(targetColl).toBeEmpty(); expect(getByText("Target Permissions")).toBeInTheDocument(); expect(getByPlaceholderText("Please enter target permissions")).toHaveValue(StepsConfig.defaultTargetPerms); expect(getByText("Provenance Granularity")).toBeInTheDocument(); expect(getByText("Off")).toBeInTheDocument(); expect(getByText("Batch Size")).toBeInTheDocument(); expect(getByPlaceholderText("Please enter batch size")).toHaveValue(StepsConfig.defaultBatchSize.toString()); expect(getByLabelText("headers-textarea")).toBeEmpty(); // Open text areas that are closed by default fireEvent.click(getByText("Interceptors")); expect(getByLabelText("interceptors-textarea")).toBeEmpty(); fireEvent.click(getByText("Custom Hook")); expect(getByLabelText("customHook-textarea")).toBeEmpty(); }); test("Verify rendering of new Mapping step", async () => { const testName = "stepName"; const testColl = "testCollection"; const testEntity = "entityName"; const {getByText, getByLabelText, getByPlaceholderText, getByTestId} = render( <Steps {...data.newMapping} /> ); expect(getByText("New Mapping Step")).toBeInTheDocument(); expect(getByLabelText("Close")).toBeInTheDocument(); // Advanced tab disabled since Basic tab has empty required fields expect(getByText("Basic").closest("div")).toHaveClass("ant-tabs-tab-active"); expect(getByText("Advanced").closest("div")).toHaveClass("ant-tabs-tab-disabled"); // Enter required name const nameField = getByPlaceholderText("Enter name"); expect(nameField).toBeInTheDocument(); nameField.focus(); fireEvent.change(nameField, {target: {value: testName}}); expect(nameField).toHaveValue(testName); nameField.blur(); // Enter required source collection const collInput = document.querySelector(("#collList .ant-input"))!; fireEvent.change(collInput, {target: {value: testColl}}); expect(collInput).toHaveValue(testColl); // Switch to enabled Advanced tab, check default collections fireEvent.click(getByText("Advanced")); expect(getByTestId("defaultCollections-" + testName)).toBeInTheDocument(); expect(getByTestId("defaultCollections-" + testEntity)).toBeInTheDocument(); // Check other defaults expect(getByText("Source Database")).toBeInTheDocument(); expect(getByText(StepsConfig.stagingDb)).toBeInTheDocument(); expect(getByText("Target Database")).toBeInTheDocument(); expect(getByText(StepsConfig.finalDb)).toBeInTheDocument(); expect(getByText("Target Permissions")).toBeInTheDocument(); expect(getByPlaceholderText("Please enter target permissions")).toHaveValue(StepsConfig.defaultTargetPerms); expect(getByText("Target Format")).toBeInTheDocument(); expect(getByText(StepsConfig.defaultTargetFormat)).toBeInTheDocument(); expect(getByText("Provenance Granularity")).toBeInTheDocument(); expect(getByText("Off")).toBeInTheDocument(); expect(getByText("Entity Validation")).toBeInTheDocument(); expect(getByText("Do not validate")).toBeInTheDocument(); expect(getByText("Batch Size")).toBeInTheDocument(); expect(getByPlaceholderText("Please enter batch size")).toHaveValue(StepsConfig.defaultBatchSize.toString()); expect(getByLabelText("headers-textarea")).toBeEmpty(); // Open text areas that are closed by default fireEvent.click(getByText("Interceptors")); expect(getByLabelText("interceptors-textarea")).toBeEmpty(); fireEvent.click(getByText("Custom Hook")); expect(getByLabelText("customHook-textarea")).toBeEmpty(); }); test("Verify rendering of new Matching step", async () => { const testName = "stepName"; const testColl = "testCollection"; const {getByText, getAllByText, getByLabelText, getByPlaceholderText, getByTestId} = render( <Steps {...data.newMatching} /> ); expect(getByText("New Matching Step")).toBeInTheDocument(); expect(getByLabelText("Close")).toBeInTheDocument(); // Advanced tab disabled since Basic tab has empty required fields expect(getByText("Basic").closest("div")).toHaveClass("ant-tabs-tab-active"); expect(getByText("Advanced").closest("div")).toHaveClass("ant-tabs-tab-disabled"); // Enter required name const nameField = getByPlaceholderText("Enter name"); expect(nameField).toBeInTheDocument(); nameField.focus(); fireEvent.change(nameField, {target: {value: testName}}); expect(nameField).toHaveValue(testName); nameField.blur(); // Enter required source collection const collInput = document.querySelector(("#collList .ant-input"))!; fireEvent.change(collInput, {target: {value: testColl}}); expect(collInput).toHaveValue(testColl); // Switch to enabled Advanced tab, check default collections fireEvent.click(getByText("Advanced")); expect(getByTestId("defaultCollections-" + testName)).toBeInTheDocument(); // Check other defaults expect(getByText("Source Database")).toBeInTheDocument(); expect(getAllByText(StepsConfig.finalDb)[0]).toBeInTheDocument(); expect(getByText("Target Database")).toBeInTheDocument(); expect(getAllByText(StepsConfig.finalDb)[1]).toBeInTheDocument(); expect(getByText("Target Permissions")).toBeInTheDocument(); expect(getByPlaceholderText("Please enter target permissions")).toHaveValue(StepsConfig.defaultTargetPerms); expect(getByText("Provenance Granularity")).toBeInTheDocument(); expect(getByText("Off")).toBeInTheDocument(); expect(getByText("Batch Size")).toBeInTheDocument(); expect(getByPlaceholderText("Please enter batch size")).toHaveValue(StepsConfig.defaultBatchSize.toString()); // Open text areas that are closed by default fireEvent.click(getByText("Interceptors")); expect(getByLabelText("interceptors-textarea")).toBeEmpty(); fireEvent.click(getByText("Custom Hook")); expect(getByLabelText("customHook-textarea")).toBeEmpty(); }); test("Verify rendering of new Merging step", async () => { const testName = "stepName"; const testColl = "testCollection"; const {getByText, getAllByText, getByLabelText, getByPlaceholderText} = render( <Steps {...data.newMerging} /> ); expect(getByText("New Merging Step")).toBeInTheDocument(); expect(getByLabelText("Close")).toBeInTheDocument(); // Advanced tab disabled since Basic tab has empty required fields expect(getByText("Basic").closest("div")).toHaveClass("ant-tabs-tab-active"); expect(getByText("Advanced").closest("div")).toHaveClass("ant-tabs-tab-disabled"); // Enter required name const nameField = getByPlaceholderText("Enter name"); expect(nameField).toBeInTheDocument(); nameField.focus(); fireEvent.change(nameField, {target: {value: testName}}); expect(nameField).toHaveValue(testName); nameField.blur(); // Enter required source collection const collInput = document.querySelector(("#collList .ant-input"))!; fireEvent.change(collInput, {target: {value: testColl}}); expect(collInput).toHaveValue(testColl); // Switch to enabled Advanced tab, check default collections fireEvent.click(getByText("Advanced")); // Check other defaults expect(getByText("Source Database")).toBeInTheDocument(); expect(getAllByText(StepsConfig.finalDb)[0]).toBeInTheDocument(); expect(getByText("Target Database")).toBeInTheDocument(); expect(getAllByText(StepsConfig.finalDb)[1]).toBeInTheDocument(); expect(getByLabelText("advanced-target-collections")).toBeInTheDocument(); expect(getByText("Target Permissions")).toBeInTheDocument(); expect(getByPlaceholderText("Please enter target permissions")).toHaveValue(StepsConfig.defaultTargetPerms); expect(getByText("Provenance Granularity")).toBeInTheDocument(); expect(getByText("Off")).toBeInTheDocument(); expect(getByText("Batch Size")).toBeInTheDocument(); expect(getByPlaceholderText("Please enter batch size")).toHaveValue(StepsConfig.defaultBatchSize.toString()); // Open text areas that are closed by default fireEvent.click(getByText("Interceptors")); expect(getByLabelText("interceptors-textarea")).toBeEmpty(); fireEvent.click(getByText("Custom Hook")); expect(getByLabelText("customHook-textarea")).toBeEmpty(); }); });
the_stack
import { Long } from 'bson'; import { createSessionWebClient, DataWebRequest, SessionWebClient } from './web-client'; import { DefaultConfiguration, WebApiConfig } from '../config'; import { OAuthCredential } from '../oauth'; import { AsyncCommandResult, DefaultRes, KnownDataStatusCode } from '../request'; import { JsonUtil } from '../util'; import { FriendFindIdStruct, FriendFindUUIDStruct, FriendListStruct, FriendReqPhoneNumberStruct, FriendReqStruct, FriendSearchStruct, LessSettingsStruct, LoginTokenStruct, MoreSettingsStruct, ProfileReqStruct, } from './struct'; export class ServiceApiClient { private _client: DataWebRequest<SessionWebClient>; constructor(client: SessionWebClient) { this._client = new DataWebRequest(client); } get config(): WebApiConfig { return this._client.client.config; } set config(config: WebApiConfig) { this._client.client.config = config; } // account /** * Request more settings. Official client sends this after login * * @param {any} since Unknown */ async requestMoreSettings(since = 0): AsyncCommandResult<MoreSettingsStruct> { const res = await this._client.requestData( 'GET', // eslint-disable-next-line max-len `${this.getAccountApiPath('more_settings.json')}?since=${encodeURIComponent(since)}&lang=${encodeURIComponent(this.config.language)}`, ); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res as DefaultRes & MoreSettingsStruct, }; } /** * Request simplified settings. Official client sends this after login * * @param {any} since Unknown */ async requestLessSettings(since = 0): AsyncCommandResult<LessSettingsStruct> { const res = await this._client.requestData( 'GET', // eslint-disable-next-line max-len `${this.getAccountApiPath('less_settings.json')}?since=${encodeURIComponent(since)}&lang=${encodeURIComponent(this.config.language)}`, ); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res as DefaultRes & LessSettingsStruct, }; } async updateSettings(settings: Partial<unknown>): AsyncCommandResult { const res = await this._client.requestData('POST', this.getAccountApiPath('update_settings.json'), settings); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS }; } /** * Get one time web login token. * * Use @method requestSessionURL to get complete url. */ async requestWebLoginToken(): AsyncCommandResult<LoginTokenStruct> { const res = await this._client.requestData('GET', this.getAccountApiPath('login_token.json')); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res as DefaultRes & LoginTokenStruct, }; } /** * Create session url. Redirect to redirectURL with session info included. * * @param {string} redirectURL */ async requestSessionURL(redirectURL: string): AsyncCommandResult<string> { const res = await this.requestWebLoginToken(); if (!res.success) return res; return { status: res.status, success: true, result: ServiceApiClient.createSessionURL(res.result.token, redirectURL), }; } async canChangeUUID(uuid: string): AsyncCommandResult<DefaultRes> { const res = await this._client.requestData('POST', this.getAccountApiPath('can_change_uuid.json'), { uuid: uuid }); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res }; } async changeUUID(uuid: string): AsyncCommandResult<DefaultRes> { const res = await this._client.requestData('POST', this.getAccountApiPath('change_uuid.json'), { uuid: uuid }); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res }; } // friends async addFriend(id: Long, pa = ''): AsyncCommandResult<FriendReqStruct> { const res = await this._client.requestData( 'GET', `${this.getFriendsApiPath('add')}/${encodeURIComponent(id.toString())}.json?pa=${encodeURIComponent(pa)}`, ); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res as DefaultRes & FriendReqStruct, }; } async addFriendWithPhoneNumber( nickname: string, countryIso: string, countryCode: string, phoneNumber: string, ): AsyncCommandResult<FriendReqPhoneNumberStruct> { const res = await this._client.requestData( 'POST', this.getFriendsApiPath('add_by_phonenumber.json'), { nickname: nickname, country_iso: countryIso, country_code: countryCode, phonenumber: phoneNumber, }, ); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res as DefaultRes & FriendReqPhoneNumberStruct, }; } async removeFriend(id: Long): AsyncCommandResult<FriendReqStruct> { const res = await this._client.requestData('POST', this.getFriendsApiPath('purge.json'), { id: id.toString() }); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res as DefaultRes & FriendReqStruct, }; } async removeFriendList(idList: Long[]): AsyncCommandResult { const res = await this._client.requestData( 'POST', this.getFriendsApiPath('delete.json'), { ids: JsonUtil.stringifyLoseless(idList) }, ); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS }; } async hideFriend(id: Long, pa = ''): AsyncCommandResult { const res = await this._client.requestData( 'POST', this.getFriendsApiPath('hide.json'), { id: id.toString(), pa: pa } ); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS }; } async unhideFriend(id: Long): AsyncCommandResult { const res = await this._client.requestData('POST', this.getFriendsApiPath('unhide.json'), { id: id.toString() }); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS }; } async searchFriends(query: string, pageNum?: number, pageSize?: number): AsyncCommandResult<FriendSearchStruct> { let res; if (pageNum && pageSize) { res = await this._client.requestData( 'GET', this.getFriendsApiPath('search.json'), { query: query, page_num: pageNum, page_size: pageSize }, ); } else { res = await this._client.requestData('GET', this.getFriendsApiPath('search.json'), { query }); } return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res as DefaultRes & FriendSearchStruct, }; } async findFriendById(id: Long): AsyncCommandResult<FriendFindIdStruct> { const res = await this._client.requestData('GET', this.getFriendsApiPath(`${id.toString()}.json`)); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res as DefaultRes & FriendFindIdStruct, }; } async findFriendByUUID(uuid: string): AsyncCommandResult<FriendFindUUIDStruct> { const res = await this._client.requestData( 'POST', `${this.getFriendsApiPath('find_by_uuid.json')}`, { uuid: uuid } ); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res as DefaultRes & FriendFindUUIDStruct, }; } async requestFriendList( types: string[] = ['plus', 'normal'], eventTypes: string[] = ['create'], token: Long = Long.ZERO, ): AsyncCommandResult<FriendListStruct> { const res = await this._client.requestData( 'GET', `${this.getFriendsApiPath('list.json')}`, { type: JSON.stringify(types), event_types: JSON.stringify(eventTypes), token }, ); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res as DefaultRes & FriendListStruct, }; } async setNickname(id: Long, nickname: string): AsyncCommandResult { const res = await this._client.requestData( 'POST', this.getFriendsApiPath('nickname.json'), { id: id.toString(), nickname: nickname }, ); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS }; } async addFavoriteFriends(idList: Long[]): AsyncCommandResult { const res = await this._client.requestData( 'POST', this.getFriendsApiPath('add_favorite.json'), { ids: JsonUtil.stringifyLoseless(idList) }, ); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS }; } async removeFavoriteFriend(id: Long): AsyncCommandResult { const res = await this._client.requestData( 'POST', this.getFriendsApiPath('remove_favorite.json'), { id: id.toString() }, ); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS }; } // profile async requestMusicList(id: Long): AsyncCommandResult<DefaultRes> { const res = await this._client.requestData('GET', this.getProfileApiPath('music/list.json'), { id: id.toString() }); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res }; } async requestMyProfile(): AsyncCommandResult<ProfileReqStruct> { const res = await this._client.requestData('GET', this.getProfile3ApiPath('me.json')); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res as DefaultRes & ProfileReqStruct, }; } async requestProfile(id: Long): AsyncCommandResult<ProfileReqStruct> { const res = await this._client.requestData( 'GET', `${this.getProfile3ApiPath('friend_info.json')}?id=${encodeURIComponent(id.toString())}`, ); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res as DefaultRes & ProfileReqStruct }; } // scrap async getPreviewURL(url: string): AsyncCommandResult<DefaultRes> { const res = await this._client.requestData('POST', this.getScrapApiPath('preview.json'), { url }); return { status: res.status, success: res.status === KnownDataStatusCode.SUCCESS, result: res }; } private getAccountApiPath(api: string) { return `${this.config.agent}/account/${api}`; } private getFriendsApiPath(api: string) { return `${this.config.agent}/friends/${api}`; } private getProfileApiPath(api: string) { return `${this.config.agent}/profile/${api}`; } private getProfile3ApiPath(api: string) { return `${this.config.agent}/profile3/${api}`; } private getScrapApiPath(api: string) { return `${this.config.agent}/scrap/${api}`; } /** * Create default AccountClient using credential and config. * * @param {OAuthCredential} credential * @param {Partial<WebApiConfig>} config */ static async create(credential: OAuthCredential, config: Partial<WebApiConfig> = {}): Promise<ServiceApiClient> { return new ServiceApiClient( await createSessionWebClient( credential, Object.assign({ ...DefaultConfiguration }, config), 'https', 'katalk.kakao.com', ), ); } static createSessionURL(token: string, redirectURL: string): string { // eslint-disable-next-line max-len return `https://accounts.kakao.com/weblogin/login_redirect?continue=${encodeURIComponent(redirectURL)}&token=${token}`; } }
the_stack
import fs = require('fs'); import path = require('path'); import clone = require('clone'); export namespace dtsmake{ const DTS_INTERFACE_STR = "!!!dtsinterface!!!"; const DTS_NAMESPACE_STR = "!!!dtsnamespace!!!"; export class DTSMake{ /** * ternjs json format data */ ternjsData:JSON; /** * currently nodejs module internal name * ex. "node_modules/path/to/module`js" */ nodeModuleName:string; /** * user defined name when tern/condense */ userDefinedModuleName:string; /** * Default Options */ option:Option = { // debug mode isDebug:false, // force output "void" to "any" isOutVoidAsAny:false, // export a namespace property same with a interface isExportInterfaceSameNameVar:true, // annotate interface constructor type as return type instance isAnnotateTypeInstance:true, // node module special replace isNodeJsModule:false, // add export statement in a bottom of d.ts file isOutExport:true, // how to export objects that has same name with JS global object globalObject:Option.GlobalObject.WRAP, // if isOutExport true, select export style "es6" or "legacy" exportStyle:Option.ExportStyle.LEGACY, // exporting module name // ex. "EXAMPLE"; usage 'import example = require("EXAMPLE");' // ex. "EXAMPLE/lib"; usage 'import example = require("EXAMPLE/lib");' // check javascript lib's import style exportModuleName:"" }; /** * main function * load json file */ main( srcPathStr:string, distPathStr:string, options?:Option ):void; /** * */ main( srcString:string, distPathStr:string, options?:Option ):void; main( param1:string, distPathStr:string, options?:Option ){ this.overrideDefaultOptions(options); if(/\n/.test(param1)){ //source code text let s = this.parseTernJson(JSON.parse(param1), distPathStr); this.saveTSDFile(distPathStr,s); } else if(/\.json$/.test(param1)){ //src json path this.loadTernJson(param1, (data:JSON)=>{ let s = this.parseTernJson(data, distPathStr); this.saveTSDFile(distPathStr,s); }) } } private overrideDefaultOptions(options?:Option){ if(options){ for(let i in options){ if(this.option[i]!==undefined || this.option[i]!==null){ //override default options this.option[i] = options[i]; } } } } /** * load ternjs json format data * @param pathStr path/to/file/example.json, must be strings */ loadTernJson(pathStr:string, cb:(data:JSON)=>void){ fs.readFile(pathStr,"UTF-8", (err:NodeJS.ErrnoException, data:Buffer)=>{ if(err)throw Error(err.name+" "+err.code+" "+err.message+" "+err.path); this.ternjsData = JSON.parse(data.toString()); //console.log(JSON.stringify(this.ternjsData)); console.log("Load a JSON file complete."); //this.parseTernJson(this.ternjsData); cb(this.ternjsData); }); } /** * save typescript d.ts file. * TODO: add line feed option (LF/CR/CR-LF) * @param name path/to/filename, no need file ext. like ".d.ts" * @param src file data strings. */ saveTSDFile(name:string,src:string):boolean{ try{ fs.writeFile(`${name}.d.ts`, src, {encoding:"UTF-8"}, (err:NodeJS.ErrnoException)=>{ if(err)throw Error(err.name+" "+err.code+" "+err.message+" "+err.path); console.log(`File saved. (${name}.d.ts)`); }); }catch(e){ throw Error(e); //return false; } return true; } saveJSON(pathStr:string, data:string, complete:Function){ fs.writeFile(pathStr, data, {encoding:"UTF-8"}, (e:NodeJS.ErrnoException)=>{ if(e)throw Error(e.name+" "+e.code+" "+e.message+" "+e.path); complete(); }); } parseTernJson(data:JSON, distPathStr?:string):string{ this.depth = 0; let o = this.parseJsonNodeDTS(data); //console.info("-----------------------"); //console.log(JSON.stringify(o)); let d = this.preModifiedJson(o); //console.info("-----------------------"); //console.log(JSON.stringify(d)); if( this.option.isOutExport && this.userDefinedModuleName && this.option.isNodeJsModule ){ d = this.replaceExportNamespace(d); } if(this.option.isDebug){ this.saveJSON(distPathStr+".json", JSON.stringify(d), ()=>{}); } let s = this.parseToDTS(d); //add referrence paths to d.ts if(this.option.lib){ let refs = this.option.lib .map((v,i,a)=>{ return `/// <reference path="${v}" />`; }) .join("\n"); s = refs +"\n"+ s; } //add header s = `// Type definitions for ${this.userDefinedModuleName} // Project: [LIBRARY_URL_HERE] // Definitions by: [YOUR_NAME_HERE] <[YOUR_URL_HERE]> // Definitions: https://github.com/borisyankov/DefinitelyTyped ` + s; if(this.option.isOutExport){ let n = this.option.exportModuleName ? this.option.exportModuleName : this.userDefinedModuleName; const reg = /^['"]([^']+)['"]$/; if(reg.test(n)){ n = RegExp.$1; } s += ` declare module '${n}' { `; if(this.option.exportStyle === dtsmake.Option.ExportStyle.ES6){ s += ` export default ${this.userDefinedModuleName}; //es6 style module export `; }else{ s += ` export = ${this.userDefinedModuleName}; //legacy ts module export `; } s += "}"+"\n"; } return s; } private modJson = {}; preModifiedJson(data:{}):Object{ let modJson = clone(data); //searching defined objects const reg = /[.]/; for(let i in modJson[TernDef.DEFINE]){ let value = modJson[TernDef.DEFINE][i]; if(typeof i === "string" && reg.test(i)){ //matched let p = i.split("."); if(p.length<=1) continue; //not defined path //naming let s = ""; if(value[0] && value[0].class && value[0].type === TSObjType.CLASS){ //already defined class let np:string[] = value[0].class.split("."); s = np[np.length-1]; }else{ s = this.resolvePathToDTSName(p); } //replace this.searchAndReplaceDTS(modJson,p,s); //save if(typeof value === "string"){ //only !type node let typeStr = value.toString(); modJson[TernDef.DEFINE][i] = {}; modJson[TernDef.DEFINE][i][TernDef.TYPE] = typeStr; //console.log("-----------------"); //console.log(JSON.stringify(value)); }else if(value instanceof Array){ if(value[0].class){ //same class instance } } modJson[TernDef.DEFINE][i][DTS_INTERFACE_STR] = s; //console.log("-----------------"); //console.log(JSON.stringify(value)); //namespace const ns = this.resolveNamespace(p); if(ns!==""){ modJson[TernDef.DEFINE][i][DTS_NAMESPACE_STR] = ns; } } } //same with js global object name const GENDOC = "\n[dtsmake] this is generated by dtsmake.\n"; for(let j in modJson){ if(typeof j === "string" && this.isJSGlobalObject(j)){ //console.log("JS Global same :"+ j) //console.log("option:"+this.option.globalObject) switch(this.option.globalObject){ case Option.GlobalObject.REMOVE: break; case Option.GlobalObject.WRAP: let n = (this.userDefinedModuleName ? this.userDefinedModuleName : "Lib");// + "." + j; if(!modJson[n]) modJson[n] = {}; let c = j; if(modJson[n][c]){ c = c + (Math.random()*1000|0); } modJson[n][c] = clone(modJson[j]); modJson[n][c][DTS_INTERFACE_STR] = c; //modJson[n][c][TernDef.TYPE] = TSObjType.FUNCTION; break; case Option.GlobalObject.RENAME: let n2 = (this.userDefinedModuleName ? this.userDefinedModuleName : "Lib") + "$" + j; if(modJson[n2]){ n2 = n2 + (Math.random()*1000|0); } modJson[n2] = {}; modJson[n2] = clone(modJson[j]); break; case Option.GlobalObject.RENAME_EXTEND: /* let n3 = (this.userDefinedModuleName ? this.userDefinedModuleName : "Lib") + "$" + j; if(modJson[n3]){ n3 = n3 + (Math.random()*1000|0); } modJson[n3] = {}; modJson[n3] = clone(modJson[j]); if(!modJson[n3][TernDef.PROTO])modJson[n3][TernDef.PROTO] = {type:TSObjType.CLASS,class:`${j}.prototype`}; console.log("modJson[n3]:"+modJson[n3]); */ break; } //remove base modJson[j] = null; delete modJson[j]; } } this.modJson = modJson; return modJson; } replaceExportNamespace(data:{}):Object{ let modJson = clone(data); //nodejs node if(modJson[TernDef.DEFINE][TernDef.NODE]){ let nodejsNode = modJson[TernDef.DEFINE][TernDef.NODE]; for(let i in nodejsNode){ //replace nodejsNode[this.userDefinedModuleName] = clone(nodejsNode[i]); //remove delete nodejsNode[i]; } } //other nodes for(let i in modJson[TernDef.DEFINE]){ let cNode = modJson[TernDef.DEFINE][i]; if(cNode[DTS_NAMESPACE_STR] &&! /\./.test(cNode[DTS_NAMESPACE_STR]) ){ //replace namespace cNode[DTS_NAMESPACE_STR] = this.userDefinedModuleName; } } if( ( modJson[this.userDefinedModuleName] && modJson[this.userDefinedModuleName] instanceof Object && Object.keys(modJson[this.userDefinedModuleName]).length === 0 ) || ( modJson[this.userDefinedModuleName] && modJson[this.userDefinedModuleName] instanceof Object && Object.keys(modJson[this.userDefinedModuleName]).length === 1 && modJson[this.userDefinedModuleName][TernDef.SPAN] ) ){ //remove delete modJson[this.userDefinedModuleName]; } return modJson; } resolvePathToDTSName(paths:string[]):string{ let s = ""; const reg2 = /^!.+/; const reg3 = /<.+>/; for(let j=paths.length-1; j>0; j--){ //console.log("P[J]:"+p[j]); if(reg2.test(paths[j])){ //tern def name let tmp = paths[j] .replace("!","") .replace(/^[a-z]/,(val)=>{ return val.toUpperCase(); }); //console.log("DEFNAME:" + tmp); s = tmp + s; //console.log("DEFNAME2:" + s); } else if(reg3.test(paths[j])){ //array type let tmp = paths[j] .replace(/^</,"") .replace(/>$/,"") .replace(/^[a-z]/, (val)=> val.toUpperCase() ); s = tmp + s; } else if(/\//.test(paths[j])){ if(paths[j] === this.nodeModuleName){ s = this.userDefinedModuleName .replace(/^[a-z]/,(val)=>val.toUpperCase()) + s; } //console.log("DTSNAME:"+s); break; } else{ //create defined name //console.log("BEFORENAME:" + s); let s2 = paths[j].replace(/^[a-z]/,(val)=>{ return val.toUpperCase(); }); s = s2 + s; //console.log("NEW NAME: "+s); break; //end } } return s; } resolveNamespace(p:string[]):string{ let nsp:string[] = []; const len = p.length; const reg2 = /^!.+/; const reg3 = /<.+>/; const isOutRepNS = this.option.isOutExport; for(let i=len-1;i>=0;i--){ if(reg2.test(p[i]) || reg3.test(p[i])){ if(i===len-1)nsp = [];//reset else if(i>=1){ let tmpPath = ["!test",p[i-1],p[i]]; //console.log("tmpPath:"+tmpPath.join(".")) nsp.push( this.resolvePathToDTSName(tmpPath) ); } i--; continue; } if( (isOutRepNS && p[i] === this.nodeModuleName) || (isOutRepNS && /[`\/]/.test(p[i])) ){ //replace nodejs namespace if(this.userDefinedModuleName){ nsp.push(this.userDefinedModuleName); } //console.log(`nodeModule: ${this.nodeModuleName}`); //console.log(`userDifined: ${this.userDefinedModuleName}`); }else{ nsp.push(p[i]); } } return nsp.reverse().join("."); } /** * @param path searching ref path * @param name a new name to replace * @param isCheckDefine when in true, search & replace in "!define" object */ searchAndReplaceDTS( data:{}, path:string[], name:string, isCheckDefine:boolean = true ){ const len = path.length; //type check const t = path[len-1]; const rt = this.checkReplaceType(t); //search let ref = this.searchRef(data, path, isCheckDefine); if(!ref || !ref[0])return; //no path /*if(name=="GulpHeader1"){ //console.trace(); console.log("GulpHeader1:", path.join(".")); //console.log("ref:"+JSON.stringify(this.searchRef(data, path, isCheckDefine))); console.log("rt:"+rt); //console.log("resolveNamespace(path):", this.resolveNamespace(path)) };*/ //replace switch(rt){ case ReplaceType.RETURN: if(!ref || !ref[0]){ if(this.option.isDebug)console.warn("t:"+t+","+JSON.stringify(ref)); return; } let ret:TSObj[] = ref[0]["ret"]; let retLen = ret.length; if(this.option.isDebug)console.warn("Ret:", name, path, ret) if(retLen===1){ const ns = this.resolveNamespace(path) if(this.option.isDebug)console.warn("ns",ns) ret[0].class = (ns!="") ? ns+"."+name : name; ret[0].type = TSObjType.CLASS; }else{ const ns = this.resolveNamespace(path) if(this.option.isDebug)console.warn("ns",ns) //TODO:real replace let o = <TSObj>{}; o.class = (ns!="") ? ns+"."+name : name;//name; o.type = TSObjType.CLASS; ret.push(o); } //console.log("ret_name:"+name); //console.log(`replace[${t}]:${JSON.stringify(ref[0]["ret"])}`); break; case ReplaceType.PARAM: if(!ref || !ref[0]){ //console.log("t:"+t+","+JSON.stringify(ref)); return; } let n = Number(t.replace(/^!/,"")); //console.log(`ref:${JSON.stringify(ref)}`); //console.log(`ref[0]:${JSON.stringify(ref[0])}`); //console.log(`ref[0]["params"]:${JSON.stringify(ref[0]["params"])}`); let param = ref[0]["params"][n]; if(param instanceof Array){ let o = <TSObj>{}; o.class = name; o.type = TSObjType.CLASS; //if same type has, then replace const pStr = path.slice(0, path.length-2).join(".")+"."+name; let hasSameClass = (<Array<TSObj>>param) .some((v,i,a)=>{ return v.class && this.resolvePathToDTSName(v.class.split(".")) === name }); //console.log("hasSameClass:", hasSameClass, name); /*let test = (<Array<TSObj>>param) .some((v,i,a)=>{ return v.class && this.resolvePathToDTSName(v.class.split(".")) === name });*/ //console.log("test",test); if(hasSameClass){ (<Array<TSObj>>param) .filter((v,i,a)=>{ return v.class && this.resolvePathToDTSName(v.class.split(".")) === name }) .map((v,i,a)=>{ v.type = TSObjType.CLASS; v.class = name; }); }else{ (<Array<TSObj>>param).push(o); } }else{ const ns = this.resolveNamespace(path); //console.log("ns!:"+ns) param.class = (ns!="") ? ns+"."+name : name; param.type = TSObjType.CLASS; } //ref[0].class = name; //console.log(`replace[${t}]:${JSON.stringify(ref[0]["params"])}`); break; case ReplaceType.CLASS: //console.log("REP CLASS "+name); ref[0]["class"] = ""; ref[0].class = name; //console.log(`replace[${t}]:${JSON.stringify(ref[0])}`); break; case ReplaceType.ARRAY: //replacing array type let at = ref[0]["arrayType"]; let nspace = path.slice(0, path.length-2).join(".") + "." + name; let nt:TSObj = { type:TSObjType.CLASS, class:nspace }; //ref[0]["arrayType"] = nt; at[at.length-1] = nt; //console.log("REP_ARRAY:", name, JSON.stringify(at)); break; case ReplaceType.OTHER: //ref[0].class = `/* ${name} */ any`; break; } } searchRef( data:{}, path:string[], isCheckDefine:boolean ):any{ const len = path.length; if(data[path[0]]) isCheckDefine = false; let ref = isCheckDefine ? data[TernDef.DEFINE] : data; const OBJECT_TO_STRING = "$toString"; const OBJECT_VALUE_OF = "$valueOf"; for(let i=0; i<len-1; i++){ let s = path[i]; //Object prototype prop special replace if(s==="toString") s = OBJECT_TO_STRING; if(s==="valueOf") s = OBJECT_VALUE_OF; if( s === "prototype" && !ref[s] && ///^[A-Z].*/.test(path[i-1]) this.checkReplaceType(path[i-1]) === ReplaceType.CLASS ){ //may be class member continue; }else if(ref[s] === undefined){ //no path ref //check from top if(i>0){ let pname = path.slice(0, i).join(".") +"."+ s; let iData = data[TernDef.DEFINE]; if(iData[pname]){ ref = iData[pname]; continue; } if(this.option.isDebug){ console.warn("pname", pname) console.warn("iData[pname]", JSON.stringify(iData[pname])) } } //TODO: ref path !n or !ret to searching if(this.option.isDebug){ console.warn("current ref path:"+ s); console.warn("no path ref:"+path.join(".")); console.warn("data", JSON.stringify(ref)) } return undefined; //do nothing }else{ ref = ref[s]; } } //has !type node if(ref[TernDef.TYPE]){ ref = ref[TernDef.TYPE]; } return ref; } checkReplaceType(s:string):ReplaceType{ let rt:ReplaceType; if(s === "!ret"){ //return rt = ReplaceType.RETURN; }else if(/^![0-9]+/.test(s)){ //param rt = ReplaceType.PARAM; }else if(/^[A-Z].*/.test(s)){ //class or object, may be class rt = ReplaceType.CLASS; }else if(/^<.+>$/.test(s)){ //array type rt = ReplaceType.ARRAY; //TODO:Array type replace }else{ //other rt = ReplaceType.OTHER; } return rt; } ternDefClassToDTSClass(ternClassStr:string):string{ let s = ""; //console.log("-----------CLASS-------------"); //console.log(ternClassStr); let regInstance = /^\+.*/; let regDefined = /^!.+/; if(regInstance.test(ternClassStr)){ //some class instance let p = ternClassStr.split("."); s = p[p.length-1]; }else if(regDefined.test(ternClassStr)){ //path to class let p = ternClassStr.split("."); s = this.resolvePathToDTSName(p); //console.log("-----------CLASS-------------"); //console.log(ternClassStr); //this.modJson; } return s; } /** * ternjs type definition to TSObj */ parseJsonNodeDTS(data:{}):any{ let o = JSON.parse("{}"); for(let i in data){ let value: string | {}; value = data[i]; switch(i){ //converts case TernDef.DEFINE: o[i] = {}; if(typeof value === "string")continue; else{ for(let j in value){ o[i] = this.parseJsonNodeDTS(value); } } break; case TernDef.NODE: /*if(typeof value === "string"){ this.option.isNodeJsModule = true; this.nodeModuleName = value; }else */ if(typeof i === "string"){ if(Object.keys(value).length === 1){ this.nodeModuleName = Object.keys(value)[0]; } } o[i] = this.parseJsonNodeDTS(value); break; //no converts case TernDef.NAME: this.userDefinedModuleName = <string>value; case TernDef.DOC: case TernDef.URL: o[i] = value; break; default: if(typeof value === "string"){ //node end //Object has same name default switch(i){ case "toString": case "valueOf": let newPropName = `$${i}`; o[newPropName] = {}; o[newPropName] = this.parseTernDef(value); break; default: o[i] = this.parseTernDef(value); } }else if( value[TernDef.TYPE] && value["prototype"] ){ //has !type && .prototype o[i] = {}; //constructor o[i][DTSDef.NEW] = {}; o[i][DTSDef.NEW] = this.parseTernDef(value[TernDef.TYPE], i, true); //prototype for(let j in value["prototype"]){ if(typeof value["prototype"][j] === "string") o[i][j] = this.parseTernDef(value["prototype"][j]); else o[i][j] = this.parseJsonNodeDTS(value["prototype"][j]); } //member without prototype/!type for(let j in value){ if(j===TernDef.TYPE)continue; if(j==="prototype")continue; if(typeof value[j] === "string"){ if( j===TernDef.DOC || j===TernDef.URL ){ o[i][j] = value[j]; }else{ o[i][j] = this.parseTernDef(value[j]); } }else{ o[i][j] = this.parseJsonNodeDTS(value[j]); } } }else{ o[i] = this.parseJsonNodeDTS(value); } break; } } return o; } private isInDefine = false; private isNodeJsModule = false; private isInClassOrInterface = false; private isInObjectLiteral = false; private isNeedDeclare = true; parseToDTS(data:{}, parent?:{}):string{ let s = ""; for(let i in data){ let value:string|Object[]|Object|TSObj[]; value = data[i]; switch (i) { case TernDef.NAME: //s += `/* LIB: ${value} */\n`; break; case TernDef.DEFINE: //already defined class instance if(value instanceof Array)continue; //nothing if(typeof value === "string")continue; this.isInDefine = true; for(let j in <Object>value){ //nodejs module if(j === TernDef.NODE){ this.isNodeJsModule = true; let dont:TSObj[] = [] let wrap:TSObj[] = []; for(let k in value[TernDef.NODE]){ const v = value[TernDef.NODE][k]; if(v[TernDef.TYPE]){ dont[k] = <TSObj>{}; dont[k] = clone(v); } else{ wrap[k] = <TSObj>{}; wrap[k] = clone(v); } } //dont wrap s += this.parseToDTS(dont); //wrap s += this.wrapNamespace(wrap, TernDef.NODE); this.isNodeJsModule = false; } //global defined else{ let ns:string = ""; let defName:string = ""; if(value[j][DTS_INTERFACE_STR]){ defName = value[j][DTS_INTERFACE_STR].toString(); delete value[j][DTS_INTERFACE_STR]; }else{ defName = j; } //has namespace if(value[j][DTS_NAMESPACE_STR]){ ns = value[j][DTS_NAMESPACE_STR]; delete value[j][DTS_NAMESPACE_STR]; } //already defined no output if( value[j] instanceof Array && value[j].length === 1 && value[j][0].type === TSObjType.CLASS ){ continue; } //outputs if(ns!=""){ //namespace open s += this.indent(); s += this.addDeclare(true); s += `namespace ${ns}{\n`; this.depth++; } //type alias if(value[j] instanceof Array){ s += this.indent(); s += `// ${j}\n`; s += this.indent(); s += `type ${defName} = `; s += this.tsObjsToUnionDTS( value[j], (<TSObj[]>value[j]).some((v,i,a)=> v.type === TSObjType.FUNCTION) ); s += ";\n"; } //global variables else if(typeof value[j] === "string"){ s += this.indent(); s += this.outJSDoc( value[j][TernDef.DOC] ? value[j][TernDef.DOC] : undefined, value[j][TernDef.URL] ? value[j][TernDef.URL] : undefined ); s += `var ${defName}: ${value[j]}\n`; } //interface else{ s += this.interfaceDTS(defName, value[j], j); } if(ns!=""){ //namespace close this.depth--; s += this.indent(); s += `}\n`; } } } this.isInDefine = false; //} break; case TernDef.DOC: //output only jsdoc break; case TernDef.SPAN: break; case TernDef.TYPE: if(this.isInClassOrInterface){ s += this.indent(); s += this.convertTSObjToString( "", <TSObj[]>value, value[TernDef.DOC], value[TernDef.URL] ); } break; case TernDef.PROTO: break; case "<i>": //TODO:research ternjs def's `<i>` mean & what to do // Maybe ternjs cannot get prop name. // so, currently, dtsmake don't output. break; default: //grammer error name replace if(/[\*\-]/.test(i)){ i = `"${i}"`; /* if(parent){ parent[i] = {}; parent[i] = clone(value); } break; */ } //node end if(value instanceof Array){ s += this.indent(); s += this.convertTSObjToString(i, <TSObj[]>value, value[TernDef.DOC], value[TernDef.URL]); } else if(typeof value === "string"){ s += this.outJSDoc( value[TernDef.DOC], value[TernDef.URL] ); s += this.indent(); s += this.addDeclare(); s += i + " : " + value; } //has "new ()" or "!proto" is class interface else if( value && (value[DTSDef.NEW] || value[TernDef.PROTO]|| value[DTS_INTERFACE_STR]) && !this.isInClassOrInterface ){ if( this.option.globalObject === Option.GlobalObject.WRAP && value[DTS_INTERFACE_STR] ){ delete value[DTS_INTERFACE_STR]; } s += this.interfaceDTS(i,value); } //has only {} node end else if(value instanceof Object &&Object.keys(value).length===0){ s += this.indent(); s += this.convertTSObjToString(i, [<TSObj>{}], value [TernDef.DOC], value[TernDef.URL]); } //has only terndef children else if( value && value[TernDef.TYPE] //TODO: other terndef node ){ //s += this.outJSDoc(); s += this.indent(); s += this.convertTSObjToString(i,value[TernDef.TYPE],value[TernDef.DOC], value[TernDef.URL]); //children if(Object.keys(value).length > 1){ let v = clone(value); delete v[TernDef.TYPE]; delete v[TernDef.DOC]; delete v[TernDef.URL]; if(this.option.isDebug){ console.log("I:"+i, JSON.stringify(v), Object.keys(v).length); } if(Object.keys(v).length>0 && !this.isInClassOrInterface){ //s += this.outNamespaceDTS(v, i, parent); s += this.outNamespaceOrInterface(v,i); } //TODO: isInClassOrInterface == true, export namespace } } //has class/interface children is namespace else if( this.isNamespace(value) ){ s += this.outNamespaceOrInterface(value, i); } //has child else{ s += this.outJSDoc( value[TernDef.DOC], value[TernDef.URL] ); s += this.indent(); //object literal type if(!this.isInObjectLiteral && !this.isInClassOrInterface){ s += this.addDeclare(); s += "var "; } s += `${i} : {\n`; this.isInObjectLiteral = true; this.depth++; //s += this.indent(); s += this.parseToDTS(value, parent); this.depth--; this.isInObjectLiteral = false; s += this.indent(); s += `}\n`; } break; } } return s; } addDeclare(flag?:boolean):string{ const DECLARE_STR = "declare "; if(flag && flag === true) return DECLARE_STR; else if(this.depth===0) return DECLARE_STR; else return ""; } outNamespaceOrInterface(value:any, name:string, path?:string):string{ let s = ""; let outI = {}; let outN = {}; for(let i in value){ if(!value[i])continue; const v = value[i]; if( v[0] && v[0].type === TSObjType.FUNCTION && /[\*\-]/.test(i) ){ //export in interface outI[i] = clone(v); } /*else if( this.isNamespace(v) || (v[0] && this.isNamespace(v[0])) ){ //namespace is only child in namespace //export in namespace outN[i] = clone(v); } else if( (v && v[DTSDef.NEW]) || (v[0] && v[0][DTSDef.NEW]) || (v && v[TernDef.PROTO]) || (v[0] && v[0][TernDef.PROTO]) ){ //class/interface is in namespace outN[i] = clone(v); }*/ else{ //export in interface //outI[i] = clone(v); outN[i] = clone(v); } } if(Object.keys(outN).length>0) s += this.outNamespaceDTS(outN, name); if(Object.keys(outI).length>0) s += this.interfaceDTS(name, outI); return s; } outNamespaceDTS(value:any, name:string, parent?:any):string{ let s = ""; s += this.outJSDoc( value[TernDef.DOC], value[TernDef.URL] ); s += this.indent(); s += this.addDeclare(); s += `namespace ${name}{\n`; this.depth++; s += this.parseToDTS(value, parent); this.depth--; s += this.indent(); s += `}\n`; return s; } /** * @param defName interface name */ interfaceDTS( defName:string, value:{}|{}[], path?:string ):string{ let s = ""; //interface name if(path){ s += this.indent(); s += `// ${path}\n`; //TODO:output option ternjs internal ref path } s += this.outJSDoc( value[TernDef.DOC] ? value[TernDef.DOC] : null, value[TernDef.URL] ? value[TernDef.URL] : null ); s += this.indent(); s += this.addDeclare(); s += `interface ${defName}`; //extending other class/interface if(value[TernDef.PROTO]){ let proto = value[TernDef.PROTO]; if( proto instanceof Array && proto.length > 1 ){ const str = "Object extends 2 or more other objects, but TypeScript only extends SINGLE Class/Interface."; console.warn(str); s += `/* ${str} */`; }else{ let t:TSObj = proto[0]; //resolve path to object prototype if(!t.class){ if(this.option.isDebug) console.log("t:"+JSON.stringify(t)); //return; }else{ let p = t.class.split("."); if(p[p.length-1]==="prototype"){ //output let ext = p.slice(0, p.length-1).join("."); s += ` extends ${ext}`; } //delete temp property value[TernDef.PROTO] = undefined; delete value[TernDef.PROTO]; } } } //interface body this.isInClassOrInterface = true; this.isInObjectLiteral = true; this.isNeedDeclare = false; s += ` {\n`; this.depth++; s += this.parseToDTS(value); this.depth--; s += this.indent(); s += `}\n`; this.isInObjectLiteral = false; this.isInClassOrInterface = false; this.isNeedDeclare = true; //interface var to new() if(value[dtsmake.DTSDef.NEW] && this.option.isExportInterfaceSameNameVar){ s += this.indent(); s += this.addDeclare(); s += `var ${defName}: ${defName};\n`; } return s; } isNamespace(value:any):boolean{ if(!value){ return false; } else if(value instanceof Array) return false; else if(value[TernDef.TYPE]) return false; else if(!(value instanceof Object)) return false; else if(Object.keys(value).length === 0) return false; else if(this.isInClassOrInterface){ return false; } else{ for(let i in value){ if(!value[i])continue; if( value[i] instanceof Object && Object.keys(value[i]).length > 1 ){ return true; } else if( value[i][0] && value[i][0].type && ( value[i][0].type === TSObjType.FUNCTION || value[i][0].type === TSObjType.BOOLEAN || value[i][0].type === TSObjType.ARRAY ) ){ return true; } } return false; } } /** * */ outJSDoc( comment?:string, url?:string, params?:string[], ret?:string ):string{ let s = ""; //jsdoc open s += this.indent(); s += "\n"; s += this.indent(); s += `/**\n`; //base comment from js files s += this.indent(); if(comment){ //TODO:support multi platform BR const aComment = comment.split("\n"); const len = aComment.length; for(let i=0; i<len; i++){ if(i!==0) s += this.indent(); s += ` * ${aComment[i]}\n`; } }else{ s += ` * \n`; } //params if(params){ for(let i of params){ s += this.indent(); s += ` * @param ${i} \n`; } } //returns if(ret){ s += this.indent(); s += ` * @return ${ret}\n`; } //url if(url){ s += this.indent(); s += ` * @url ${url}\n`; } //jsdoc close s += this.indent(); s += ` */\n`; return s; } outFuncJsDocs( t:TSObj, docData?:string, urlData?:string ):string{ let s = ""; let ps = (t.params) ? t.params .map((v,i,a)=>{ if(v instanceof Array){ return v[0].name; }else{ return v.name; } }) : null; let rs = ( !t.ret || t.ret .every((v,i,a)=>v.type === TSObjType.VOID) ) ? null : //no ret or void only //t.ret.map((v,i,a)=> v.class ? v.class : "").join(", "); //TODO:return info " " s += this.outJSDoc(docData,urlData,ps,rs); return s; } convertTSObjToString( symbolName:string, tsObjects:TSObj[], docData?:string, //TODO:support doc data urlData?:string, //TODO:support url data spanData?:string //TODO:support spandata ):string{ let s = ""; let keyword = ""; let isFunc = false; if(tsObjects[0].type === TSObjType.FUNCTION){ isFunc = true; } //Object property special replace revert if(/^\$(toString|valueOf)$/.test(symbolName)){ //console.log(symbolName+" should revert."); symbolName = symbolName.replace(/^\$/,""); } //may be class let isMaybeClass = false; if( /^[A-Z]/.test(symbolName) && //PascalCase tsObjects[0].type === TSObjType.FUNCTION ){ isMaybeClass = true; } //keyword if(this.isInClassOrInterface){ }else if(this.isInObjectLiteral){ } else{ if(isFunc && !isMaybeClass){ keyword = "function "; }else if(isFunc && isMaybeClass){ //TODO:option class or interface (default) keyword = "class "; }else{ keyword = "var "; } } //function not class/interface if(isFunc && !isMaybeClass){ let ol = tsObjects.length; //TODO:overloads support //out ol = tsObjects.length; for(let i=0;i<ol;i++){ let t = tsObjects[i]; //console.log("T:"+JSON.stringify(t)); //jsdoc s += this.outFuncJsDocs(t, docData,urlData) s += this.indent(); //output function d.ts s += this.addDeclare(); s += keyword + symbolName + "("+ this.paramsToDTS(t.params) +")"; //return type if( t.ret && symbolName === DTSDef.NEW && !this.option.isAnnotateTypeInstance && t.ret.every((v)=>v.type === TSObjType.VOID) ){ //constructor maynot return self instance //no output type annotation } else if(t.ret){ s += `: ${this.tsObjsToUnionDTS(t.ret, (t.ret.length>1) ? true : false, t, false)}`; } if(i!==ol-1){ //overload function s += ";"; } } //s += keyword + symbolName + "():" + JSON.stringify(tsObjects); } //may be class/interface else if(isFunc && isMaybeClass){ let nt:any = { //type:TSObjType.FUNCTION, [DTSDef.NEW]:[], [TernDef.DOC]:docData ? docData : null//, //[TernDef.URL]:urlData ? urlData : null }; if(urlData)nt[TernDef.URL] = urlData; for(let i in tsObjects){ if(i===TSObj.Def.TYPE)continue; let tmp = tsObjects[i]; //console.log("TMP:", JSON.stringify(tmp)); tmp.ret .filter((v,i,a)=>v.type===TSObjType.VOID) .map((v,i,a)=>{ //console.log("V1:",JSON.stringify(v)) v.type = TSObjType.CLASS; v.class = symbolName; //console.log("V2:",JSON.stringify(v)) return v; }); nt[DTSDef.NEW].push(tmp); } s += this.interfaceDTS(symbolName, nt); /* if(false){ //class open s += this.outJSDoc(docData,urlData); s += this.indent(); s += keyword + symbolName + "{\n"; this.depth++; //constructor only for(let i in tsObjects){ //constructor overloads let t = tsObjects[i]; //jsdoc s += this.indent(); s += this.outFuncJsDocs(t, docData,urlData) s += this.indent(); s += "constructor(" + this.paramsToDTS(t.params) +");\n"; } //class close this.depth--; s += this.indent(); s += "}"; } */ } else{ s += this.outJSDoc( docData, urlData ); s += this.indent(); if(!this.isInDefine && !this.isInObjectLiteral && !this.isInClassOrInterface) s += "export "; s += this.addDeclare(); s += keyword + symbolName+" : "+this.tsObjsToUnionDTS(tsObjects); } //close ; if(isMaybeClass)s += "\n"; else s += ";\n"; //this.depth--; return s; } paramsToDTS(params:TSObj[]):string{ //console.log("PARAMS:" + JSON.stringify(params)); if(params==null) return ""; else return params .map((v, i, a)=>{ //console.log(`|-[${i}]:${JSON.stringify(v)}`); if(v instanceof Array){ return this.tsObjsToUnionDTS(<any>v, true); }else{ if(!v.name) v.name = `param${i+1}`; return this.tsObjToDTS(v); } }) .join(", "); } /** * @param wrap wrap params with "()" */ tsObjsToUnionDTS( t:TSObj[], wrap:boolean = false, parentTSObj?:TSObj, isOutName:boolean = true ):string{ if(!t){ //not unions throw Error("union needs dts any tsObjs.") } //return "!!ERROR!!"; //merge `any` only union let isOnlyAny = t .every((v,i,a)=>(v.type === TSObjType.ANY)); if(isOnlyAny){ return this.tsObjToDTS(t[0], wrap, parentTSObj, isOutName); } //replace `any` to `{}` or `Object` if this is not `any` only union //because typescript type inferrence can't show union types (eg. VS Code) let hasAny = t.some((v,i,a)=>(v.type === TSObjType.ANY)) && (t.length > 1); if(hasAny){ t = t.map((v,i,a)=>{ if(v.type === TSObjType.ANY){ v.type = TSObjType.CLASS; v.class = "{}"; } return v; }); } return t .map((v, i, a)=>{ let isOutParamName = isOutName; if(i!==0) isOutParamName = false; // v.name = null; //don't output //if(!isOutName) v.name = null; return this.tsObjToDTS(v, wrap, parentTSObj, isOutParamName); }) .join(" | "); } tsObjToDTS( t:TSObj, wrap:boolean = false, parentTSObj?:TSObj, isOutName:boolean = true ):string{ if(!t)return " /* error */ any"; let s = ""; if(t.name && isOutName) s += t.name + " : "; wrap = wrap && (t.type === TSObjType.FUNCTION); if(wrap) s += "("; //wrap start switch(t.type){ case TSObjType.ANY: s += "any"; break; case TSObjType.ARRAY: s += "Array<"+this.tsObjsToUnionDTS(t.arrayType)+">"; break; case TSObjType.BOOLEAN: s += "boolean"; break; case TSObjType.CLASS: //ref to user class if(/^\+.+/.test(t.class)){ //class instance s += t.class.replace(/^\+/,""); //TODO:check real path } else if(/\./.test(t.class)){ const tp = t.class.split("."); const last = tp[tp.length-1]; if(/^[A-Z].+([0-9A-Z]|Ret)$/.test(last)){ //replaced class name s += t.class; }else{ //TODO: check path exist //temporary output s += `/* ${t.class} */ any`; } } else{ s += t.class; } //this.ternDefClassToDTSClass(t.class); break; case TSObjType.FUNCTION: //console.log("TStoDTS:fn("+t.params+")"+(t.ret)?"=>"+t.ret:""); s += "("+ this.paramsToDTS(t.params) +")"; if(!t.ret){ t.ret = [<TSObj>{type:TSObjType.VOID}]; } s += " => " + this.tsObjsToUnionDTS(t.ret, false, null, false); break; case TSObjType.NUMBER: s += "number"; break; case TSObjType.OBJECT: if(t.class){ switch (this.checkReplaceType(t.class)) { case ReplaceType.PARAM: //TODO:replace let n = Number(t.class.replace(/^!/, "")); if(!parentTSObj || !parentTSObj.params){ s += `/*${t.class}*/ any`; break; } let rep:TSObj|TSObj[] = parentTSObj.params[n]; // if(rep instanceof Array){ const isWrap = rep .some((v,i,a)=>v.type === TSObjType.FUNCTION); s += this.tsObjsToUnionDTS(rep,isWrap,null,false); }else{ s += this.tsObjToDTS(<TSObj>rep,false,null,false); if( rep && (<TSObj>rep).type && (<TSObj>rep).type===TSObjType.ANY ){ s += ` /* same type param "${(<TSObj>rep).name}" */`; //TODO:generate class/interface } } break; case ReplaceType.RETURN: //TODO:replace s += `/* ${t.class} */`; break; case ReplaceType.ARRAY: //TODO:replace s += `/* Array<${t.class}> */`; break; default: if(this.isJSGlobalObject(t.class)){ s += t.class; }else{ s += `/* ${t.class} */ `; s += "any"; } break; } }else{ s += "any"; } break; case TSObjType.STRING: s += "string"; break; case TSObjType.UNIONS: throw Error("unions? "+ JSON.stringify(t)); //break; case TSObjType.VOID: if(this.option.isOutVoidAsAny) s += "/* void */ any"; else s += "void"; break; default: s += "/*no type*/{}"; //no type break; } if(wrap) s += ")"; //wrap end return s; } isJSGlobalObject(name:string):boolean{ const g:string[] = [ "Object", "Function", "Boolean", "Symbol", "Error", "EvalError", "InternalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "Number", "Math", "Date", "String", "RegExp", "Array", "Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array", "Uint32Array", "Float32Array", "Float64Array", "Map", "Set", "WeakMap", "WeakSet", "ArrayBuffer", "DataView", "JSON", "Promise", "Generator", "GeneratorFunction", "Reflect", "Proxy" ]; return g.some( (v,i,a)=> v === name); } /** * */ wrapNamespace(value:string|Object, nodeName:string):string{ let s = ""; if(typeof value === "string"){ throw Error(nodeName +" node value must not to be string."); }else{ for(let j in value){ //open namespace s += "//nodejs module namespace\n"; s += this.addDeclare(); s += `namespace ${j}{\n`; //TODO:use namespace keyword option this.depth++; //s += this.indent(); s += this.parseToDTS(value[j]); this.depth--; //close namespace s += `}\n`; } } return s; } private depth:number = 0; indent():string{ let s = ""; const INDENT_STR = " "; //defalut tab string for(let i = 0|0; (i|0)<(this.depth|0);i++){ s += INDENT_STR; } return s; } convertTernJsToTs(ternDef:string):TSObj{ let ts:TSObj; return ts; } parseTernDef(ternDef:string, parentName?:string, isConstructor:boolean = false):any[]{ if(!ternDef) throw Error("need ternjs def string."); //remove spaces ternDef = ternDef.replace(/[\s\t\n]+/g,""); //remove outer () let reg = /^\((.+)\)$/; if(reg.test(ternDef)){ //console.log("reg:"+ternDef.match(reg)[1]); ternDef = ternDef.match(reg)[1]; //console.log("rm ():"+ ternDef); } // let sa = this.splitUnions(ternDef); let ret:any[] = []; for(let i of sa){ let ts = <TSObj>{}; ts.type = this.checkType(i); if(parentName)ts.name = parentName; if(ts.type === TSObjType.CLASS || ts.type === TSObjType.OBJECT){ ts.class = i; //console.log("++++++++++++++++++++++++"); //console.log(" ["+i+"]:" + ts.class); //console.log("++++++++++++++++++++++++"); } //console.log(`ts:${JSON.stringify(ts)}, ts.type:${ts.type}`); switch (ts.type) { case TSObjType.UNIONS: ret.push(this.parseTernDef(i)); continue; //break; case TSObjType.ARRAY: //console.log("ARRAY:"+i); //let test = i.replace(/^\[/,"").replace(/\]$/,""); //console.log(`i.replace(/^\[/,"").replace(/\]$/,""):${test}`); ts.arrayType = this.parseTernDef( i.replace(/^\[/,"").replace(/\]$/,"") ); break; case TSObjType.FUNCTION: //console.log(`fn:${i}`); ts.ret = this.parseFnReturn(i, parentName, isConstructor); ts.params = this.parseParams(i); break; case TSObjType.CLASS: case TSObjType.OBJECT: ts.class = i; //console.log("---CLASS/Object----"+ i + "----------"); break; case TSObjType.ANY: case TSObjType.BOOLEAN: case TSObjType.NUMBER: default: break; } ret.push(ts); //ret.push(this.parseTernDef(i)); } //console.log(`ret:${JSON.stringify(ret)}`); return ret; } private parseFnReturn(fnStr:string, parentName?:string, isConstructor:boolean = false):TSObj[]{ let sa = this.splitReturn(fnStr); if(isConstructor && this.option.isAnnotateTypeInstance && parentName && sa.length === 1){ //force annotate constructor return type instance return [<TSObj>{type:TSObjType.CLASS,class:parentName}]; } else if(sa.length===1){ //void return [<TSObj>{type:TSObjType.VOID}]; } //console.log(`fn-ret:${sa[1]}`); //return null; /* let ret:any[] = []; for(let i of sa){ ret.push(this.parseTernDef(i)); }*/ let ret = this.parseTernDef(sa[1]); if(isConstructor && this.option.isAnnotateTypeInstance && parentName){ ret .filter((v,i,a)=>v.type===TSObjType.VOID) .map((v,i,a)=>{ return <TSObj>{type:TSObjType.CLASS,class:parentName} }); } return ret; } parseParams(fnStr:string):any[]{ let fns = this.splitReturn(fnStr)[0]; //console.log("paramFnStr: "+fns); let reg1 = /^fn\(/; let reg2 = /\)$/; //let reg3 = /.*->.*/; //still inner /* if(reg1.test(fnStr)&&reg2.test(fnStr)&&reg3.test(fnStr)){ }*/ let fna = reg1.test(fns) && reg2.test(fns) /*&& !reg3.test(fnStr) */? fns .replace(/^fn\(/, "") .replace(/\)$/,"") : fns; /* console.log( "\u001b[32m■[check!]:\u001b[0m"+ reg1.test(fns)+ "^"+ reg2.test(fns)+ //"^"+ //!reg3.test(fnStr)+ ",\n"+ fna );*/ if(!fna || fna.length===1){ //console.log("no params. : "+fnStr) return null; }else{ let paramStr = fna; //console.log("param_str[1]:"+ paramStr); //return; //* let sa = this.splitParams(paramStr); //console.log(`param_str[2]:${sa}, len:${sa.length}`) let ret:any[] = []; for(let i of sa){ let n = i.search(/:/); let name = (n===-1) ? null : i.substring(0,n); let sType = i.substring(n+1); //console.log(`sType:${sType}`); let checked = this.checkType(sType); if(TSObjType.UNIONS === checked){ //unions let pa = this.parseTernDef(sType, name); ret.push(pa); } else if(TSObjType.ARRAY === checked){ let a = this.parseTernDef(sType,name); if(a.length===1){ ret.push(a[0]); }else{ ret.push(a); } } else{ let ts = <TSObj>{}; if(n!==-1)ts.name = name; ts.type = checked; if( ts.type === TSObjType.OBJECT || ts.type === TSObjType.CLASS ){ ts.class = sType; } //if(n===-1)console.log(`ts:${ts.name},${ts.type}`); ret.push(ts); } } return ret; } } /** * ternjs type to typescript type enum * | (a|b) | UNIONS | * | fn() | FUNCTION | * | ? | ANY | * | bool | BOOLEAN | * | number| NUMBER | * | string| STRING | * | [?] | ARRAY | * | +abc | CLASS | * | other above | OBJECT | * @return TSObjType return enums (number) */ checkType(ternDef:string):TSObjType{ if(this.splitUnions(ternDef).length>1){ return TSObjType.UNIONS; }else if(/^fn\(/.test(ternDef)){ //function return TSObjType.FUNCTION; }else if(ternDef==="?"){ return TSObjType.ANY; }else if(ternDef==="bool"){ return TSObjType.BOOLEAN; }else if(ternDef==="number"){ return TSObjType.NUMBER; }else if(ternDef==="string"){ return TSObjType.STRING; }else if(/^\[.+\]$/.test(ternDef)){ return TSObjType.ARRAY; }else if(/^\+.+$/.test(ternDef)){ return TSObjType.CLASS; }else if(ternDef!=""){ //console.log(`\u001b[35mWARNING: \u001b[0m ${ternDef} may not be type string. Is this a Object?`); return TSObjType.OBJECT; }else{ throw Error("\u001b[31mcan not check type. : \u001b[0m"+ternDef); //return; } } private splitUnions(ternDef:string):string[]{ return this.splits(ternDef, "(", ")", "|"); } splitParams(paramStr:string):string[]{ return this.splits(paramStr, "(", ")", ","); } private splitReturn(fnStr:string):string[]{ return this.splits(fnStr, "(",")","->"); } private splits( str:string, depthUpStr:string, depthDownStr:string, splitter:string ):string[]{ let delimIdxs:number[] = []; let retStr:any[] = []; const len = str.length|0; let depth = 0; //* const dUpIni = depthUpStr.charAt(0); const dDwIni = depthDownStr.charAt(0); const splIni = splitter.charAt(0); for(let i = 0|0;(i|0)<(len|0);i=(i+1)|0){ let cs = str.charAt(i); switch (cs) { case dUpIni: depth++; break; case dDwIni: depth--; break; case splIni: if(str.substr(i, splitter.length) != splitter) break; if(depth===0){ delimIdxs.push(i); i += splitter.length; } break; default: break; } }//*/ const delimLen = delimIdxs.length; if(delimLen===0){ retStr.push(str); }else{ let start = 0; let end = 0; for(let j=0;j<delimLen;j++){ end = delimIdxs[j]; let s = str.slice(start,end); start = delimIdxs[j]+splitter.length; retStr.push(s); if(j==delimLen-1){ retStr.push( str.slice(start) ); } } } //console.log(`retStr:${retStr}`); return retStr; } } /** * config option interface */ export interface Option{ isDebug?:boolean, isOutVoidAsAny?:boolean, isExportInterfaceSameNameVar?:boolean, isAnnotateTypeInstance?:boolean, isNodeJsModule?:boolean, isOutExport?:boolean, globalObject?:string, exportStyle?:string, exportModuleName?:string, lib?:string[] } /** * d.ts file data */ interface DTS{ name:string; isNodeModule:boolean; defines:{}; globals:Object[]; } interface DTSNode{ path?:string; } export const enum EnumTernDef{ NAME, DEFINE, TYPE, DOC, URL, EFFECTS, THIS, RET, SPAN, PROTO, STR_PROTO, NODE } export /*const*/ enum ReplaceType{ RETURN, PARAM, CLASS, ARRAY, OTHER } /** * * TODO:compat to TypeScript AST */ export interface TSObj{ type:TSObjType; //only for param/object/class name?:string; //only for function type params?:TSObj[]; ret?:TSObj[]; //only for array arrayType?:TSObj[]; //only for class class?:string; } export enum TSObjType{ ANY, VOID, BOOLEAN, NUMBER, STRING, FUNCTION, ARRAY, CLASS, UNIONS, OBJECT } } export namespace dtsmake.DTSDef{ export const NEW = "new "; } export namespace dtsmake.TSObj.Def{ export const TYPE = "type"; export const NAME = "name"; export const PARAMS = "params"; export const RET = "ret"; export const ARRAYTYPE = "arrayType"; export const CLASS = "class"; } export namespace dtsmake.Option.ExportStyle{ /** * es6 style `export default MODULE;` */ export const ES6 = "es6"; /** * legacy ts style `export = MODULE;` */ export const LEGACY = "legacy"; } export namespace dtsmake.Option.GlobalObject{ /** * remove extending global objects, no output */ export const REMOVE = "remove"; /** * wraping global objects with lib's namespace * @example `Math` -> `lib.Math` */ export const WRAP = "wrap"; /** * renaming global objects * @example `Math` -> `Lib$Math` */ export const RENAME = "rename"; /** * renaming global objects and extending global object * @example `Math` -> `Lib$Math extends Math` * [NEED] tsc >= 1.6 */ export const RENAME_EXTEND = "renameExtend"; } export namespace dtsmake.TernDef{ export const NAME = "!name"; export const DEFINE = "!define"; export const TYPE = "!type"; export const DOC = "!doc"; export const URL = "!url"; export const EFFECTS = "!effects"; export const THIS = "!this"; export const RET = "!ret"; export const SPAN = "!span"; export const PROTO = "!proto"; export const STR_PROTO = "!stdProto"; export const NODE = "!modules"; /** * convert TernDef.CONST:string to EnumTernDef.CONST:number * @param s TernDef class prop constraint string * @return EnumTernDef enum */ export function strToEnum(s:string):EnumTernDef{ switch (s) { case this.NAME: return EnumTernDef.NAME;//break; case this.DEFINE: return EnumTernDef.DEFINE;//break; case this.TYPE: return EnumTernDef.TYPE;//break; case this.DOC: return EnumTernDef.DOC;//break; case this.URL: return EnumTernDef.URL;//break; case this.EFFECTS: return EnumTernDef.EFFECTS;//break; case this.THIS: return EnumTernDef.THIS;//break; case this.RET: return EnumTernDef.RET;//break; case this.SPAN: return EnumTernDef.SPAN;//break; case this.PROTO: return EnumTernDef.PROTO;//break; case this.STD_PROTO: return EnumTernDef.STR_PROTO;//break; case this.NODE: return EnumTernDef.NODE;//break; default: throw Error("no match enum strings:"+s); //break; } } } /////////////////////////////// // CLI ////////////////////////////// //var dgen = new dtsmake.DTSMake();
the_stack
import * as cp from 'child_process' import * as github from '@actions/github' import * as os from 'os' import * as path from 'path' import * as process from 'process' import {expect, test} from '@jest/globals' import {promises} from 'fs' const {readFile, writeFile} = promises import {Formatter, FormatterOptions} from '../src/formatter' test('Example.xcresult', async () => { const bundlePath = '__tests__/data/Example.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format() const reportText = `${report.reportSummary}\n${report.reportDetail}` const outputPath = path.join(os.tmpdir(), 'Example.md') await writeFile(outputPath, reportText) // await writeFile('Example.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/Example.md')).toString() ) }) test('Example.xcresult', async () => { const bundlePath = '__tests__/data/Example.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format({ showPassedTests: false, showCodeCoverage: true }) const reportText = `${report.reportSummary}\n${report.reportDetail}` const outputPath = path.join(os.tmpdir(), 'ExampleOnlyFailures.md') await writeFile(outputPath, reportText) // await writeFile('ExampleOnlyFailures.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/ExampleOnlyFailures.md')).toString() ) }) test('KeychainAccess.xcresult', async () => { const bundlePath = '__tests__/data/KeychainAccess.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format() const reportText = `${report.reportSummary}\n${report.reportDetail}` const outputPath = path.join(os.tmpdir(), 'KeychainAccess.md') await writeFile(outputPath, reportText) // await writeFile('KeychainAccess.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/KeychainAccess.md')).toString() ) }) test('KeychainAccess.xcresult', async () => { const bundlePath = '__tests__/data/KeychainAccess.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format({ showPassedTests: false, showCodeCoverage: true }) const reportText = `${report.reportSummary}\n${report.reportDetail}` const outputPath = path.join(os.tmpdir(), 'KeychainAccessOnlyFailures.md') await writeFile(outputPath, reportText) // await writeFile('KeychainAccessOnlyFailures.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/KeychainAccessOnlyFailures.md')).toString() ) }) test('TAU.xcresult', async () => { const bundlePath = '__tests__/data/TAU.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format() const reportText = `${report.reportSummary}\n${report.reportDetail}` const outputPath = path.join(os.tmpdir(), 'TAU.md') await writeFile(outputPath, reportText) // await writeFile('TAU.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/TAU.md')).toString() ) }) test('Merged.xcresult', async () => { const bundlePath = '__tests__/data/Merged.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format() const reportText = `${report.reportSummary}\n${report.reportDetail}` const outputPath = path.join(os.tmpdir(), 'Merged.md') await writeFile(outputPath, reportText) // await writeFile('Merged.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/Merged.md')).toString() ) }) test('Spaceship.xcresult', async () => { const bundlePath = '__tests__/data/Spaceship.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format() const reportText = `${report.reportSummary}\n${report.reportDetail}` const outputPath = path.join(os.tmpdir(), 'Spaceship.md') await writeFile(outputPath, reportText) // await writeFile('Spaceship.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/Spaceship.md')).toString() ) }) test('TestResults.xcresult', async () => { const bundlePath = '__tests__/data/TestResults.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format() const reportText = `${report.reportSummary}\n${report.reportDetail}` const outputPath = path.join(os.tmpdir(), 'TestResults.md') await writeFile(outputPath, reportText) // await writeFile('TestResults.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/TestResults.md')).toString() ) }) test('UhooiPicBook.xcresult', async () => { const bundlePath = '__tests__/data/UhooiPicBook.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format() let root = '' if (process.env.GITHUB_REPOSITORY) { const pr = github.context.payload.pull_request const sha = (pr && pr.head.sha) || github.context.sha root = `${github.context.serverUrl}/${github.context.repo.owner}/${github.context.repo.repo}/blob/${sha}/` } const re = new RegExp(`${root}`, 'g') const reportText = `${report.reportSummary}\n${report.reportDetail}`.replace( re, '' ) const outputPath = path.join(os.tmpdir(), 'UhooiPicBook.md') await writeFile(outputPath, reportText) // await writeFile('UhooiPicBook.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/UhooiPicBook.md')).toString() ) }) test('Attachment.xcresult', async () => { const bundlePath = '__tests__/data/Attachment.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format() const reportText = `${report.reportSummary}\n${report.reportDetail}` const outputPath = path.join(os.tmpdir(), 'Attachment.md') await writeFile(outputPath, reportText) // await writeFile('Attachment.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/Attachment.md')).toString() ) }) test('Coverage.xcresult', async () => { const bundlePath = '__tests__/data/Coverage.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format() let root = '' if (process.env.GITHUB_REPOSITORY) { const pr = github.context.payload.pull_request const sha = (pr && pr.head.sha) || github.context.sha root = `${github.context.serverUrl}/${github.context.repo.owner}/${github.context.repo.repo}/blob/${sha}/` } const re = new RegExp(`${root}`, 'g') const reportText = `${report.reportSummary}\n${report.reportDetail}`.replace( re, '' ) const outputPath = path.join(os.tmpdir(), 'Coverage.md') await writeFile(outputPath, reportText) // await writeFile('Coverage.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/Coverage.md')).toString() ) }) test('Coverage.xcresult', async () => { const bundlePath = '__tests__/data/Coverage.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format({ showPassedTests: true, showCodeCoverage: false }) let root = '' if (process.env.GITHUB_REPOSITORY) { const pr = github.context.payload.pull_request const sha = (pr && pr.head.sha) || github.context.sha root = `${github.context.serverUrl}/${github.context.repo.owner}/${github.context.repo.repo}/blob/${sha}/` } const re = new RegExp(`${root}`, 'g') const reportText = `${report.reportSummary}\n${report.reportDetail}`.replace( re, '' ) const outputPath = path.join(os.tmpdir(), 'HideCodeCoverage.md') await writeFile(outputPath, reportText) // await writeFile('HideCodeCoverage.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/HideCodeCoverage.md')).toString() ) }) test('BuildError.xcresult', async () => { const bundlePath = '__tests__/data/BuildError.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format() const reportText = `${report.reportSummary}\n${report.reportDetail}` const outputPath = path.join(os.tmpdir(), 'BuildError.md') await writeFile(outputPath, reportText) // await writeFile('BuildError.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/BuildError.md')).toString() ) }) test('LinkError.xcresult', async () => { const bundlePath = '__tests__/data/LinkError.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format() const reportText = `${report.reportSummary}\n${report.reportDetail}` const outputPath = path.join(os.tmpdir(), 'LinkError.md') await writeFile(outputPath, reportText) // await writeFile('LinkError.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/LinkError.md')).toString() ) }) test('NoTests.xcresult', async () => { const bundlePath = '__tests__/data/NoTests.xcresult' const formatter = new Formatter(bundlePath) const report = await formatter.format() let root = '' if (process.env.GITHUB_REPOSITORY) { const pr = github.context.payload.pull_request const sha = (pr && pr.head.sha) || github.context.sha root = `${github.context.serverUrl}/${github.context.repo.owner}/${github.context.repo.repo}/blob/${sha}/` } const re = new RegExp(`${root}`, 'g') const reportText = `${report.reportSummary}\n${report.reportDetail}`.replace( re, '' ) const outputPath = path.join(os.tmpdir(), 'NoTests.md') await writeFile(outputPath, reportText) // await writeFile('NoTests.md', reportText) expect((await readFile(outputPath)).toString()).toBe( (await readFile('__tests__/data/NoTests.md')).toString() ) }) test('test runs', () => { process.env['INPUT_PATH'] = '__tests__/data/Example.xcresult' process.env['INPUT_SHOW-PASSED-TESTS'] = 'true' process.env['INPUT_SHOW-CODE-COVERAGE'] = 'true' process.env['INPUT_UPLOAD-BUNDLES'] = 'true' const np = process.execPath const ip = path.join(__dirname, '..', 'lib', 'main.js') const options: cp.ExecFileSyncOptions = { env: process.env } console.log(cp.execFileSync(np, [ip], options).toString()) })
the_stack
export interface DeleteProductRequest { /** * 需要删除的产品 ID */ ProductId: string; /** * 删除LoRa产品需要skey */ Skey?: string; } /** * DescribePrivateCABindedProducts请求参数结构体 */ export interface DescribePrivateCABindedProductsRequest { /** * 证书名称 */ CertName: string; /** * 查询偏移量 */ Offset: number; /** * 查询的数据量,默认为20, 最大为200 */ Limit: number; } /** * DescribePrivateCAs返回参数结构体 */ export interface DescribePrivateCAsResponse { /** * 私有CA证书列表 */ CAs: Array<CertInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * UpdateDevicesEnableState返回参数结构体 */ export interface UpdateDevicesEnableStateResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribePrivateCA请求参数结构体 */ export interface DescribePrivateCARequest { /** * 私有化CA名称 */ CertName: string; } /** * DescribeProductCA返回参数结构体 */ export interface DescribeProductCAResponse { /** * CA证书列表 */ CAs: Array<CertInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeletePrivateCA返回参数结构体 */ export interface DeletePrivateCAResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * UpdatePrivateCA请求参数结构体 */ export interface UpdatePrivateCARequest { /** * CA证书名称 */ CertName: string; /** * CA证书内容 */ CertText: string; /** * 校验CA证书的证书内容 */ VerifyCertText: string; } /** * DescribePrivateCABindedProducts返回参数结构体 */ export interface DescribePrivateCABindedProductsResponse { /** * 私有CA绑定的产品列表 */ Products: Array<BindProductInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteDevice请求参数结构体 */ export interface DeleteDeviceRequest { /** * 设备所属的产品 ID */ ProductId: string; /** * 需要删除的设备名称 */ DeviceName: string; /** * 删除LoRa设备以及LoRa网关设备需要skey */ Skey?: string; } /** * DeleteProduct返回参数结构体 */ export interface DeleteProductResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreatePrivateCA返回参数结构体 */ export interface CreatePrivateCAResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 子产品信息 */ export interface BindProductInfo { /** * 产品ID */ ProductId: string; /** * 产品名 */ ProductName: string; } /** * DescribeDevices返回参数结构体 */ export interface DescribeDevicesResponse { /** * 设备总数 */ TotalCount: number; /** * 设备详细信息列表 */ Devices: Array<DeviceInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 设备属性 */ export interface DeviceTag { /** * 属性名称 */ Tag: string; /** * 属性值的类型,1 int,2 string */ Type: number; /** * 属性的值 */ Value: string; /** * 属性描述名称 注意:此字段可能返回 null,表示取不到有效值。 */ Name?: string; } /** * DescribeProductCA请求参数结构体 */ export interface DescribeProductCARequest { /** * 产品ID */ ProductId: string; } /** * CreatePrivateCA请求参数结构体 */ export interface CreatePrivateCARequest { /** * CA证书名称 */ CertName: string; /** * CA证书内容 */ CertText: string; /** * 校验CA证书的证书内容 */ VerifyCertText: string; } /** * DescribeProduct返回参数结构体 */ export interface DescribeProductResponse { /** * 产品ID */ ProductId: string; /** * 产品名 */ ProductName: string; /** * 产品元数据 */ ProductMetadata: ProductMetadata; /** * 产品属性 */ ProductProperties: ProductProperties; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeDevice请求参数结构体 */ export interface DescribeDeviceRequest { /** * 产品ID */ ProductId: string; /** * 设备名 */ DeviceName: string; } /** * 设备标签 */ export interface DeviceLabel { /** * 标签标识 */ Key: string; /** * 标签值 */ Value: string; } /** * X509证书信息 */ export interface CertInfo { /** * 证书名称 */ CertName: string; /** * 证书的序列号,16进制编码 */ CertSN: string; /** * 证书颁发着名称 */ IssuerName: string; /** * 证书主题 */ Subject: string; /** * 证书创建时间,秒级时间戳 */ CreateTime: number; /** * 证书生效时间,秒级时间戳 */ EffectiveTime: number; /** * 证书失效时间,秒级时间戳 */ ExpireTime: number; /** * X509证书内容 */ CertText: string; } /** * 产品元数据 */ export interface ProductMetadata { /** * 产品创建时间 */ CreationDate: number; } /** * DescribePrivateCAs请求参数结构体 */ export declare type DescribePrivateCAsRequest = null; /** * UpdatePrivateCA返回参数结构体 */ export interface UpdatePrivateCAResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeDevices请求参数结构体 */ export interface DescribeDevicesRequest { /** * 需要查看设备列表的产品 ID */ ProductId: string; /** * 偏移量,Offset从0开始 */ Offset: number; /** * 分页的大小,数值范围 10-250 */ Limit: number; /** * 设备固件版本号,若不带此参数会返回所有固件版本的设备。传"None-FirmwareVersion"查询无版本号的设备 */ FirmwareVersion?: string; /** * 需要过滤的设备名称 */ DeviceName?: string; /** * 设备是否启用,0禁用状态1启用状态,默认不区分 */ EnableState?: number; } /** * UpdateDeviceLogLevel请求参数结构体 */ export interface UpdateDeviceLogLevelRequest { /** * 产品ID */ ProductId: string; /** * 设备名称 */ DeviceName: string; /** * 日志级别,0:关闭,1:错误,2:告警,3:信息,4:调试 */ LogLevel: number; } /** * DescribePrivateCA返回参数结构体 */ export interface DescribePrivateCAResponse { /** * 私有化CA详情 */ CA: CertInfo; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * UpdateDeviceLogLevel返回参数结构体 */ export interface UpdateDeviceLogLevelResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateDevice返回参数结构体 */ export interface CreateDeviceResponse { /** * 设备名称 */ DeviceName: string; /** * 对称加密密钥,base64编码。采用对称加密时返回该参数 */ DevicePsk: string; /** * 设备证书,用于 TLS 建立链接时校验客户端身份。采用非对称加密时返回该参数 */ DeviceCert: string; /** * 设备私钥,用于 TLS 建立链接时校验客户端身份,腾讯云后台不保存,请妥善保管。采用非对称加密时返回该参数 */ DevicePrivateKey: string; /** * LoRa设备的DevEui,当设备是LoRa设备时,会返回该字段 */ LoraDevEui: string; /** * LoRa设备的MoteType,当设备是LoRa设备时,会返回该字段 */ LoraMoteType: number; /** * LoRa设备的AppKey,当设备是LoRa设备时,会返回该字段 */ LoraAppKey: string; /** * LoRa设备的NwkKey,当设备是LoRa设备时,会返回该字段 */ LoraNwkKey: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * UpdateDevicesEnableState请求参数结构体 */ export interface UpdateDevicesEnableStateRequest { /** * 设备所属产品id */ ProductId: string; /** * 设备名称集合 */ DeviceNames: Array<string>; /** * 要设置的设备状态,1为启用,0为禁用 */ Status: number; } /** * CreateDevice请求参数结构体 */ export interface CreateDeviceRequest { /** * 产品 ID 。创建产品时腾讯云为用户分配全局唯一的 ID */ ProductId: string; /** * 设备名称。命名规则:[a-zA-Z0-9:_-]{1,48}。 */ DeviceName: string; /** * 设备属性 */ Attribute?: Attribute; /** * 是否使用自定义PSK,默认不使用 */ DefinedPsk?: string; /** * 运营商类型,当产品是NB-IoT产品时,此字段必填。1表示中国电信,2表示中国移动,3表示中国联通 */ Isp?: number; /** * IMEI,当产品是NB-IoT产品时,此字段必填 */ Imei?: string; /** * LoRa设备的DevEui,当创建LoRa时,此字段必填 */ LoraDevEui?: string; /** * LoRa设备的MoteType */ LoraMoteType?: number; /** * 创建LoRa设备需要skey */ Skey?: string; /** * LoRa设备的AppKey */ LoraAppKey?: string; /** * 私有CA创建的设备证书 */ TlsCrt?: string; } /** * DescribeProduct请求参数结构体 */ export interface DescribeProductRequest { /** * 产品ID */ ProductId: string; } /** * 设备属性 */ export interface Attribute { /** * 属性列表 */ Tags?: Array<DeviceTag>; } /** * DeleteDevice返回参数结构体 */ export interface DeleteDeviceResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeletePrivateCA请求参数结构体 */ export interface DeletePrivateCARequest { /** * 私有CA证书名称 */ CertName: string; } /** * 设备详细信息 */ export interface DeviceInfo { /** * 设备名 */ DeviceName: string; /** * 设备是否在线,0不在线,1在线 */ Online: number; /** * 设备登录时间 */ LoginTime: number; /** * 设备版本 */ Version: string; /** * 设备证书,证书加密的设备返回 */ DeviceCert: string; /** * 设备密钥,密钥加密的设备返回 */ DevicePsk: string; /** * 设备属性 */ Tags: Array<DeviceTag>; /** * 设备类型 */ DeviceType: number; /** * 国际移动设备识别码 IMEI */ Imei: string; /** * 运营商类型 */ Isp: number; /** * NB IOT运营商处的DeviceID */ NbiotDeviceID: string; /** * IP地址 */ ConnIP: number; /** * 设备最后更新时间 */ LastUpdateTime: number; /** * LoRa设备的dev eui */ LoraDevEui: string; /** * LoRa设备的Mote type */ LoraMoteType: number; /** * 首次上线时间 注意:此字段可能返回 null,表示取不到有效值。 */ FirstOnlineTime: number; /** * 最近下线时间 注意:此字段可能返回 null,表示取不到有效值。 */ LastOfflineTime: number; /** * 设备创建时间 注意:此字段可能返回 null,表示取不到有效值。 */ CreateTime: number; /** * 设备日志级别 注意:此字段可能返回 null,表示取不到有效值。 */ LogLevel: number; /** * 设备证书获取状态, 1 已获取过设备密钥,0 未获取过设备密钥 注意:此字段可能返回 null,表示取不到有效值。 */ CertState: number; /** * 设备可用状态,0禁用,1启用 注意:此字段可能返回 null,表示取不到有效值。 */ EnableState: number; /** * 设备标签 注意:此字段可能返回 null,表示取不到有效值。 */ Labels: Array<DeviceLabel>; /** * MQTT客户端IP地址 注意:此字段可能返回 null,表示取不到有效值。 */ ClientIP: string; /** * ota最后更新时间 注意:此字段可能返回 null,表示取不到有效值。 */ FirmwareUpdateTime: number; } /** * 产品属性 */ export interface ProductProperties { /** * 产品描述 */ ProductDescription?: string; /** * 加密类型,1表示证书认证,2表示签名认证。如不填写,默认值是1 */ EncryptionType?: string; /** * 产品所属区域,目前只支持广州(gz) */ Region?: string; /** * 产品类型,各个类型值代表的节点-类型如下: 0 普通产品,2 NB-IoT产品,4 LoRa产品,3 LoRa网关产品,5 普通网关产品 默认值是0 */ ProductType?: number; /** * 数据格式,取值为json或者custom,默认值是json */ Format?: string; /** * 产品所属平台,默认值是0 */ Platform?: string; /** * LoRa产品运营侧APPEUI,只有LoRa产品需要填写 */ Appeui?: string; /** * 产品绑定的物模型ID,-1表示不绑定 */ ModelId?: string; /** * 产品绑定的物模型名称 */ ModelName?: string; /** * 产品密钥,suite产品才会有 */ ProductKey?: string; /** * 动态注册类型 0-关闭, 1-预定义设备名 2-动态定义设备名 */ RegisterType?: number; /** * 动态注册产品秘钥 */ ProductSecret?: string; /** * RegisterType为2时,设备动态创建的限制数量 */ RegisterLimit?: number; /** * 划归的产品,展示为源产品ID,其余为空 */ OriginProductId?: string; /** * 私有CA名称 */ PrivateCAName?: string; /** * 划归的产品,展示为源用户ID,其余为空 */ OriginUserId?: number; } /** * DescribeDevice返回参数结构体 */ export interface DescribeDeviceResponse { /** * 设备名 */ DeviceName: string; /** * 设备是否在线,0不在线,1在线 */ Online: number; /** * 设备登录时间 */ LoginTime: number; /** * 设备固件版本 */ Version: string; /** * 设备最后更新时间 */ LastUpdateTime: number; /** * 设备证书 */ DeviceCert: string; /** * 设备密钥 */ DevicePsk: string; /** * 设备属性 */ Tags: Array<DeviceTag>; /** * 设备类型 */ DeviceType: number; /** * 国际移动设备识别码 IMEI */ Imei: string; /** * 运营商类型 */ Isp: number; /** * IP地址 */ ConnIP: number; /** * NB IoT运营商处的DeviceID */ NbiotDeviceID: string; /** * Lora设备的dev eui */ LoraDevEui: string; /** * Lora设备的mote type */ LoraMoteType: number; /** * 设备的sdk日志等级 注意:此字段可能返回 null,表示取不到有效值。 */ LogLevel: number; /** * 首次上线时间 注意:此字段可能返回 null,表示取不到有效值。 */ FirstOnlineTime: number; /** * 最近下线时间 注意:此字段可能返回 null,表示取不到有效值。 */ LastOfflineTime: number; /** * 设备创建时间 注意:此字段可能返回 null,表示取不到有效值。 */ CreateTime: number; /** * 设备证书获取状态,0 未获取过设备密钥, 1 已获取过设备密钥 注意:此字段可能返回 null,表示取不到有效值。 */ CertState: number; /** * 设备启用状态 注意:此字段可能返回 null,表示取不到有效值。 */ EnableState: number; /** * 设备标签 注意:此字段可能返回 null,表示取不到有效值。 */ Labels: Array<DeviceLabel>; /** * MQTT客户端IP地址 注意:此字段可能返回 null,表示取不到有效值。 */ ClientIP: string; /** * 设备固件更新时间 注意:此字段可能返回 null,表示取不到有效值。 */ FirmwareUpdateTime: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; }
the_stack
import moment from "moment"; import {ProwJobState, Pull} from "../api/prow"; import {relativeURL} from "./urls"; // This file likes namespaces, so stick with it for now. /* tslint:disable:no-namespace */ // The cell namespace exposes functions for constructing common table cells. export namespace cell { export function text(content: string): HTMLTableDataCellElement { const c = document.createElement("td"); c.appendChild(document.createTextNode(content)); return c; } export function time(id: string, when: moment.Moment): HTMLTableDataCellElement { const tid = "time-cell-" + id; const main = document.createElement("div"); const isADayOld = when.isBefore(moment().startOf('day')); main.textContent = when.format(isADayOld ? 'MMM DD HH:mm:ss' : 'HH:mm:ss'); main.id = tid; const tip = tooltip.forElem(tid, document.createTextNode(when.format('MMM DD YYYY, HH:mm:ss [UTC]ZZ'))); const c = document.createElement("td"); c.appendChild(main); c.appendChild(tip); return c; } export function link(displayText: string, url: string): HTMLTableDataCellElement { const c = document.createElement("td"); const a = document.createElement("a"); a.href = url; a.appendChild(document.createTextNode(displayText)); c.appendChild(a); return c; } export function state(s: ProwJobState): HTMLTableDataCellElement { const c = document.createElement("td"); if (!s) { c.appendChild(document.createTextNode("")); return c; } c.classList.add("icon-cell"); let displayState = stateToAdj(s); displayState = displayState[0].toUpperCase() + displayState.slice(1); let displayIcon = ""; switch (s) { case "triggered": displayIcon = "schedule"; break; case "pending": displayIcon = "watch_later"; break; case "success": displayIcon = "check_circle"; break; case "failure": displayIcon = "error"; break; case "aborted": displayIcon = "remove_circle"; break; case "error": displayIcon = "warning"; break; } const stateIndicator = document.createElement("i"); stateIndicator.classList.add("material-icons", "state", s); stateIndicator.innerText = displayIcon; c.appendChild(stateIndicator); c.title = displayState; return c; } function stateToAdj(s: ProwJobState): string { switch (s) { case "success": return "succeeded"; case "failure": return "failed"; default: return s; } } export function commitRevision(repo: string, ref: string, SHA: string, pushCommitLink: string): HTMLTableDataCellElement { const c = document.createElement("td"); const bl = document.createElement("a"); bl.href = pushCommitLink; if (!bl.href) { bl.href = `/github-link?dest=${repo}/commit/${SHA}`; } bl.text = `${ref} (${SHA.slice(0, 7)})`; c.appendChild(bl); return c; } export function prRevision(repo: string, pull: Pull): HTMLTableDataCellElement { const td = document.createElement("td"); addPRRevision(td, repo, pull); return td; } let idCounter = 0; function nextID(): string { idCounter++; return "tipID-" + String(idCounter); } export function addPRRevision(elem: Node, repo: string, pull: Pull): void { elem.appendChild(document.createTextNode("#")); const pl = document.createElement("a"); if (pull.link) { pl.href = pull.link; } else { pl.href = `/github-link?dest=${repo}/pull/${pull.number}`; } pl.text = pull.number.toString(); if (pull.title) { pl.id = `pr-${repo}-${pull.number}-${nextID()}`; const tip = tooltip.forElem(pl.id, document.createTextNode(pull.title)); pl.appendChild(tip); } elem.appendChild(pl); if (pull.sha) { elem.appendChild(document.createTextNode(" (")); const cl = document.createElement("a"); if (pull.commit_link) { cl.href = pull.commit_link; } else { cl.href = `/github-link?dest=${repo}/pull/${pull.number}/commits/${pull.sha}`; } cl.text = pull.sha.slice(0, 7); elem.appendChild(cl); elem.appendChild(document.createTextNode(")")); } if (pull.author) { elem.appendChild(document.createTextNode(" by ")); const al = document.createElement("a"); if (pull.author_link) { al.href = pull.author_link; } else { al.href = "/github-link?dest=" + pull.author; } al.text = pull.author; elem.appendChild(al); } } } export namespace tooltip { export function forElem(elemID: string, tipElem: Node): HTMLElement { const tip = document.createElement("div"); tip.appendChild(tipElem); tip.setAttribute("data-mdl-for", elemID); tip.classList.add("mdl-tooltip", "mdl-tooltip--large"); tip.style.whiteSpace = "normal"; return tip; } } export namespace icon { export function create(iconString: string, tip: string = "", onClick?: (this: HTMLElement, ev: MouseEvent) => any): HTMLAnchorElement { const i = document.createElement("i"); i.classList.add("icon-button", "material-icons"); i.innerHTML = iconString; if (tip !== "") { i.title = tip; } if (onClick) { i.addEventListener("click", onClick); } const container = document.createElement("a"); container.appendChild(i); container.classList.add("mdl-button", "mdl-js-button", "mdl-button--icon"); return container; } } export namespace tidehistory { export function poolIcon(org: string, repo: string, branch: string): HTMLAnchorElement { const link = icon.create("timeline", "Pool History"); const encodedRepo = encodeURIComponent(`${org}/${repo}`); const encodedBranch = encodeURIComponent(branch); link.href = `/tide-history?repo=${encodedRepo}&branch=${encodedBranch}`; return link; } export function authorIcon(author: string): HTMLAnchorElement { const link = icon.create("timeline", "Personal Tide History"); const encodedAuthor = encodeURIComponent(author); link.href = `/tide-history?author=${encodedAuthor}`; return link; } } export function getCookieByName(name: string): string { if (!document.cookie) { return ""; } const docCookies = decodeURIComponent(document.cookie).split(";"); for (const cookie of docCookies) { const c = cookie.trim(); const pref = name + "="; if (c.indexOf(pref) === 0) { return c.slice(pref.length); } } return ""; } export function createRerunProwJobIcon(modal: HTMLElement, rerunElement: HTMLElement, prowjob: string, rerunCreatesJob: boolean, csrfToken: string): HTMLElement { const url = `${location.protocol}//${location.host}/rerun?prowjob=${prowjob}`; const i = icon.create("refresh", "Show instructions for rerunning this job"); window.onkeydown = (event: any) => { if ( event.key === "Escape" ) { modal.style.display = "none"; } }; window.onclick = (event: any) => { if (event.target === modal) { modal.style.display = "none"; } }; // we actually want to know whether the "access-token-session" cookie exists, but we can't always // access it from the frontend. "github_login" should be set whenever "access-token-session" is i.onclick = () => { modal.style.display = "block"; rerunElement.innerHTML = `kubectl create -f "<a href="${url}">${url}</a>"`; const copyButton = document.createElement('a'); copyButton.className = "mdl-button mdl-js-button mdl-button--icon"; copyButton.onclick = () => copyToClipboardWithToast(`kubectl create -f "${url}"`); copyButton.innerHTML = "<i class='material-icons state triggered' style='color: gray'>file_copy</i>"; rerunElement.appendChild(copyButton); if (rerunCreatesJob) { const runButton = document.createElement('a'); runButton.innerHTML = "<button class='mdl-button mdl-js-button mdl-button--raised mdl-button--colored'>Rerun</button>"; runButton.onclick = async () => { gtag("event", "rerun", { event_category: "engagement", transport_type: "beacon", }); const result = await fetch(url, { headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8", "X-CSRF-Token": csrfToken, }, method: 'post', }); const data = await result.text(); if (result.status === 401) { window.location.href = window.location.origin + `/github-login?dest=${relativeURL({rerun: "gh_redirect"})}`; } else { rerunElement.innerHTML = data; } }; rerunElement.appendChild(runButton); } }; return i; } function copyToClipboardWithToast(text: string): void { copyToClipboard(text); const toast = document.getElementById("toast") as SnackbarElement<HTMLDivElement>; toast.MaterialSnackbar.showSnackbar({message: "Copied to clipboard"}); } // copyToClipboard is from https://stackoverflow.com/a/33928558 // Copies a string to the clipboard. Must be called from within an // event handler such as click. May return false if it failed, but // this is not always possible. Browser support for Chrome 43+, // Firefox 42+, Safari 10+, Edge and IE 10+. // IE: The clipboard feature may be disabled by an administrator. By // default a prompt is shown the first time the clipboard is // used (per session). function copyToClipboard(text: string) { if (window.clipboardData && window.clipboardData.setData) { // IE specific code path to prevent textarea being shown while dialog is visible. return window.clipboardData.setData("Text", text); } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) { const textarea = document.createElement("textarea"); textarea.textContent = text; textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in MS Edge. document.body.appendChild(textarea); textarea.select(); try { return document.execCommand("copy"); // Security exception may be thrown by some browsers. } catch (ex) { console.warn("Copy to clipboard failed.", ex); return false; } finally { document.body.removeChild(textarea); } } } export function formatDuration(seconds: number): string { const parts: string[] = []; if (seconds >= 3600) { const hours = Math.floor(seconds / 3600); parts.push(String(hours)); parts.push('h'); seconds = seconds % 3600; } if (seconds >= 60) { const minutes = Math.floor(seconds / 60); if (minutes > 0) { parts.push(String(minutes)); parts.push('m'); seconds = seconds % 60; } } if (seconds >= 0) { parts.push(String(seconds)); parts.push('s'); } return parts.join(''); }
the_stack
import Dictionary from '../../../util/Dictionary'; import Rectangle from '../../geometry/Rectangle'; import Geometry from '../../geometry/Geometry'; import Point from '../../geometry/Point'; import { Graph } from '../../Graph'; import Cell from '../../cell/datatypes/Cell'; import CellArray from '../../cell/datatypes/CellArray'; /** * @class GraphLayout * * Base class for all layout algorithms in mxGraph. Main public functions are * {@link moveCell} for handling a moved cell within a layouted parent, and {@link execute} for * running the layout on a given parent cell. * * Known Subclasses: * * {@link mxCircleLayout}, {@link mxCompactTreeLayout}, {@link mxCompositeLayout}, * {@link mxFastOrganicLayout}, {@link mxParallelEdgeLayout}, {@link mxPartitionLayout}, * {@link mxStackLayout} */ class GraphLayout { constructor(graph: Graph) { this.graph = graph; } /** * Reference to the enclosing {@link mxGraph}. */ graph: Graph = null; /** * Boolean indicating if the bounding box of the label should be used if * its available. Default is true. */ useBoundingBox: boolean = true; /** * The parent cell of the layout, if any */ parent: Cell = null; /** * Notified when a cell is being moved in a parent that has automatic * layout to update the cell state (eg. index) so that the outcome of the * layout will position the vertex as close to the point (x, y) as * possible. * * Empty implementation. * * @param cell {@link mxCell} which has been moved. * @param x X-coordinate of the new cell location. * @param y Y-coordinate of the new cell location. */ moveCell(cell: Cell, x: number, y: number): void {} /** * Function: resizeCell * * Notified when a cell is being resized in a parent that has automatic * layout to update the other cells in the layout. * * Empty implementation. * * Parameters: * * cell - <mxCell> which has been moved. * bounds - <mxRectangle> that represents the new cell bounds. */ resizeCell(cell: Cell, bounds: Rectangle, prev?: Cell) {} /** * Executes the layout algorithm for the children of the given parent. * * @param parent {@link mxCell} whose children should be layed out. */ execute(parent: Cell): void {} /** * Returns the graph that this layout operates on. */ getGraph(): Graph { return this.graph; } /** * Returns the constraint for the given key and cell. The optional edge and * source arguments are used to return inbound and outgoing routing- * constraints for the given edge and vertex. This implementation always * returns the value for the given key in the style of the given cell. * * @param key Key of the constraint to be returned. * @param cell {@link mxCell} whose constraint should be returned. * @param edge Optional {@link mxCell} that represents the connection whose constraint * should be returned. Default is null. * @param source Optional boolean that specifies if the connection is incoming * or outgoing. Default is null. */ getConstraint(key: string, cell: Cell, edge?: Cell, source?: boolean): any { return this.graph.getCurrentCellStyle(cell)[key]; } /** * Traverses the (directed) graph invoking the given function for each * visited vertex and edge. The function is invoked with the current vertex * and the incoming edge as a parameter. This implementation makes sure * each vertex is only visited once. The function may return false if the * traversal should stop at the given vertex. * * Example: * * (code) * mxLog.show(); * var cell = graph.getSelectionCell(); * graph.traverse(cell, false, function(vertex, edge) * { * mxLog.debug(graph.getLabel(vertex)); * }); * (end) * * @param vertex {@link mxCell} that represents the vertex where the traversal starts. * @param directed Optional boolean indicating if edges should only be traversed * from source to target. Default is true. * @param func Visitor function that takes the current vertex and the incoming * edge as arguments. The traversal stops if the function returns false. * @param edge Optional {@link mxCell} that represents the incoming edge. This is * null for the first step of the traversal. * @param visited Optional {@link Dictionary} of cell paths for the visited cells. */ traverse( vertex: Cell, directed?: boolean, func?: Function, edge?: Cell, visited?: Dictionary<Cell, boolean> ): void { if (func != null && vertex != null) { directed = directed != null ? directed : true; visited = visited || new Dictionary(); if (!visited.get(vertex)) { visited.put(vertex, true); const result = func(vertex, edge); if (result == null || result) { const edgeCount = vertex.getEdgeCount(); if (edgeCount > 0) { for (let i = 0; i < edgeCount; i += 1) { const e = vertex.getEdgeAt(i); const isSource = e.getTerminal(true) === vertex; if (!directed || isSource) { const next = this.graph.view.getVisibleTerminal(e, !isSource); this.traverse(next, directed, func, e, visited); } } } } } } } /** * Returns true if the given parent is an ancestor of the given child. * * @param parent {@link mxCell} that specifies the parent. * @param child {@link mxCell} that specifies the child. * @param traverseAncestors boolean whether to */ isAncestor(parent: Cell, child: Cell, traverseAncestors?: boolean): boolean { if (!traverseAncestors) { return child.getParent() === parent; } if (child === parent) { return false; } while (child != null && child !== parent) { child = child.getParent(); } return child === parent; } /** * Returns a boolean indicating if the given {@link mxCell} is movable or * bendable by the algorithm. This implementation returns true if the given * cell is movable in the graph. * * @param cell {@link mxCell} whose movable state should be returned. */ isVertexMovable(cell: Cell): boolean { return this.graph.isCellMovable(cell); } /** * Returns a boolean indicating if the given {@link mxCell} should be ignored by * the algorithm. This implementation returns false for all vertices. * * @param vertex {@link mxCell} whose ignored state should be returned. */ isVertexIgnored(vertex: Cell): boolean { return !vertex.isVertex() || !vertex.isVisible(); } /** * Returns a boolean indicating if the given {@link mxCell} should be ignored by * the algorithm. This implementation returns false for all vertices. * * @param cell {@link mxCell} whose ignored state should be returned. */ isEdgeIgnored(edge: Cell): boolean { const model = this.graph.getModel(); return ( !edge.isEdge() || !edge.isVisible() || edge.getTerminal(true) == null || edge.getTerminal(false) == null ); } /** * Disables or enables the edge style of the given edge. */ setEdgeStyleEnabled(edge: Cell, value: any): void { this.graph.setCellStyles('noEdgeStyle', value ? '0' : '1', [edge]); } /** * Disables or enables orthogonal end segments of the given edge. */ setOrthogonalEdge(edge: Cell, value: any): void { this.graph.setCellStyles('orthogonal', value ? '1' : '0', [edge]); } /** * Determines the offset of the given parent to the parent * of the layout */ getParentOffset(parent: Cell): Point { const result = new Point(); if (parent != null && parent !== this.parent) { const model = this.graph.getModel(); if (model.isAncestor(this.parent, parent)) { let parentGeo = parent.getGeometry(); while (parent !== this.parent) { result.x += parentGeo.x; result.y += parentGeo.y; parent = parent.getParent(); parentGeo = parent.getGeometry(); } } } return result; } /** * Replaces the array of mxPoints in the geometry of the given edge * with the given array of mxPoints. */ setEdgePoints(edge: Cell, points: Point[]): void { if (edge != null) { const { model } = this.graph; let geometry = edge.getGeometry(); if (geometry == null) { geometry = new Geometry(); geometry.setRelative(true); } else { geometry = geometry.clone(); } if (this.parent != null && points != null) { const parent = edge.getParent(); const parentOffset = this.getParentOffset(parent); for (let i = 0; i < points.length; i += 1) { points[i].x = points[i].x - parentOffset.x; points[i].y = points[i].y - parentOffset.y; } } geometry.points = points; model.setGeometry(edge, geometry); } } /** * Sets the new position of the given cell taking into account the size of * the bounding box if {@link useBoundingBox} is true. The change is only carried * out if the new location is not equal to the existing location, otherwise * the geometry is not replaced with an updated instance. The new or old * bounds are returned (including overlapping labels). * * @param cell {@link mxCell} whose geometry is to be set. * @param x Integer that defines the x-coordinate of the new location. * @param y Integer that defines the y-coordinate of the new location. */ setVertexLocation(cell: Cell, x: number, y: number): Rectangle { const model = this.graph.getModel(); let geometry = cell.getGeometry(); let result = null; if (geometry != null) { result = new Rectangle(x, y, geometry.width, geometry.height); // Checks for oversize labels and shifts the result // TODO: Use mxUtils.getStringSize for label bounds if (this.useBoundingBox) { const state = this.graph.getView().getState(cell); if (state != null && state.text != null && state.text.boundingBox != null) { const { scale } = this.graph.getView(); const box = state.text.boundingBox; if (state.text.boundingBox.x < state.x) { x += (state.x - box.x) / scale; result.width = box.width; } if (state.text.boundingBox.y < state.y) { y += (state.y - box.y) / scale; result.height = box.height; } } } if (this.parent != null) { const parent = cell.getParent(); if (parent != null && parent !== this.parent) { const parentOffset = this.getParentOffset(parent); x -= parentOffset.x; y -= parentOffset.y; } } if (geometry.x !== x || geometry.y !== y) { geometry = geometry.clone(); geometry.x = x; geometry.y = y; model.setGeometry(cell, geometry); } } return result; } /** * Returns an {@link Rectangle} that defines the bounds of the given cell or * the bounding box if {@link useBoundingBox} is true. */ getVertexBounds(cell: Cell): Rectangle { let geo = cell.getGeometry(); // Checks for oversize label bounding box and corrects // the return value accordingly // TODO: Use mxUtils.getStringSize for label bounds if (this.useBoundingBox) { const state = this.graph.getView().getState(cell); if (state != null && state.text != null && state.text.boundingBox != null) { const { scale } = this.graph.getView(); const tmp = state.text.boundingBox; const dx0 = Math.max(state.x - tmp.x, 0) / scale; const dy0 = Math.max(state.y - tmp.y, 0) / scale; const dx1 = Math.max(tmp.x + tmp.width - (state.x + state.width), 0) / scale; const dy1 = Math.max(tmp.y + tmp.height - (state.y + state.height), 0) / scale; geo = new Rectangle( geo.x - dx0, geo.y - dy0, geo.width + dx0 + dx1, geo.height + dy0 + dy1 ); } } if (this.parent != null) { const parent = cell.getParent(); geo = geo.clone(); if (parent != null && parent !== this.parent) { const parentOffset = this.getParentOffset(parent); geo.x += parentOffset.x; geo.y += parentOffset.y; } } return new Rectangle(geo.x, geo.y, geo.width, geo.height); } /** * Function: arrangeGroups * * Shortcut to <mxGraph.updateGroupBounds> with moveGroup set to true. */ arrangeGroups( cells: CellArray, border: Rectangle, topBorder, rightBorder, bottomBorder, leftBorder ) { return this.graph.updateGroupBounds( cells, border, true, topBorder, rightBorder, bottomBorder, leftBorder ); } } export default GraphLayout;
the_stack
import * as Fs from 'fs'; import * as Path from 'path'; import Bluebird from 'bluebird'; import { EventEmitter } from 'events'; import d from 'debug'; import Parser from './parser'; import Protocol from './protocol'; import Stats from './sync/stats'; import Entry from './sync/entry'; import PushTransfer from './sync/pushtransfer'; import PullTransfer from './sync/pulltransfer'; import Connection from './connection'; import { Callback } from '../Callback'; import { Readable } from 'stream'; const TEMP_PATH = '/data/local/tmp'; const DEFAULT_CHMOD = 0o644; const DATA_MAX_LENGTH = 65536; const debug = d('adb:sync'); interface ENOENT extends Error { errno: 34; code: 'ENOENT'; path: string; } export default class Sync extends EventEmitter { private parser: Parser; public static temp(path: string): string { return `${TEMP_PATH}/${Path.basename(path)}`; } constructor(private connection: Connection) { super(); // this.connection = connection; this.parser = this.connection.parser as Parser; } public stat(path: string, callback?: Callback<Stats>): Bluebird<Stats> { this._sendCommandWithArg(Protocol.STAT, path); return this.parser .readAscii(4) .then((reply) => { switch (reply) { case Protocol.STAT: return this.parser.readBytes(12).then((stat) => { const mode = stat.readUInt32LE(0); const size = stat.readUInt32LE(4); const mtime = stat.readUInt32LE(8); if (mode === 0) { return this._enoent(path); } else { return new Stats(mode, size, mtime); } }); case Protocol.FAIL: return this._readError(); default: return this.parser.unexpected(reply, 'STAT or FAIL'); } }) .nodeify(callback); } public readdir(path: string, callback?: Callback<Entry[]>): Bluebird<Entry[]> { const files: Entry[] = []; const readNext = () => { return this.parser.readAscii(4).then((reply) => { switch (reply) { case Protocol.DENT: return this.parser.readBytes(16).then((stat) => { const mode = stat.readUInt32LE(0); const size = stat.readUInt32LE(4); const mtime = stat.readUInt32LE(8); const namelen = stat.readUInt32LE(12); return this.parser.readBytes(namelen).then(function (name) { const nameString = name.toString(); // Skip '.' and '..' to match Node's fs.readdir(). if (!(nameString === '.' || nameString === '..')) { files.push(new Entry(nameString, mode, size, mtime)); } return readNext(); }); }); case Protocol.DONE: return this.parser.readBytes(16).then(function () { return files; }); case Protocol.FAIL: return this._readError(); default: return this.parser.unexpected(reply, 'DENT, DONE or FAIL'); } }); }; this._sendCommandWithArg(Protocol.LIST, path); return readNext().nodeify(callback); } public push(contents: string | Readable, path: string, mode?: number): PushTransfer { if (typeof contents === 'string') { return this.pushFile(contents, path, mode); } else { return this.pushStream(contents, path, mode); } } pushFile(file: string, path: string, mode = DEFAULT_CHMOD): PushTransfer { mode || (mode = DEFAULT_CHMOD); return this.pushStream(Fs.createReadStream(file), path, mode); } public pushStream(stream: Readable, path: string, mode = DEFAULT_CHMOD): PushTransfer { mode |= Stats.S_IFREG; this._sendCommandWithArg(Protocol.SEND, `${path},${mode}`); return this._writeData(stream, Math.floor(Date.now() / 1000)); } public pull(path: string): PullTransfer { this._sendCommandWithArg(Protocol.RECV, `${path}`); return this._readData(); } public end(): Sync { this.connection.end(); return this; } public tempFile(path: string): string { return Sync.temp(path); } private _writeData(stream: Readable, timeStamp: number): PushTransfer { const transfer = new PushTransfer(); const writeData = () => { let readableListener: () => void; let connErrorListener: (err: Error) => void; let endListener: () => void; let errorListener: (err: Error) => void; let resolver = Bluebird.defer(); const writer = Bluebird.resolve(); endListener = () => { writer.then(() => { this._sendCommandWithLength(Protocol.DONE, timeStamp); return resolver.resolve(); }); }; stream.on('end', endListener); const waitForDrain = () => { resolver = Bluebird.defer(); const drainListener = () => { resolver.resolve(); }; this.connection.on('drain', drainListener); return resolver.promise.finally(() => { return this.connection.removeListener('drain', drainListener); }); }; const track = () => transfer.pop(); const writeNext = () => { let chunk: Buffer; if ((chunk = stream.read(DATA_MAX_LENGTH) || stream.read())) { this._sendCommandWithLength(Protocol.DATA, chunk.length); transfer.push(chunk.length); if (this.connection.write(chunk, track)) { return writeNext(); } else { return waitForDrain().then(writeNext); } } else { return Bluebird.resolve(); } }; readableListener = () => writer.then(writeNext); stream.on('readable', readableListener); errorListener = (err) => resolver.reject(err); stream.on('error', errorListener); connErrorListener = (err: Error) => { stream.destroy(err); this.connection.end(); resolver.reject(err); }; this.connection.on('error', connErrorListener); return resolver.promise.finally(() => { stream.removeListener('end', endListener); stream.removeListener('readable', readableListener); stream.removeListener('error', errorListener); this.connection.removeListener('error', connErrorListener); return writer.cancel(); }); }; const readReply = () => { return this.parser.readAscii(4).then((reply) => { switch (reply) { case Protocol.OKAY: return this.parser.readBytes(4).then(function () { return true; }); case Protocol.FAIL: return this._readError(); default: return this.parser.unexpected(reply, 'OKAY or FAIL'); } }); }; // While I can't think of a case that would break this double-Promise // writer-reader arrangement right now, it's not immediately obvious // that the code is correct and it may or may not have some failing // edge cases. Refactor pending. const writer = writeData() // .cancellable() .catch(Bluebird.CancellationError, () => { return this.connection.end(); }) .catch(function (err) { transfer.emit('error', err); return reader.cancel(); }); const reader = readReply() .catch(Bluebird.CancellationError, () => true) .catch((err) => { transfer.emit('error', err); return writer.cancel(); }) .finally(() => { return transfer.end(); }); transfer.on('cancel', () => { writer.cancel(); reader.cancel(); }); return transfer; } private _readData(): PullTransfer { const transfer = new PullTransfer(); const readNext = () => { return this.parser.readAscii(4).then((reply) => { switch (reply) { case Protocol.DATA: return this.parser.readBytes(4).then((lengthData) => { const length = lengthData.readUInt32LE(0); return this.parser.readByteFlow(length, transfer).then(readNext); }); case Protocol.DONE: return this.parser.readBytes(4).then(function () { return true; }); case Protocol.FAIL: return this._readError(); default: return this.parser.unexpected(reply, 'DATA, DONE or FAIL'); } }); }; const reader = readNext() .catch(Bluebird.CancellationError, () => this.connection.end()) .catch((err: Error) => transfer.emit('error', err)) .finally(function () { transfer.removeListener('cancel', cancelListener); return transfer.end(); }); const cancelListener = () => reader.cancel(); transfer.on('cancel', cancelListener); return transfer; } // eslint-disable-next-line @typescript-eslint/no-explicit-any private _readError(): Bluebird<any> { return this.parser .readBytes(4) .then((length: Buffer) => { return this.parser.readBytes(length.readUInt32LE(0)).then((buf: Buffer) => { return Bluebird.reject(new Parser.FailError(buf.toString())); }); }) .finally(() => { return this.parser.end(); }); } private _sendCommandWithLength(cmd: string, length: number): Connection { if (cmd !== Protocol.DATA) { debug(cmd); } const payload = Buffer.alloc(cmd.length + 4); payload.write(cmd, 0, cmd.length); payload.writeUInt32LE(length, cmd.length); return this.connection.write(payload); } private _sendCommandWithArg(cmd: string, arg: string): Connection { debug(`${cmd} ${arg}`); const arglen = Buffer.byteLength(arg, 'utf-8'); const payload = Buffer.alloc(cmd.length + 4 + arglen); let pos = 0; payload.write(cmd, pos, cmd.length); pos += cmd.length; payload.writeUInt32LE(arglen, pos); pos += 4; payload.write(arg, pos); return this.connection.write(payload); } // eslint-disable-next-line @typescript-eslint/no-explicit-any private _enoent(path: string): Bluebird<any> { const err: ENOENT = new Error(`ENOENT, no such file or directory '${path}'`) as ENOENT; err.errno = 34; err.code = 'ENOENT'; err.path = path; return Bluebird.reject(err); } }
the_stack
import Page = require('../../../../../base/Page'); import Response = require('../../../../../http/response'); import V1 = require('../../../V1'); import { SerializableClass } from '../../../../../interfaces'; type UserConversationNotificationLevel = 'default'|'muted'; type UserConversationState = 'inactive'|'active'|'closed'; /** * Initialize the UserConversationList * * @param version - Version of the resource * @param chatServiceSid - The unique ID of the Conversation Service this conversation belongs to. * @param userSid - The unique ID for the User. */ declare function UserConversationList(version: V1, chatServiceSid: string, userSid: string): UserConversationListInstance; /** * Options to pass to update * * @property lastReadMessageIndex - The index of the last read Message. * @property lastReadTimestamp - The date of the last message read in conversation by the user. * @property notificationLevel - The Notification Level of this User Conversation. */ interface UserConversationInstanceUpdateOptions { lastReadMessageIndex?: number; lastReadTimestamp?: Date; notificationLevel?: UserConversationNotificationLevel; } interface UserConversationListInstance { /** * @param sid - sid of instance */ (sid: string): UserConversationContext; /** * Streams UserConversationInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Function to process each record */ each(callback?: (item: UserConversationInstance, done: (err?: Error) => void) => void): void; /** * Streams UserConversationInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Function to process each record */ each(opts?: UserConversationListInstanceEachOptions, callback?: (item: UserConversationInstance, done: (err?: Error) => void) => void): void; /** * Constructs a user_conversation * * @param conversationSid - The unique SID identifier of the Conversation. */ get(conversationSid: string): UserConversationContext; /** * Retrieve a single target page of UserConversationInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ getPage(callback?: (error: Error | null, items: UserConversationPage) => any): Promise<UserConversationPage>; /** * Retrieve a single target page of UserConversationInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param targetUrl - API-generated URL for the requested results page * @param callback - Callback to handle list of records */ getPage(targetUrl?: string, callback?: (error: Error | null, items: UserConversationPage) => any): Promise<UserConversationPage>; /** * Lists UserConversationInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ list(callback?: (error: Error | null, items: UserConversationInstance[]) => any): Promise<UserConversationInstance[]>; /** * Lists UserConversationInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ list(opts?: UserConversationListInstanceOptions, callback?: (error: Error | null, items: UserConversationInstance[]) => any): Promise<UserConversationInstance[]>; /** * Retrieve a single page of UserConversationInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ page(callback?: (error: Error | null, items: UserConversationPage) => any): Promise<UserConversationPage>; /** * Retrieve a single page of UserConversationInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ page(opts?: UserConversationListInstancePageOptions, callback?: (error: Error | null, items: UserConversationPage) => any): Promise<UserConversationPage>; /** * Provide a user-friendly representation */ toJSON(): any; } /** * Options to pass to each * * @property callback - * Function to process each record. If this and a positional * callback are passed, this one will be used * @property done - Function to be called upon completion of streaming * @property limit - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) */ interface UserConversationListInstanceEachOptions { callback?: (item: UserConversationInstance, done: (err?: Error) => void) => void; done?: Function; limit?: number; pageSize?: number; } /** * Options to pass to list * * @property limit - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) */ interface UserConversationListInstanceOptions { limit?: number; pageSize?: number; } /** * Options to pass to page * * @property pageNumber - Page Number, this value is simply for client state * @property pageSize - Number of records to return, defaults to 50 * @property pageToken - PageToken provided by the API */ interface UserConversationListInstancePageOptions { pageNumber?: number; pageSize?: number; pageToken?: string; } interface UserConversationPayload extends UserConversationResource, Page.TwilioResponsePayload { } interface UserConversationResource { account_sid: string; attributes: string; chat_service_sid: string; conversation_sid: string; conversation_state: UserConversationState; created_by: string; date_created: Date; date_updated: Date; friendly_name: string; last_read_message_index: number; links: string; notification_level: UserConversationNotificationLevel; participant_sid: string; timers: object; unique_name: string; unread_messages_count: number; url: string; user_sid: string; } interface UserConversationSolution { chatServiceSid?: string; userSid?: string; } declare class UserConversationContext { /** * Initialize the UserConversationContext * * @param version - Version of the resource * @param chatServiceSid - The SID of the Conversation Service that the resource is associated with. * @param userSid - The unique SID identifier of the User. * @param conversationSid - The unique SID identifier of the Conversation. */ constructor(version: V1, chatServiceSid: string, userSid: string, conversationSid: string); /** * fetch a UserConversationInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: UserConversationInstance) => any): Promise<UserConversationInstance>; /** * remove a UserConversationInstance * * @param callback - Callback to handle processed record */ remove(callback?: (error: Error | null, items: UserConversationInstance) => any): Promise<boolean>; /** * Provide a user-friendly representation */ toJSON(): any; /** * update a UserConversationInstance * * @param callback - Callback to handle processed record */ update(callback?: (error: Error | null, items: UserConversationInstance) => any): Promise<UserConversationInstance>; /** * update a UserConversationInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts?: UserConversationInstanceUpdateOptions, callback?: (error: Error | null, items: UserConversationInstance) => any): Promise<UserConversationInstance>; } declare class UserConversationInstance extends SerializableClass { /** * Initialize the UserConversationContext * * @param version - Version of the resource * @param payload - The instance payload * @param chatServiceSid - The unique ID of the Conversation Service this conversation belongs to. * @param userSid - The unique ID for the User. * @param conversationSid - The unique SID identifier of the Conversation. */ constructor(version: V1, payload: UserConversationPayload, chatServiceSid: string, userSid: string, conversationSid: string); private _proxy: UserConversationContext; accountSid: string; attributes: string; chatServiceSid: string; conversationSid: string; conversationState: UserConversationState; createdBy: string; dateCreated: Date; dateUpdated: Date; /** * fetch a UserConversationInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: UserConversationInstance) => any): Promise<UserConversationInstance>; friendlyName: string; lastReadMessageIndex: number; links: string; notificationLevel: UserConversationNotificationLevel; participantSid: string; /** * remove a UserConversationInstance * * @param callback - Callback to handle processed record */ remove(callback?: (error: Error | null, items: UserConversationInstance) => any): Promise<boolean>; timers: any; /** * Provide a user-friendly representation */ toJSON(): any; uniqueName: string; unreadMessagesCount: number; /** * update a UserConversationInstance * * @param callback - Callback to handle processed record */ update(callback?: (error: Error | null, items: UserConversationInstance) => any): Promise<UserConversationInstance>; /** * update a UserConversationInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts?: UserConversationInstanceUpdateOptions, callback?: (error: Error | null, items: UserConversationInstance) => any): Promise<UserConversationInstance>; url: string; userSid: string; } declare class UserConversationPage extends Page<V1, UserConversationPayload, UserConversationResource, UserConversationInstance> { /** * Initialize the UserConversationPage * * @param version - Version of the resource * @param response - Response from the API * @param solution - Path solution */ constructor(version: V1, response: Response<string>, solution: UserConversationSolution); /** * Build an instance of UserConversationInstance * * @param payload - Payload response from the API */ getInstance(payload: UserConversationPayload): UserConversationInstance; /** * Provide a user-friendly representation */ toJSON(): any; } export { UserConversationContext, UserConversationInstance, UserConversationInstanceUpdateOptions, UserConversationList, UserConversationListInstance, UserConversationListInstanceEachOptions, UserConversationListInstanceOptions, UserConversationListInstancePageOptions, UserConversationNotificationLevel, UserConversationPage, UserConversationPayload, UserConversationResource, UserConversationSolution, UserConversationState }
the_stack
import { AfterContentInit, AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, Output, Renderer2, ViewChild } from "@angular/core"; import {IPopupable, PopupInfo, PopupOptions, PopupPositionType, PopupService} from "../../common/service/popup.service"; import {SimpleNode, SimpleTreeData} from "../../common/core/data/tree-data"; import {AbstractJigsawComponent} from "../../common/common"; import {CommonUtils} from '../../common/core/utils/common-utils'; import {JigsawList, JigsawListOption} from "../list-and-tile/list"; import {JigsawTheme} from "../../common/core/theming/theme"; export type MenuTheme = 'light' | 'dark' | 'navigation'; export class MenuOptions { data?: SimpleTreeData; width?: string | number; height?: string | number; theme?: MenuTheme; options?: PopupOptions; showBorder?: boolean; select?: EventEmitter<SimpleNode>; } /** * @internal */ export const cascadingMenuFlag = class CascadingMenuFlag { }; /** * @internal */ export function closeAllContextMenu(popups: PopupInfo[]): void { popups.filter(popup => popup.extra === cascadingMenuFlag) .forEach(popup => popup.dispose()); } /** * @internal */ @Component({ template: ` <div style="width:0px; height:0px;" jigsawCascadingMenu [jigsawCascadingMenuOptions]="initData?.options" [jigsawCascadingMenuWidth]="initData?.width" [jigsawCascadingMenuHeight]="initData?.height" [jigsawCascadingMenuShowBorder]="initData?.showBorder" [jigsawCascadingMenuData]="initData?.data" [jigsawCascadingMenuTheme]="initData?.theme" [jigsawCascadingMenuPosition]="'bottomLeft'" [jigsawCascadingMenuOpen]="true" [jigsawCascadingMenuOpenTrigger]="'none'" [jigsawCascadingMenuCloseTrigger]="'click'" (jigsawCascadingMenuSelect)="onSelect($event)" (jigsawCascadingMenuClose)="close.emit()"> </div> `, changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawMenuHelper implements IPopupable { public answer: EventEmitter<any> = new EventEmitter<any>(); public initData: MenuOptions; public close = new EventEmitter<void>(); public onSelect(node: SimpleNode): void { if (this.initData && this.initData.select) { this.initData.select.emit(node); } } } @Component({ selector: 'jigsaw-menu, j-menu', template: ` <j-list #menuList [width]="_$realWidth" [height]="_$realHeight" [perfectScrollbar]="{wheelSpeed: 0.5, minScrollbarLength: 20,suppressScrollX: true}"> <j-list-option *ngFor="let node of _$realData?.nodes; index as index" [value]="node" jigsawCascadingMenu [jigsawCascadingMenuOptions]="_$realOptions" [jigsawCascadingMenuWidth]="_$realWidth" [jigsawCascadingMenuHeight]="_$realHeight" [jigsawCascadingMenuShowBorder]="_$realShowBorder" [jigsawCascadingMenuData]="node" [jigsawCascadingMenuTheme]="_$realTheme" [jigsawCascadingMenuPosition]="'rightTop'" [jigsawCascadingMenuOpenTrigger]="'mouseenter'" [jigsawCascadingMenuInitData]="{select:_$realSelect}" [disabled]="node.disabled" (click)=" !node.disabled && !!node.label && select.emit(node); !node.disabled && !!node.label && initData?.select?.emit(node); " (mouseenter)="_$mouseenter(index, node)" (mouseleave)="_$mouseleave(index)" [style.minHeight]="_$getMinHeight(node.label)"> <div class="jigsaw-menu-list-title" *ngIf="!!node.label && _$realTheme != 'navigation'" [title]="_$getTitle(node.label,index,'jigsaw-menu-list-title')" [ngStyle]="_$getTitleWidth(node)"> <i class="{{node.icon}}"></i> <span>{{node.label}}</span> </div> <hr *ngIf="!node.label && _$realTheme != 'navigation'"> <div class="jigsaw-menu-list-sub-title" *ngIf="_$realTheme != 'navigation'" [title]="_$getTitle(node.subTitle,index,'jigsaw-menu-list-sub-title')" [ngStyle]="_$getSubTitleWidth(node, index)"> <span *ngIf="!!node.subTitle">{{node.subTitle}}</span> <i class="{{node.subIcon}} jigsaw-menu-subIcon" *ngIf="!!node.subIcon && !_$isSubTitleOverflow(index)"></i> <i *ngIf="node.nodes && node.nodes.length>0" class="iconfont iconfont-e144"></i> </div> <div class="jigsaw-menu-navigation-title" *ngIf="_$realTheme == 'navigation'"> {{node.label}} <i *ngIf="node.nodes && node.nodes.length>0 && !!node.label " class="iconfont iconfont-e144" style="position: absolute;right: 10px;line-height: 40px"></i> <hr *ngIf="!node.label"> </div> </j-list-option> </j-list>`, host: { '(click)': "_$onClick($event)", '[class.jigsaw-menu-dark]': "_$realTheme == 'dark'", '[class.jigsaw-menu-light]': "_$realTheme == 'light'", '[class.jigsaw-menu-navigation]': "_$realTheme == 'navigation'", }, changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawMenu extends AbstractJigsawComponent implements IPopupable, AfterViewInit, AfterContentInit { public initData: MenuOptions; /** * @internal */ public get _$realData(): SimpleTreeData { const realData = this.initData?.data || this.data; this._fixNodeIcon(realData); return realData; } /** * @internal */ public get _$realOptions(): PopupOptions { return this.initData && this.initData.options ? this.initData.options : this.options; } /** * @internal */ public get _$realWidth(): number | string { return this.initData && this.initData.width ? this.initData.width : this.width; } /** * @internal */ public get _$realHeight(): number | string { return this.initData && this.initData.height ? this.initData.height : this.height; } /** * @internal */ public get _$realShowBorder(): boolean { return this.initData && this.initData.hasOwnProperty('showBorder') ? this.initData.showBorder : this.showBorder; } /** * @internal */ public get _$realTheme(): MenuTheme { let theme = this.initData && this.initData.theme ? this.initData.theme : this.theme; if (theme !== 'light' && theme !== 'dark' && theme !== 'navigation') { theme = 'light'; } return theme; } /** * @internal */ public get _$realSelect(): any { if (this.initData && this.initData.select) { return this.initData.select; } else { return this.select; } } /** * @NoMarkForCheckRequired */ @Input() public data: SimpleTreeData; /** * @NoMarkForCheckRequired */ @Input() public options: PopupOptions; /** * @NoMarkForCheckRequired */ @Input() public showBorder: boolean = true; /** * @NoMarkForCheckRequired */ @Input() public theme: MenuTheme = JigsawTheme.majorStyle || 'light'; /** * @internal */ @Output() public answer: EventEmitter<any> = new EventEmitter<any>(); @Output() public select: EventEmitter<SimpleNode> = new EventEmitter<SimpleNode>(); @ViewChild('menuList', {read: ElementRef}) private _menuListElement: ElementRef; @ViewChild('menuList') private _menuListInstance: JigsawList; constructor(private _renderer: Renderer2, private _elementRef: ElementRef, private _changeDetectorRef: ChangeDetectorRef) { super(); } /** * @internal */ public _$onClick(event: any) { event.stopPropagation(); event.preventDefault(); } private _fixNodeIcon(data: SimpleTreeData) { if (!data.nodes) { return; } data.nodes.filter(node => !node.icon && !!node.iconUnicode) .forEach((node: SimpleTreeData) => { node.icon = 'iconfont iconfont-' + node.iconUnicode; }); } ngAfterViewInit() { this._setBorder(); } ngAfterContentInit() { } private _setBorder() { if (!this._$realShowBorder) { this._menuListElement.nativeElement.style.border = 'none'; } } private _resetListItems(): JigsawListOption[] { const listItems = this._menuListInstance._items.toArray(); listItems.forEach(listItem => { listItem.selected = false; }); return listItems; } /** * @internal */ public _$mouseenter(index: number, node: SimpleNode) { const listItems = this._resetListItems(); if (!node.label || node.disabled) { return; } listItems[index].selected = true; } /** * @internal */ public _$mouseleave(index: number) { const popups = PopupService.instance.popups; const realIndex = popups.findIndex(pop => pop.element == this._elementRef.nativeElement); const popupInfo = popups[realIndex + 1]; if (!popupInfo || popupInfo.extra !== cascadingMenuFlag) { const listItems = this._menuListInstance._items.toArray(); listItems[index].selected = false; } } /** * @internal */ public _$getMinHeight(label: string): string { if (!label) { return "1px"; } else { return "32px"; } } /** * @internal */ public _$getTitleWidth(node: SimpleNode): any { if (!node.nodes || node.nodes.length == 0) { return {maxWidth: '100%'}; } else { // 5是给有子节点时,留下的箭头;2是给标题和箭头之间留点距离;一共为7px return {maxWidth: 'calc(100% - 7px)'}; } } /** * @internal */ _$isSubTitleOverflow(index: number): boolean { if (!this._menuListElement) { return false; } const listOptionElements = this._menuListElement.nativeElement.children; const subTitleElement = listOptionElements[index].getElementsByClassName("jigsaw-menu-list-sub-title")[0].children[0]; return subTitleElement.offsetWidth < subTitleElement.scrollWidth; } /** * @internal */ public _$getSubTitleWidth(node: SimpleNode, index: number): any { if (!this._menuListElement || node.disabled || !node.label) { return {maxWidth: 'auto'}; } const listOptionElements = this._menuListElement.nativeElement.children; const titleElement = listOptionElements[index].getElementsByClassName("jigsaw-menu-list-title")[0]; if (!titleElement) { return {maxWidth: 'auto'}; } const wrapElement = titleElement.parentElement; // 14是给有子节点时,留下的箭头; const minWidth = node.nodes && node.nodes.length > 0 ? 14 : 0; if (titleElement.offsetWidth < wrapElement.offsetWidth - minWidth - 6) { return {maxWidth: `${wrapElement.offsetWidth - titleElement.offsetWidth - 6}px`}; } else { return {width: `${minWidth}px`}; } } /** * @internal */ public _$getTitle(label: string, index: number, titleClass: string): string { if (!this._menuListElement || !label) { return ''; } const listOptionElements = this._menuListElement.nativeElement.children; const titleElement = listOptionElements[index].getElementsByClassName(titleClass)[0]; return titleElement && titleElement.scrollWidth > titleElement.offsetWidth ? label : ''; } public static show(event: MouseEvent, options: MenuOptions | SimpleTreeData, callback?: (node: SimpleNode) => void, context?: any): PopupInfo { if (!event) { return; } event.stopPropagation(); event.preventDefault(); if (!options) { return; } closeAllContextMenu(PopupService.allPopups); const ctx = options instanceof SimpleTreeData ? {data: options} : options; if (!ctx.select) { ctx.select = new EventEmitter<SimpleNode>(); } const selectSubscription = ctx.select.subscribe((node: SimpleNode) => { CommonUtils.safeInvokeCallback(context, callback, [node]); }); const popOpt = { pos: {x: event.clientX, y: event.clientY}, posType: PopupPositionType.fixed }; const info = PopupService.instance.popup(JigsawMenuHelper, popOpt, ctx); info.extra = cascadingMenuFlag; const closeSubscription = info.instance.close.subscribe(() => { selectSubscription.unsubscribe(); closeSubscription.unsubscribe(); }); return info; } }
the_stack
import { RefObject, useCallback, useMemo, useRef } from "react"; import { flatten2DArray, reverseArray } from "ariakit-utils/array"; import { useControlledState, useInitialValue, useLiveRef, } from "ariakit-utils/hooks"; import { useStorePublisher } from "ariakit-utils/store"; import { SetState } from "ariakit-utils/types"; import { CollectionState, CollectionStateProps, useCollectionState, } from "../collection/collection-state"; import { Item, Orientation, findFirstEnabledItem, flipItems, getActiveId, getEnabledItems, getItemsInRow, getOppositeOrientation, groupItemsByRows, normalizeRows, verticalizeItems, } from "./__utils"; /** * Provides state for the `Composite` component. * @example * ```jsx * const composite = useCompositeState(); * <Composite state={composite}> * <CompositeItem>Item 1</CompositeItem> * <CompositeItem>Item 2</CompositeItem> * <CompositeItem>Item 3</CompositeItem> * </Composite> * ``` */ export function useCompositeState<T extends Item = Item>({ orientation = "both", rtl = false, virtualFocus = false, focusLoop = false, focusWrap = false, focusShift = false, ...props }: CompositeStateProps<T> = {}): CompositeState<T> { const collection = useCollectionState(props); const baseRef = useRef<HTMLDivElement>(null); const [moves, setMoves] = useControlledState(0, props.moves, props.setMoves); const [_activeId, setActiveId] = useControlledState( props.defaultActiveId, props.activeId, props.setActiveId ); const activeId = useMemo( () => getActiveId(collection.items, _activeId), [collection.items, _activeId] ); const initialActiveId = useInitialValue(activeId); const includesBaseElement = props.includesBaseElement ?? initialActiveId === null; const activeIdRef = useLiveRef(activeId); const move = useCallback((id?: Item["id"]) => { // move() does nothing if (id === undefined) return; setMoves((prevMoves) => prevMoves + 1); setActiveId(id); }, []); const first = useCallback(() => { const firstItem = findFirstEnabledItem(collection.items); return firstItem?.id; }, [collection.items]); const last = useCallback(() => { const firstItem = findFirstEnabledItem(reverseArray(collection.items)); return firstItem?.id; }, [collection.items]); const getNextId = useCallback( ( items: Item[], orientation: Orientation, hasNullItem: boolean, skip?: number ): string | null | undefined => { // RTL doesn't make sense on vertical navigation const isHorizontal = orientation !== "vertical"; const isRTL = rtl && isHorizontal; const allItems = isRTL ? reverseArray(items) : items; // If there's no item focused, we just move the first one. if (activeIdRef.current == null) { return findFirstEnabledItem(allItems)?.id; } const activeItem = allItems.find( (item) => item.id === activeIdRef.current ); // If there's no item focused, we just move to the first one. if (!activeItem) { return findFirstEnabledItem(allItems)?.id; } const isGrid = !!activeItem.rowId; const activeIndex = allItems.indexOf(activeItem); const nextItems = allItems.slice(activeIndex + 1); const nextItemsInRow = getItemsInRow(nextItems, activeItem.rowId); // Home, End, PageUp, PageDown if (skip !== undefined) { const nextEnabledItemsInRow = getEnabledItems( nextItemsInRow, activeIdRef.current ); const nextItem = nextEnabledItemsInRow.slice(skip)[0] || // If we can't find an item, just return the last one. nextEnabledItemsInRow[nextEnabledItemsInRow.length - 1]; return nextItem?.id; } const oppositeOrientation = getOppositeOrientation( // If it's a grid and orientation is not set, it's a next/previous // call, which is inherently horizontal. up/down will call next with // orientation set to vertical by default (see below on up/down // methods). isGrid ? orientation || "horizontal" : orientation ); const canLoop = focusLoop && focusLoop !== oppositeOrientation; const canWrap = isGrid && focusWrap && focusWrap !== oppositeOrientation; // previous and up methods will set hasNullItem, but when calling next // directly, hasNullItem will only be true if if it's not a grid and // focusLoop is set to true, which means that pressing right or down keys // on grids will never focus the composite container element. On // one-dimensional composites that don't loop, pressing right or down // keys also doesn't focus on the composite container element. hasNullItem = hasNullItem || (!isGrid && canLoop && includesBaseElement); if (canLoop) { const loopItems = canWrap && !hasNullItem ? allItems : getItemsInRow(allItems, activeItem.rowId); const sortedItems = flipItems( loopItems, activeIdRef.current, hasNullItem ); const nextItem = findFirstEnabledItem(sortedItems, activeIdRef.current); return nextItem?.id; } if (canWrap) { const nextItem = findFirstEnabledItem( // We can use nextItems, which contains all the next items, including // items from other rows, to wrap between rows. However, if there is // a null item (the composite container), we'll only use the next // items in the row. So moving next from the last item will focus on // the composite container. On grid composites, horizontal navigation // never focuses on the composite container, only vertical. hasNullItem ? nextItemsInRow : nextItems, activeIdRef.current ); const nextId = hasNullItem ? nextItem?.id || null : nextItem?.id; return nextId; } const nextItem = findFirstEnabledItem( nextItemsInRow, activeIdRef.current ); if (!nextItem && hasNullItem) { return null; } return nextItem?.id; }, [focusLoop, focusWrap, includesBaseElement] ); const next = useCallback( (skip?: number) => { return getNextId(collection.items, orientation, false, skip); }, [getNextId, collection.items, orientation] ); const previous = useCallback( (skip?: number) => { // If activeId is initially set to null or if includesBaseElement is set // to true, then the composite container will be focusable while // navigating with arrow keys. But, if it's a grid, we don't want to // focus on the composite container with horizontal navigation. const isGrid = !!findFirstEnabledItem(collection.items)?.rowId; const hasNullItem = !isGrid && includesBaseElement; return getNextId( reverseArray(collection.items), orientation, hasNullItem, skip ); }, [collection.items, getNextId, orientation, includesBaseElement] ); const down = useCallback( (skip?: number) => { const shouldShift = focusShift && !skip; // First, we make sure rows have the same number of items by filling it // with disabled fake items. Then, we reorganize the items. const verticalItems = verticalizeItems( flatten2DArray( normalizeRows( groupItemsByRows(collection.items), activeIdRef.current, shouldShift ) ) ); const canLoop = focusLoop && focusLoop !== "horizontal"; // Pressing down arrow key will only focus on the composite container if // loop is true, both, or vertical. const hasNullItem = canLoop && includesBaseElement; return getNextId(verticalItems, "vertical", hasNullItem, skip); }, [collection.items, getNextId, focusShift, focusLoop] ); const up = useCallback( (skip?: number) => { const shouldShift = focusShift && !skip; const verticalItems = verticalizeItems( reverseArray( flatten2DArray( normalizeRows( groupItemsByRows(collection.items), activeIdRef.current, shouldShift ) ) ) ); // If activeId is initially set to null, we'll always focus on the // composite container when the up arrow key is pressed in the first row. const hasNullItem = includesBaseElement; return getNextId(verticalItems, "vertical", hasNullItem, skip); }, [collection.items, getNextId, focusShift] ); const state = useMemo( () => ({ ...collection, baseRef, orientation, rtl, virtualFocus, focusLoop, focusWrap, focusShift, moves, setMoves, includesBaseElement, activeId, setActiveId, move, next, previous, up, down, first, last, }), [ collection, baseRef, orientation, rtl, virtualFocus, focusLoop, focusWrap, focusShift, moves, setMoves, includesBaseElement, activeId, setActiveId, move, next, previous, up, down, first, last, ] ); return useStorePublisher(state); } export type CompositeState<T extends Item = Item> = CollectionState<T> & { /** * The ref to the `Composite` element. */ baseRef: RefObject<HTMLElement>; /** * If enabled, the composite element will act as an * [aria-activedescendant](https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_focus_activedescendant) * container instead of [roving * tabindex](https://www.w3.org/TR/wai-aria-practices/#kbd_roving_tabindex). * DOM focus will remain on the composite while its items receive virtual * focus. * @default false */ virtualFocus: boolean; /** * Defines the orientation of the composite widget. If the composite has a * single row or column (one-dimensional), the `orientation` value determines * which arrow keys can be used to move focus: * - `both`: all arrow keys work. * - `horizontal`: only left and right arrow keys work. * - `vertical`: only up and down arrow keys work. * * It doesn't have any effect on two-dimensional composites. * @default "both" */ orientation: Orientation; /** * Determines how the `next` and `previous` functions will behave. If `rtl` is * set to `true`, they will be inverted. This only affects the composite * widget behavior. You still need to set `dir="rtl"` on HTML/CSS. * @default false */ rtl: boolean; /** * On one-dimensional composites: * - `true` loops from the last item to the first item and vice-versa. * - `horizontal` loops only if `orientation` is `horizontal` or not set. * - `vertical` loops only if `orientation` is `vertical` or not set. * - If `activeId` is initially set to `null`, the composite element will be * focused in between the last and first items. * * On two-dimensional composites: * - `true` loops from the last row/column item to the first item in the * same row/column and vice-versa. If it's the last item in the last row, * it moves to the first item in the first row and vice-versa. * - `horizontal` loops only from the last row item to the first item in the * same row. * - `vertical` loops only from the last column item to the first item in * the column row. * - If `activeId` is initially set to `null`, vertical loop will have no * effect as moving down from the last row or up from the first row will * focus the composite element. * - If `focusWrap` matches the value of `focusLoop`, it'll wrap between the * last item in the last row or column and the first item in the first row * or column and vice-versa. * @default false */ focusLoop: boolean | Orientation; /** * **Has effect only on two-dimensional composites**. If enabled, moving to * the next item from the last one in a row or column will focus the first * item in the next row or column and vice-versa. * - `true` wraps between rows and columns. * - `horizontal` wraps only between rows. * - `vertical` wraps only between columns. * - If `focusLoop` matches the value of `focusWrap`, it'll wrap between the last * item in the last row or column and the first item in the first row or * column and vice-versa. * @default false */ focusWrap: boolean | Orientation; /** * **Has effect only on two-dimensional composites**. If enabled, moving up * or down when there's no next item or the next item is disabled will shift * to the item right before it. * @default false */ focusShift: boolean; /** * The number of times the `move` function has been called. * @default 0 * @example * const composite = useCompositeState(); * composite.moves; // 0 * composite.move(null); * // On the next render * composite.moves; // 1 */ moves: number; /** * Sets the `moves` state. */ setMoves: SetState<CompositeState["moves"]>; /** * Indicates whether the `Composite` element should be included in the focus * order. * @default false */ includesBaseElement: boolean; /** * The current focused item `id`. * - `undefined` will automatically focus the first enabled composite item. * - `null` will focus the base composite element and users will be able to * navigate out of it using arrow keys. * - If `activeId` is initially set to `null`, the base composite element * itself will have focus and users will be able to navigate to it using * arrow keys. */ activeId?: Item["id"]; /** * Sets the `activeId` state without moving focus. */ setActiveId: SetState<CompositeState["activeId"]>; /** * Moves focus to a given item id. * @example * const composite = useCompositeState(); * const onClick = () => { * composite.move("item-2"); // focus item 2 * }; */ move: (id?: Item["id"]) => void; /** * Returns the id of the next item. * @example * const composite = useCompositeState(); * const onClick = () => { * composite.move(composite.next()); // focus next item * }; */ next: (skip?: number) => Item["id"] | undefined; /** * Returns the id of the previous item. * @example * const composite = useCompositeState(); * const onClick = () => { * composite.move(composite.previous()); // focus previous item * }; */ previous: (skip?: number) => Item["id"] | undefined; /** * Returns the id of the item above. * @example * const composite = useCompositeState(); * const onClick = () => { * composite.move(composite.up()); // focus the item above * }; */ up: (skip?: number) => Item["id"] | undefined; /** * Returns the id of the item below. * @example * const composite = useCompositeState(); * const onClick = () => { * composite.move(composite.down()); // focus the item below * }; */ down: (skip?: number) => Item["id"] | undefined; /** * Returns the id of the first item. * @example * const composite = useCompositeState(); * const onClick = () => { * composite.move(composite.first()); // focus the first item * }; */ first: () => Item["id"] | undefined; /** * Returns the id of the last item. * @example * const composite = useCompositeState(); * const onClick = () => { * composite.move(composite.last()); // focus the last item * }; */ last: () => Item["id"] | undefined; }; export type CompositeStateProps<T extends Item = Item> = CollectionStateProps<T> & Partial< Pick< CompositeState<T>, | "virtualFocus" | "orientation" | "rtl" | "focusLoop" | "focusWrap" | "focusShift" | "moves" | "includesBaseElement" | "activeId" > > & { /** * The composite item id that should be focused when the composite is * initialized. * @example * ```jsx * const composite = useCompositeState({ defaultActiveId: "item-2" }); * <Composite state={composite}> * <CompositeItem>Item 1</CompositeItem> * <CompositeItem id="item-2">Item 2</CompositeItem> * <CompositeItem>Item 3</CompositeItem> * </Composite> * ``` */ defaultActiveId?: CompositeState<T>["activeId"]; /** * Function that will be called when setting the composite `moves` state. * @example * const [moves, setMoves] = useState(0); * useCompositeState({ moves, setMoves }); */ setMoves?: (moves: CompositeState<T>["moves"]) => void; /** * Function that will be called when setting the composite `activeId`. * @example * function MyComposite({ activeId, onActiveIdChange }) { * const composite = useCompositeState({ * activeId, * setActiveId: onActiveIdChange, * }); * } */ setActiveId?: (activeId: CompositeState<T>["activeId"]) => void; };
the_stack
import Config from "../config/Config"; import DSLCombinerTypes from "../constants/DSLCombinerTypes"; import DSLExpression from "../structs/DSLExpression"; import DSLFilterTypes from "../constants/DSLFilterTypes"; import DSLUtil from "./DSLUtil"; const STRING_EXPR = /(['"])[^\1]+?(?=\1)\1/; const DSLUpdateUtil = { /** * Default function used by the `applyAdd` function to detect is similar node * already exists in the expression. * * @param {FilterNode} referenceNode - The node to compare against * @param {FilterNode} compareNode - The node to compare * @returns {Boolean} Returns `true` if there is no similar node in the AST */ defaultNodeCompareFunction(referenceNode, compareNode) { if (referenceNode.filterType !== compareNode.filterType) { return false; } if (referenceNode.filterType !== DSLFilterTypes.ATTRIB) { return true; } return referenceNode.filterParams.label === compareNode.filterParams.label; }, /** * Clean-up a DSL expression without damaging it's semantic meaning. * This function does the following: * * - Expands single parenthesis (ex. "foo (bar) baz") * - Trims consecutive whitespaces (ex "foo bar ") * - Trims consecutive or empty commas (ex. "foo,, bar, , baz") * - Removes orphan comas (ex. ", foo (, bar) label:,baz") * * @param {String} src - The source expression string * @returns {String} The cleaned-up expression string */ cleanupExpressionString(src) { const strings = []; // Extract string expressions so we have a simpler expression to work with src = src.replace(STRING_EXPR, (match) => { strings.push(match); return "\x01"; }); // Perform clean-ups src = src.replace(/\(([^ ,]+)\)/g, "$1"); // Single parenthesis src = src.replace(/\s+/g, " "); // Consecutive spaces src = src.replace(/,(\s*,)+/g, ","); // Consecutive commas src = src.replace(/^\s*,/g, ""); // Orphan commas (left-side) src = src.replace(/,\s*$/g, ""); // Orphan commas (right-side) src = src.replace(/\(\s*,\s*/g, "("); // Orphan commas (left-paren) src = src.replace(/\s*,\s*\)/g, ")"); // Orphan commas (right-paren) src = src.replace(/:,+/g, ":"); // Orphan commas (multi-value) src = src.replace(/\s+,\s+/g, ", "); // Commas with surrounding whitespace // Put strings back src = src.replace(/\x01/g, () => strings.pop(0)); return src.trim(); }, /** * Update the text representation of a node in order to match the new node. * * @param {String} src - The source expression string * @param {ASTNode} node - The ast node to replace * @param {ASTNode} newNode - The ast node to replace with * @param {number} offset - The offset to apply on position indices * @returns {String} Returns the updated string */ updateNodeTextString(src, node, newNode, offset = 0) { const { position, filterType } = node; let textStart = position[0][0] + offset; let textEnd = position[0][1] + offset; let { filterParams: { text }, } = newNode; if (filterType !== newNode.filterType) { if (Config.environment === "development") { throw new Error("Trying to update a node with a mismatching node!"); } return src; } // Attributes have their value on position[1] if (filterType === DSLFilterTypes.ATTRIB) { textStart = position[1][0] + offset; textEnd = position[1][1] + offset; } // Exact matches are not quoted, so quote them now if (filterType === DSLFilterTypes.EXACT) { text = `"${text}"`; } // Replace the entire string return src.substr(0, textStart) + text + src.substr(textEnd); }, /** * Update the label of an attribute node with the new label from `newNode`. * * @param {String} src - The source expression string * @param {ASTNode} node - The ast node to replace * @param {ASTNode} newNode - The ast node to replace with * @param {number} offset - The offset to apply on position indices * @returns {String} Returns the updated string */ updateNodeValueString(src, node, newNode, offset = 0) { const { position, filterType } = node; const labelStart = position[0][0] + offset; const labelEnd = position[0][1] + offset; const { filterParams: { label }, } = newNode; if (filterType !== newNode.filterType) { if (Config.environment === "development") { throw new Error("Trying to update a node with a mismatching node!"); } return src; } if (filterType !== DSLFilterTypes.ATTRIB) { if (Config.environment === "development") { throw new Error("Trying to update a non-label node as label!"); } return src; } // Replace only label return src.substr(0, labelStart) + `${label}:` + src.substr(labelEnd); }, /** * Delete the string representation of the given expression string * * @param {String} src - The source expression string * @param {ASTNode} node - The node node to replace * @param {number} offset - The offset to apply on position indices * @param {Boolean} [bleed] - Set to true if you want to trim bleeding spaces * @returns {String} Returns the updated string */ deleteNodeString(src, node, offset = 0) { const { position } = node; const endingRegex = /^(\s|,\s|$)/; let start = position[0][0] + offset; let end = position[0][1] + offset; // Attributes have a special handling, in case they are multi-valued if (node.filterType === DSLFilterTypes.ATTRIB) { // Change scope to value start = position[1][0] + offset; end = position[1][1] + offset; // Increase the scope to the entire value only if the node is the only // value in the attribute. To test for this, we are checking if the // character right before is the label ':' and the character after is a // whitespace or a comma with whitespace if (src[start - 1] === ":" && endingRegex.exec(src.substr(end))) { start = position[0][0] + offset; end = position[1][1] + offset; // Otherwise, bleed left to remove the comma if we are part of multi-value } else if (src[start - 1] === ",") { start -= 1; // Or bleed right if we were the first item } else if (src[end] === ",") { end += 1; } } // Strip and cleanup any damage caused by it return DSLUpdateUtil.cleanupExpressionString( src.substr(0, start) + src.substr(end) ); }, /** * Append the given node at the end of the expression * * @param {String} src - The source expression string * @param {ASTNode} node - The node node to add * @param {ASTNode} fullAst - The representation of the current full AST * @param {number} offset - The offset to apply on position indices * @param {DSLCombinerTypes} [combiner] - The combiner operation to use * @returns {String} Returns the updated string */ addNodeString( src, node, fullAst, offset = 0, combiner = DSLCombinerTypes.AND ) { const whitespaceRegex = /\s+$/; // Trim tailing whitespace src = src.replace(whitespaceRegex, ""); // If we are using AND operation just append node string with whitespace if (combiner === DSLCombinerTypes.AND) { if (src) { src += " "; } return src + DSLUtil.getNodeString(node); } // If we are using OR operator, just append if (src) { src += ", "; } return src + DSLUtil.getNodeString(node); }, /** * Append the given node at the end of the given attribute node, creating * or updating a multi-value node * * @param {String} src - The source expression string * @param {ASTNode} node - The node node to append * @param {ASTNode} toNode - The attribute node to add onto * @param {number} offset - The offset to apply on position indices * @returns {String} Returns the updated string */ appendAttribNodeString(src, node, toNode, offset = 0) { // Inject only the text into the given label return ( src.substr(0, toNode.position[1][1] + offset) + "," + node.filterParams.text + src.substr(toNode.position[1][1] + offset) ); }, /** * Append the given nodes at the end of the expression * * @param {DSLExpression} expression - The expression to update * @param {Array} nodes - The node(s) to append * @param {Object} [options] - Combine options * @returns {DSLExpression} expression - The updated expression */ applyAdd(expression, nodes, options = {}) { const { nodeCompareFunction = DSLUpdateUtil.defaultNodeCompareFunction, itemCombiner = DSLCombinerTypes.AND, newCombiner = DSLCombinerTypes.AND, } = options; const expressionUpdate = nodes.reduce( ({ value, offset }, node, index) => { let combiner = itemCombiner; let newValue = value; // Find all the existing nodes, related to the node being added const relevantNodes = DSLUtil.reduceAstFilters( expression.ast, (memo, filterNode) => { if (nodeCompareFunction(node, filterNode)) { memo.push(filterNode); } return memo; }, [] ); // If this is the first element, check if we have previous relevant // occurrences in the expression, and if yes, use the `newCombiner` if (index === 0) { if (relevantNodes.length === 0) { combiner = newCombiner; } } // In case of an OR operator + attribute node we take special care for // creating multi-value attributes when possible if ( combiner === DSLCombinerTypes.OR && node.filterType === DSLFilterTypes.ATTRIB && relevantNodes.length !== 0 && node.filterParams.label === relevantNodes[0].filterParams.label ) { newValue = DSLUpdateUtil.appendAttribNodeString( value, node, relevantNodes[0], offset ); // Otherwise we use regular node concatenation } else { newValue = DSLUpdateUtil.addNodeString( value, node, expression.ast, offset, combiner ); } // Update offset in order for the token positions in the expression // AST to be processable even after the updates offset += newValue.length - value.length; return { offset, value: newValue }; }, { offset: 0, value: expression.value } ); return new DSLExpression(expressionUpdate.value); }, /** * Delete the given list of nodes from the expression * * @param {DSLExpression} expression - The expression to update * @param {Array} nodes - The node(s) to delete * @returns {DSLExpression} expression - The updated expression */ applyDelete(expression, nodes) { const newExpression = nodes.reduce( ({ value, offset }, node) => { // Delete value const newValue = DSLUpdateUtil.deleteNodeString(value, node, offset); // This action shifted the location of the tokens in the original // expression. Update offset. offset += newValue.length - value.length; return { value: newValue, offset }; }, { value: expression.value, offset: 0 } ); return new DSLExpression(newExpression.value); }, /** * Replace the given nodes in the expression with the new array of nodes * taking correcting actions if the lengths do not match. * * @param {DSLExpression} expression - The expression to update * @param {Array} nodes - The node(s) to update * @param {Array} newNodes - The node(s) to update with * @param {Object} [addOptions] - Options for adding nodes * @returns {DSLExpression} expression - The updated expression */ applyReplace(expression, nodes, newNodes, addOptions = {}) { const updateCount = Math.min(nodes.length, newNodes.length); let expressionValue = expression.value; let offset = 0; // First update nodes for (let i = 0; i < updateCount; ++i) { const updateNode = nodes[i]; const withNode = newNodes[i]; // Update expression value const newValue = DSLUpdateUtil.updateNodeTextString( expressionValue, updateNode, withNode, offset ); // This action may have shifted the location of the tokens // in the original expression. Update offset. offset += newValue.length - expressionValue.length; expressionValue = newValue; } // Compile the status of the expression so far const newExpression = new DSLExpression(expressionValue); // Delete nodes using applyDelete if (newNodes.length < nodes.length) { // Note that the offsets in the `nodes` array point to the old expression // so they have to be updated in order to match the new expression const deleteNodes = nodes.slice(updateCount).map((node) => { node.position = node.position.map(([start, end]) => [ start + offset, end + offset, ]); return node; }); // We avoid expanding the logic of `applyDelete` and instead we use the // 'hack' of the offset update above in order to isolate the logic. return DSLUpdateUtil.applyDelete(newExpression, deleteNodes); } // Add nodes using applyAdd if (newNodes.length > nodes.length) { return DSLUpdateUtil.applyAdd( newExpression, newNodes.slice(updateCount), addOptions ); } // Otherwise just return the expression return newExpression; }, }; export default DSLUpdateUtil;
the_stack
import {ObjectLoader} from 'three/src/loaders/ObjectLoader'; import {Object3D} from 'three/src/core/Object3D'; import {BufferGeometry} from 'three/src/core/BufferGeometry'; import {Poly} from '../../engine/Poly'; import {ModuleName} from '../../engine/poly/registers/modules/Common'; import {LineSegments} from 'three/src/objects/LineSegments'; import {Mesh} from 'three/src/objects/Mesh'; import {Points} from 'three/src/objects/Points'; import {LineBasicMaterial} from 'three/src/materials/LineBasicMaterial'; import {MeshLambertMaterial} from 'three/src/materials/MeshLambertMaterial'; import {PointsMaterial} from 'three/src/materials/PointsMaterial'; import {DRACOLoader} from '../../modules/three/examples/jsm/loaders/DRACOLoader'; import {GLTF, GLTFLoader} from '../../modules/three/examples/jsm/loaders/GLTFLoader'; import {CoreUserAgent} from '../UserAgent'; import {CoreBaseLoader} from './_Base'; import {BaseNodeType} from '../../engine/nodes/_Base'; import {TypeAssert} from '../../engine/poly/Assert'; import {PolyScene} from '../../engine/index_all'; import {isBooleanTrue} from '../BooleanValue'; export enum GeometryFormat { AUTO = 'auto', DRC = 'drc', FBX = 'fbx', JSON = 'json', GLTF = 'gltf', GLTF_WITH_DRACO = 'gltf_with_draco', OBJ = 'obj', PDB = 'pdb', PLY = 'ply', STL = 'stl', } export const GEOMETRY_FORMATS: GeometryFormat[] = [ GeometryFormat.AUTO, GeometryFormat.DRC, GeometryFormat.FBX, GeometryFormat.JSON, GeometryFormat.GLTF, GeometryFormat.GLTF_WITH_DRACO, GeometryFormat.OBJ, GeometryFormat.PDB, GeometryFormat.PLY, GeometryFormat.STL, ]; enum GeometryExtension { DRC = 'drc', FBX = 'fbx', GLTF = 'gltf', GLB = 'glb', OBJ = 'obj', PDB = 'pdb', PLY = 'ply', STL = 'stl', } export const GEOMETRY_EXTENSIONS: GeometryExtension[] = [ GeometryExtension.DRC, GeometryExtension.FBX, GeometryExtension.GLTF, GeometryExtension.GLB, GeometryExtension.OBJ, GeometryExtension.PDB, GeometryExtension.PLY, GeometryExtension.STL, ]; interface PdbObject { geometryAtoms: BufferGeometry; geometryBonds: BufferGeometry; } type MaxConcurrentLoadsCountMethod = () => number; interface CoreLoaderGeometryOptions { url: string; format: GeometryFormat; } export class CoreLoaderGeometry extends CoreBaseLoader { private static _default_mat_mesh = new MeshLambertMaterial(); private static _default_mat_point = new PointsMaterial(); private static _default_mat_line = new LineBasicMaterial(); constructor( protected _options: CoreLoaderGeometryOptions, protected _scene: PolyScene, protected _node?: BaseNodeType ) { super(_options.url, _scene, _node); } load(on_success: (objects: Object3D[]) => void, on_error: (error: string) => void) { this._load() .then((object) => { on_success(object); }) .catch((error) => { on_error(error); }); } private _load(): Promise<any> { return new Promise(async (resolve, reject) => { const url = await this._urlToLoad(); const ext = this.extension(); if (ext == GeometryFormat.JSON && this._options.format == GeometryFormat.AUTO) { CoreLoaderGeometry.increment_in_progress_loads_count(); await CoreLoaderGeometry.wait_for_max_concurrent_loads_queue_freed(); fetch(url) .then(async (response) => { const data = await response.json(); const obj_loader = new ObjectLoader(this.loadingManager); obj_loader.parse(data, (obj) => { CoreLoaderGeometry.decrement_in_progress_loads_count(); resolve(this.on_load_success(obj.children[0])); }); }) .catch((error) => { CoreLoaderGeometry.decrement_in_progress_loads_count(); reject(error); }); } else { const loader = await this._loaderForFormat(); if (loader) { CoreLoaderGeometry.increment_in_progress_loads_count(); await CoreLoaderGeometry.wait_for_max_concurrent_loads_queue_freed(); loader.load( url, (object: Object3D | BufferGeometry | PdbObject | GLTF) => { this.on_load_success(object).then((object2) => { CoreLoaderGeometry.decrement_in_progress_loads_count(); resolve(object2); }); }, undefined, (error_message: ErrorEvent) => { Poly.warn('error loading', url, error_message); CoreLoaderGeometry.decrement_in_progress_loads_count(); reject(error_message); } ); } else { const error_message = `format not supported (${ext})`; reject(error_message); } } }); } private async on_load_success(object: Object3D | BufferGeometry | PdbObject | GLTF): Promise<Object3D[]> { const ext = this.extension(); if (ext == GeometryFormat.JSON) { return [object as Object3D]; } // WARNING // when exporting with File->Export // `object instanceof Object3D` returns false even if it is an Object3D. // This needs to be investigated, but in the mean time, we test with .isObject3D const obj = object as Object3D; if (isBooleanTrue(obj.isObject3D)) { switch (ext) { case GeometryExtension.PDB: return this.on_load_succes_pdb(object as PdbObject); case GeometryExtension.OBJ: return [obj]; // [object] //.children default: return [obj]; } } const geo = object as BufferGeometry; if (geo.isBufferGeometry) { switch (ext) { case GeometryExtension.DRC: return this.on_load_succes_drc(geo); default: return [new Mesh(geo)]; } } const gltf = object as GLTF; if (gltf.scene != null) { switch (ext) { case GeometryExtension.GLTF: return this.on_load_succes_gltf(gltf); case GeometryExtension.GLB: return this.on_load_succes_gltf(gltf); default: return [obj]; } } const pdbobject = object as PdbObject; if (pdbobject.geometryAtoms || pdbobject.geometryBonds) { switch (ext) { case GeometryExtension.PDB: return this.on_load_succes_pdb(pdbobject); default: return []; } } return []; } private on_load_succes_drc(geometry: BufferGeometry): Object3D[] { const mesh = new Mesh(geometry, CoreLoaderGeometry._default_mat_mesh); return [mesh]; } private on_load_succes_gltf(gltf: GLTF): Object3D[] { const scene = gltf['scene']; scene.animations = gltf.animations; return [scene]; } private on_load_succes_pdb(pdb_object: PdbObject): Object3D[] { const atoms = new Points(pdb_object.geometryAtoms, CoreLoaderGeometry._default_mat_point); const bonds = new LineSegments(pdb_object.geometryBonds, CoreLoaderGeometry._default_mat_line); return [atoms, bonds]; } static moduleNamesFromFormat(format: GeometryFormat, ext: string): ModuleName[] | void { switch (format) { case GeometryFormat.AUTO: return this.moduleNamesFromExt(ext); case GeometryFormat.DRC: return [ModuleName.DRACOLoader]; case GeometryFormat.FBX: return [ModuleName.FBXLoader]; case GeometryFormat.JSON: return []; case GeometryFormat.GLTF: return [ModuleName.GLTFLoader]; case GeometryFormat.GLTF_WITH_DRACO: return [ModuleName.GLTFLoader, ModuleName.DRACOLoader]; case GeometryFormat.OBJ: return [ModuleName.OBJLoader]; case GeometryFormat.PDB: return [ModuleName.PDBLoader]; case GeometryFormat.PLY: return [ModuleName.PLYLoader]; case GeometryFormat.STL: return [ModuleName.STLLoader]; } TypeAssert.unreachable(format); } static moduleNamesFromExt(ext: string): ModuleName[] | void { switch (ext) { case GeometryExtension.DRC: return [ModuleName.DRACOLoader]; case GeometryExtension.FBX: return [ModuleName.FBXLoader]; case GeometryExtension.GLTF: return [ModuleName.GLTFLoader]; case GeometryExtension.GLB: return [ModuleName.GLTFLoader, ModuleName.DRACOLoader]; case GeometryExtension.OBJ: return [ModuleName.OBJLoader]; case GeometryExtension.PDB: return [ModuleName.PDBLoader]; case GeometryExtension.PLY: return [ModuleName.PLYLoader]; case GeometryExtension.STL: return [ModuleName.STLLoader]; } } private async _loaderForFormat() { const format = this._options.format; switch (format) { case GeometryFormat.AUTO: return this._loaderForExt(); case GeometryFormat.DRC: return this.loader_for_drc(this._node); case GeometryFormat.FBX: return this.loader_for_fbx(); case GeometryFormat.JSON: return; case GeometryFormat.GLTF: return this.loader_for_gltf(); case GeometryFormat.GLTF_WITH_DRACO: return this.loader_for_glb(this._node); case GeometryFormat.OBJ: return this.loader_for_obj(); case GeometryFormat.PDB: return this.loader_for_pdb(); case GeometryFormat.PLY: return this.loader_for_ply(); case GeometryFormat.STL: return this.loader_for_stl(); } TypeAssert.unreachable(format); } private async _loaderForExt() { const ext = this.extension(); switch (ext.toLowerCase()) { case GeometryExtension.DRC: return this.loader_for_drc(this._node); case GeometryExtension.FBX: return this.loader_for_fbx(); case GeometryExtension.GLTF: return this.loader_for_gltf(); case GeometryExtension.GLB: return this.loader_for_glb(this._node); case GeometryExtension.OBJ: return this.loader_for_obj(); case GeometryExtension.PDB: return this.loader_for_pdb(); case GeometryExtension.PLY: return this.loader_for_ply(); case GeometryExtension.STL: return this.loader_for_stl(); } } loader_for_fbx() { const FBXLoader = Poly.modulesRegister.module(ModuleName.FBXLoader); if (FBXLoader) { return new FBXLoader(this.loadingManager); } } loader_for_gltf() { const GLTFLoader = Poly.modulesRegister.module(ModuleName.GLTFLoader); if (GLTFLoader) { return new GLTFLoader(this.loadingManager); } } static async loader_for_drc(node?: BaseNodeType) { const DRACOLoader = Poly.modulesRegister.module(ModuleName.DRACOLoader); if (DRACOLoader) { const draco_loader = new DRACOLoader(this.loadingManager); const root = Poly.libs.root(); const DRACOPath = Poly.libs.DRACOPath(); if (root || DRACOPath) { const decoder_path = `${root || ''}${DRACOPath || ''}/`; if (node) { // const files = ['draco_decoder.js', 'draco_decoder.wasm', 'draco_wasm_wrapper.js']; // for (let file of files) { // const storedUrl = `${DRACOPath}/${file}`; // const fullUrl = `${decoder_path}${file}`; // Poly.blobs.fetchBlob({storedUrl, fullUrl, node}); // } const files = ['draco_decoder.js', 'draco_decoder.wasm', 'draco_wasm_wrapper.js']; await this._loadMultipleBlobGlobal({ files: files.map((file) => { return { storedUrl: `${DRACOPath}/${file}`, fullUrl: `${decoder_path}${file}`, }; }), node, error: 'failed to load draco libraries. Make sure to install them to load .glb files', }); } draco_loader.setDecoderPath(decoder_path); } else { (draco_loader as any).setDecoderPath(undefined); } draco_loader.setDecoderConfig({type: 'js'}); return draco_loader; } } loader_for_drc(node?: BaseNodeType) { return CoreLoaderGeometry.loader_for_drc(node); } private static gltf_loader: GLTFLoader | undefined; private static draco_loader: DRACOLoader | undefined; static async loader_for_glb(node?: BaseNodeType) { const GLTFLoader = Poly.modulesRegister.module(ModuleName.GLTFLoader); const DRACOLoader = Poly.modulesRegister.module(ModuleName.DRACOLoader); if (GLTFLoader && DRACOLoader) { this.gltf_loader = this.gltf_loader || new GLTFLoader(this.loadingManager); this.draco_loader = this.draco_loader || new DRACOLoader(this.loadingManager); const root = Poly.libs.root(); const DRACOGLTFPath = Poly.libs.DRACOGLTFPath(); if (root || DRACOGLTFPath) { const decoder_path = `${root || ''}${DRACOGLTFPath || ''}/`; if (node) { // const files = ['draco_decoder.js', 'draco_decoder.wasm', 'draco_wasm_wrapper.js']; // for (let file of files) { // const storedUrl = `${DRACOGLTFPath}/${file}`; // const fullUrl = `${decoder_path}${file}`; // Poly.blobs.fetchBlob({storedUrl, fullUrl, node}); // } const files = ['draco_decoder.js', 'draco_decoder.wasm', 'draco_wasm_wrapper.js']; await this._loadMultipleBlobGlobal({ files: files.map((file) => { return { storedUrl: `${DRACOGLTFPath}/${file}`, fullUrl: `${decoder_path}${file}`, }; }), node, error: 'failed to load draco libraries. Make sure to install them to load .glb files', }); } this.draco_loader.setDecoderPath(decoder_path); } else { (this.draco_loader as any).setDecoderPath(undefined); } // not having this uses wasm if the relevant libraries are found // draco_loader.setDecoderConfig({type: 'js'}); this.gltf_loader.setDRACOLoader(this.draco_loader); return this.gltf_loader; } } loader_for_glb(node?: BaseNodeType) { return CoreLoaderGeometry.loader_for_glb(node); } loader_for_obj() { const OBJLoader = Poly.modulesRegister.module(ModuleName.OBJLoader); if (OBJLoader) { return new OBJLoader(this.loadingManager); } } loader_for_pdb() { const PDBLoader = Poly.modulesRegister.module(ModuleName.PDBLoader); if (PDBLoader) { return new PDBLoader(this.loadingManager); } } loader_for_ply() { const PLYLoader = Poly.modulesRegister.module(ModuleName.PLYLoader); if (PLYLoader) { return new PLYLoader(this.loadingManager); } } loader_for_stl() { const STLLoader = Poly.modulesRegister.module(ModuleName.STLLoader); if (STLLoader) { return new STLLoader(this.loadingManager); } } // // // CONCURRENT LOADS // // private static MAX_CONCURRENT_LOADS_COUNT: number = CoreLoaderGeometry._init_max_concurrent_loads_count(); private static CONCURRENT_LOADS_DELAY: number = CoreLoaderGeometry._init_concurrent_loads_delay(); private static in_progress_loads_count: number = 0; private static _queue: Array<() => void> = []; private static _maxConcurrentLoadsCountMethod: MaxConcurrentLoadsCountMethod | undefined; public static setMaxConcurrentLoadsCount(method: MaxConcurrentLoadsCountMethod | undefined) { this._maxConcurrentLoadsCountMethod = method; } private static _init_max_concurrent_loads_count(): number { if (this._maxConcurrentLoadsCountMethod) { return this._maxConcurrentLoadsCountMethod(); } return CoreUserAgent.isChrome() ? 4 : 1; // const parser = new UAParser(); // const name = parser.getBrowser().name; // // limit to 4 for non chrome, // // as firefox was seen hanging trying to load multiple glb files // // limit to 1 for safari, // if (name) { // const loads_count_by_browser: PolyDictionary<number> = { // Chrome: 10, // Firefox: 4, // }; // const loads_count = loads_count_by_browser[name]; // if (loads_count != null) { // return loads_count; // } // } // return 1; } private static _init_concurrent_loads_delay(): number { return CoreUserAgent.isChrome() ? 1 : 10; // const parser = new UAParser(); // const name = parser.getBrowser().name; // // add a delay for browsers other than Chrome and Firefox // if (name) { // const delay_by_browser: PolyDictionary<number> = { // Chrome: 1, // Firefox: 10, // Safari: 10, // }; // const delay = delay_by_browser[name]; // if (delay != null) { // return delay; // } // } // return 10; } // public static override_max_concurrent_loads_count(count: number) { // this.MAX_CONCURRENT_LOADS_COUNT = count; // } private static increment_in_progress_loads_count() { this.in_progress_loads_count++; } private static decrement_in_progress_loads_count() { this.in_progress_loads_count--; const queued_resolve = this._queue.pop(); if (queued_resolve) { const delay = this.CONCURRENT_LOADS_DELAY; setTimeout(() => { queued_resolve(); }, delay); } } private static async wait_for_max_concurrent_loads_queue_freed(): Promise<void> { if (this.in_progress_loads_count <= this.MAX_CONCURRENT_LOADS_COUNT) { return; } else { return new Promise((resolve) => { this._queue.push(resolve); }); } } }
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * AutoscaleSettings * __NOTE__: An instance of this class is automatically created for an * instance of the InsightsManagementClient. */ export interface AutoscaleSettings { /** * Lists the autoscale settings for a resource group * * @param {string} resourceGroupName The name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. For * more information please see * https://msdn.microsoft.com/en-us/library/azure/dn931934.aspx * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AutoscaleSettingResourceCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AutoscaleSettingResourceCollection>>; /** * Lists the autoscale settings for a resource group * * @param {string} resourceGroupName The name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. For * more information please see * https://msdn.microsoft.com/en-us/library/azure/dn931934.aspx * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AutoscaleSettingResourceCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AutoscaleSettingResourceCollection} [result] - The deserialized result object if an error did not occur. * See {@link AutoscaleSettingResourceCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.AutoscaleSettingResourceCollection>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.AutoscaleSettingResourceCollection>): void; listByResourceGroup(resourceGroupName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AutoscaleSettingResourceCollection>): void; /** * Creates or updates an autoscale setting. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} autoscaleSettingName The autoscale setting name. * * @param {object} parameters Parameters supplied to the operation. * * @param {array} parameters.profiles the collection of automatic scaling * profiles that specify different scaling parameters for different time * periods. A maximum of 20 profiles can be specified. * * @param {array} [parameters.notifications] the collection of notifications. * * @param {boolean} [parameters.enabled] the enabled flag. Specifies whether * automatic scaling is enabled for the resource. The default value is 'true'. * * @param {string} parameters.autoscaleSettingResourceName the name of the * autoscale setting. * * @param {string} [parameters.targetResourceUri] the resource identifier of * the resource that the autoscale setting should be added to. * * @param {string} [parameters.name] Azure resource name * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AutoscaleSettingResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, autoscaleSettingName: string, parameters: models.AutoscaleSettingResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AutoscaleSettingResource>>; /** * Creates or updates an autoscale setting. * * @param {string} resourceGroupName The name of the resource group. * * @param {string} autoscaleSettingName The autoscale setting name. * * @param {object} parameters Parameters supplied to the operation. * * @param {array} parameters.profiles the collection of automatic scaling * profiles that specify different scaling parameters for different time * periods. A maximum of 20 profiles can be specified. * * @param {array} [parameters.notifications] the collection of notifications. * * @param {boolean} [parameters.enabled] the enabled flag. Specifies whether * automatic scaling is enabled for the resource. The default value is 'true'. * * @param {string} parameters.autoscaleSettingResourceName the name of the * autoscale setting. * * @param {string} [parameters.targetResourceUri] the resource identifier of * the resource that the autoscale setting should be added to. * * @param {string} [parameters.name] Azure resource name * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AutoscaleSettingResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AutoscaleSettingResource} [result] - The deserialized result object if an error did not occur. * See {@link AutoscaleSettingResource} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, autoscaleSettingName: string, parameters: models.AutoscaleSettingResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AutoscaleSettingResource>; createOrUpdate(resourceGroupName: string, autoscaleSettingName: string, parameters: models.AutoscaleSettingResource, callback: ServiceCallback<models.AutoscaleSettingResource>): void; createOrUpdate(resourceGroupName: string, autoscaleSettingName: string, parameters: models.AutoscaleSettingResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AutoscaleSettingResource>): void; /** * Deletes and autoscale setting * * @param {string} resourceGroupName The name of the resource group. * * @param {string} autoscaleSettingName The autoscale setting name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, autoscaleSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes and autoscale setting * * @param {string} resourceGroupName The name of the resource group. * * @param {string} autoscaleSettingName The autoscale setting name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, autoscaleSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, autoscaleSettingName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, autoscaleSettingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets an autoscale setting * * @param {string} resourceGroupName The name of the resource group. * * @param {string} autoscaleSettingName The autoscale setting name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AutoscaleSettingResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, autoscaleSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AutoscaleSettingResource>>; /** * Gets an autoscale setting * * @param {string} resourceGroupName The name of the resource group. * * @param {string} autoscaleSettingName The autoscale setting name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AutoscaleSettingResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AutoscaleSettingResource} [result] - The deserialized result object if an error did not occur. * See {@link AutoscaleSettingResource} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, autoscaleSettingName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AutoscaleSettingResource>; get(resourceGroupName: string, autoscaleSettingName: string, callback: ServiceCallback<models.AutoscaleSettingResource>): void; get(resourceGroupName: string, autoscaleSettingName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AutoscaleSettingResource>): void; /** * Lists the autoscale settings for a resource group * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AutoscaleSettingResourceCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AutoscaleSettingResourceCollection>>; /** * Lists the autoscale settings for a resource group * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AutoscaleSettingResourceCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AutoscaleSettingResourceCollection} [result] - The deserialized result object if an error did not occur. * See {@link AutoscaleSettingResourceCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AutoscaleSettingResourceCollection>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.AutoscaleSettingResourceCollection>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AutoscaleSettingResourceCollection>): void; } /** * @class * ServiceDiagnosticSettingsOperations * __NOTE__: An instance of this class is automatically created for an * instance of the InsightsManagementClient. */ export interface ServiceDiagnosticSettingsOperations { /** * Gets the active diagnostic settings for the specified resource. * * @param {string} resourceUri The identifier of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ServiceDiagnosticSettingsResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceUri: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceDiagnosticSettingsResource>>; /** * Gets the active diagnostic settings for the specified resource. * * @param {string} resourceUri The identifier of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ServiceDiagnosticSettingsResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ServiceDiagnosticSettingsResource} [result] - The deserialized result object if an error did not occur. * See {@link ServiceDiagnosticSettingsResource} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceUri: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceDiagnosticSettingsResource>; get(resourceUri: string, callback: ServiceCallback<models.ServiceDiagnosticSettingsResource>): void; get(resourceUri: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceDiagnosticSettingsResource>): void; /** * Create or update new diagnostic settings for the specified resource. * * @param {string} resourceUri The identifier of the resource. * * @param {object} parameters Parameters supplied to the operation. * * @param {string} [parameters.storageAccountId] The resource ID of the storage * account to which you would like to send Diagnostic Logs. * * @param {string} [parameters.serviceBusRuleId] The service bus rule ID of the * service bus namespace in which you would like to have Event Hubs created for * streaming Diagnostic Logs. The rule ID is of the format: '{service bus * resource ID}/authorizationrules/{key name}'. * * @param {array} [parameters.metrics] the list of metric settings. * * @param {array} [parameters.logs] the list of logs settings. * * @param {string} [parameters.workspaceId] The workspace ID (resource ID of a * Log Analytics workspace) for a Log Analytics workspace to which you would * like to send Diagnostic Logs. Example: * /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2 * * @param {string} [parameters.name] Azure resource name * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ServiceDiagnosticSettingsResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceUri: string, parameters: models.ServiceDiagnosticSettingsResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceDiagnosticSettingsResource>>; /** * Create or update new diagnostic settings for the specified resource. * * @param {string} resourceUri The identifier of the resource. * * @param {object} parameters Parameters supplied to the operation. * * @param {string} [parameters.storageAccountId] The resource ID of the storage * account to which you would like to send Diagnostic Logs. * * @param {string} [parameters.serviceBusRuleId] The service bus rule ID of the * service bus namespace in which you would like to have Event Hubs created for * streaming Diagnostic Logs. The rule ID is of the format: '{service bus * resource ID}/authorizationrules/{key name}'. * * @param {array} [parameters.metrics] the list of metric settings. * * @param {array} [parameters.logs] the list of logs settings. * * @param {string} [parameters.workspaceId] The workspace ID (resource ID of a * Log Analytics workspace) for a Log Analytics workspace to which you would * like to send Diagnostic Logs. Example: * /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2 * * @param {string} [parameters.name] Azure resource name * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ServiceDiagnosticSettingsResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ServiceDiagnosticSettingsResource} [result] - The deserialized result object if an error did not occur. * See {@link ServiceDiagnosticSettingsResource} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceUri: string, parameters: models.ServiceDiagnosticSettingsResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceDiagnosticSettingsResource>; createOrUpdate(resourceUri: string, parameters: models.ServiceDiagnosticSettingsResource, callback: ServiceCallback<models.ServiceDiagnosticSettingsResource>): void; createOrUpdate(resourceUri: string, parameters: models.ServiceDiagnosticSettingsResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceDiagnosticSettingsResource>): void; } /** * @class * AlertRules * __NOTE__: An instance of this class is automatically created for an * instance of the InsightsManagementClient. */ export interface AlertRules { /** * Creates or updates an alert rule. * Request method: PUT Request URI: * https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/microsoft.insights/alertRules/{alert-rule-name}?api-version={api-version} * * @param {string} resourceGroupName The name of the resource group. * * @param {string} ruleName The name of the rule. * * @param {object} parameters The parameters of the rule to create or update. * * @param {string} parameters.alertRuleResourceName the name of the alert rule. * * @param {string} [parameters.description] the description of the alert rule * that will be included in the alert email. * * @param {boolean} parameters.isEnabled the flag that indicates whether the * alert rule is enabled. * * @param {object} [parameters.condition] the condition that results in the * alert rule being activated. * * @param {string} parameters.condition.odatatype Polymorphic Discriminator * * @param {array} [parameters.actions] the array of actions that are performed * when the alert rule becomes active, and when an alert condition is resolved. * * @param {string} [parameters.name] Azure resource name * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AlertRuleResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, ruleName: string, parameters: models.AlertRuleResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertRuleResource>>; /** * Creates or updates an alert rule. * Request method: PUT Request URI: * https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/microsoft.insights/alertRules/{alert-rule-name}?api-version={api-version} * * @param {string} resourceGroupName The name of the resource group. * * @param {string} ruleName The name of the rule. * * @param {object} parameters The parameters of the rule to create or update. * * @param {string} parameters.alertRuleResourceName the name of the alert rule. * * @param {string} [parameters.description] the description of the alert rule * that will be included in the alert email. * * @param {boolean} parameters.isEnabled the flag that indicates whether the * alert rule is enabled. * * @param {object} [parameters.condition] the condition that results in the * alert rule being activated. * * @param {string} parameters.condition.odatatype Polymorphic Discriminator * * @param {array} [parameters.actions] the array of actions that are performed * when the alert rule becomes active, and when an alert condition is resolved. * * @param {string} [parameters.name] Azure resource name * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AlertRuleResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AlertRuleResource} [result] - The deserialized result object if an error did not occur. * See {@link AlertRuleResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, ruleName: string, parameters: models.AlertRuleResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertRuleResource>; createOrUpdate(resourceGroupName: string, ruleName: string, parameters: models.AlertRuleResource, callback: ServiceCallback<models.AlertRuleResource>): void; createOrUpdate(resourceGroupName: string, ruleName: string, parameters: models.AlertRuleResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertRuleResource>): void; /** * Deletes an alert rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} ruleName The name of the rule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, ruleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes an alert rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} ruleName The name of the rule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, ruleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, ruleName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, ruleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets an alert rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} ruleName The name of the rule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AlertRuleResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, ruleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertRuleResource>>; /** * Gets an alert rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} ruleName The name of the rule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AlertRuleResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AlertRuleResource} [result] - The deserialized result object if an error did not occur. * See {@link AlertRuleResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, ruleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertRuleResource>; get(resourceGroupName: string, ruleName: string, callback: ServiceCallback<models.AlertRuleResource>): void; get(resourceGroupName: string, ruleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertRuleResource>): void; /** * List the alert rules within a resource group. * * @param {string} resourceGroupName The name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. For * more information please see * https://msdn.microsoft.com/en-us/library/azure/dn931934.aspx * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AlertRuleResourceCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertRuleResourceCollection>>; /** * List the alert rules within a resource group. * * @param {string} resourceGroupName The name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] The filter to apply on the operation. For * more information please see * https://msdn.microsoft.com/en-us/library/azure/dn931934.aspx * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AlertRuleResourceCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AlertRuleResourceCollection} [result] - The deserialized result object if an error did not occur. * See {@link AlertRuleResourceCollection} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertRuleResourceCollection>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.AlertRuleResourceCollection>): void; listByResourceGroup(resourceGroupName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertRuleResourceCollection>): void; } /** * @class * AlertRuleIncidents * __NOTE__: An instance of this class is automatically created for an * instance of the InsightsManagementClient. */ export interface AlertRuleIncidents { /** * Gets an incident associated to an alert rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} ruleName The name of the rule. * * @param {string} incidentName The name of the incident to retrieve. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Incident>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, ruleName: string, incidentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Incident>>; /** * Gets an incident associated to an alert rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} ruleName The name of the rule. * * @param {string} incidentName The name of the incident to retrieve. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Incident} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Incident} [result] - The deserialized result object if an error did not occur. * See {@link Incident} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, ruleName: string, incidentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Incident>; get(resourceGroupName: string, ruleName: string, incidentName: string, callback: ServiceCallback<models.Incident>): void; get(resourceGroupName: string, ruleName: string, incidentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Incident>): void; /** * Gets a list of incidents associated to an alert rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} ruleName The name of the rule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<IncidentListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByAlertRuleWithHttpOperationResponse(resourceGroupName: string, ruleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.IncidentListResult>>; /** * Gets a list of incidents associated to an alert rule * * @param {string} resourceGroupName The name of the resource group. * * @param {string} ruleName The name of the rule. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {IncidentListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {IncidentListResult} [result] - The deserialized result object if an error did not occur. * See {@link IncidentListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByAlertRule(resourceGroupName: string, ruleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.IncidentListResult>; listByAlertRule(resourceGroupName: string, ruleName: string, callback: ServiceCallback<models.IncidentListResult>): void; listByAlertRule(resourceGroupName: string, ruleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.IncidentListResult>): void; } /** * @class * LogProfiles * __NOTE__: An instance of this class is automatically created for an * instance of the InsightsManagementClient. */ export interface LogProfiles { /** * Deletes the log profile. * * @param {string} logProfileName The name of the log profile. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(logProfileName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the log profile. * * @param {string} logProfileName The name of the log profile. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(logProfileName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(logProfileName: string, callback: ServiceCallback<void>): void; deleteMethod(logProfileName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets the log profile. * * @param {string} logProfileName The name of the log profile. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LogProfileResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(logProfileName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LogProfileResource>>; /** * Gets the log profile. * * @param {string} logProfileName The name of the log profile. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LogProfileResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LogProfileResource} [result] - The deserialized result object if an error did not occur. * See {@link LogProfileResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(logProfileName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LogProfileResource>; get(logProfileName: string, callback: ServiceCallback<models.LogProfileResource>): void; get(logProfileName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LogProfileResource>): void; /** * Create or update a log profile in Azure Monitoring REST API. * * @param {string} logProfileName The name of the log profile. * * @param {object} parameters Parameters supplied to the operation. * * @param {string} [parameters.storageAccountId] the resource id of the storage * account to which you would like to send the Activity Log. * * @param {string} [parameters.serviceBusRuleId] The service bus rule ID of the * service bus namespace in which you would like to have Event Hubs created for * streaming the Activity Log. The rule ID is of the format: '{service bus * resource ID}/authorizationrules/{key name}'. * * @param {array} parameters.locations List of regions for which Activity Log * events should be stored or streamed. It is a comma separated list of valid * ARM locations including the 'global' location. * * @param {array} [parameters.categories] the categories of the logs. These * categories are created as is convenient to the user. Some values are: * 'Write', 'Delete', and/or 'Action.' * * @param {object} [parameters.retentionPolicy] the retention policy for the * events in the log. * * @param {boolean} parameters.retentionPolicy.enabled a value indicating * whether the retention policy is enabled. * * @param {number} parameters.retentionPolicy.days the number of days for the * retention in days. A value of 0 will retain the events indefinitely. * * @param {string} [parameters.name] Azure resource name * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LogProfileResource>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(logProfileName: string, parameters: models.LogProfileResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LogProfileResource>>; /** * Create or update a log profile in Azure Monitoring REST API. * * @param {string} logProfileName The name of the log profile. * * @param {object} parameters Parameters supplied to the operation. * * @param {string} [parameters.storageAccountId] the resource id of the storage * account to which you would like to send the Activity Log. * * @param {string} [parameters.serviceBusRuleId] The service bus rule ID of the * service bus namespace in which you would like to have Event Hubs created for * streaming the Activity Log. The rule ID is of the format: '{service bus * resource ID}/authorizationrules/{key name}'. * * @param {array} parameters.locations List of regions for which Activity Log * events should be stored or streamed. It is a comma separated list of valid * ARM locations including the 'global' location. * * @param {array} [parameters.categories] the categories of the logs. These * categories are created as is convenient to the user. Some values are: * 'Write', 'Delete', and/or 'Action.' * * @param {object} [parameters.retentionPolicy] the retention policy for the * events in the log. * * @param {boolean} parameters.retentionPolicy.enabled a value indicating * whether the retention policy is enabled. * * @param {number} parameters.retentionPolicy.days the number of days for the * retention in days. A value of 0 will retain the events indefinitely. * * @param {string} [parameters.name] Azure resource name * * @param {string} parameters.location Resource location * * @param {object} [parameters.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LogProfileResource} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LogProfileResource} [result] - The deserialized result object if an error did not occur. * See {@link LogProfileResource} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(logProfileName: string, parameters: models.LogProfileResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LogProfileResource>; createOrUpdate(logProfileName: string, parameters: models.LogProfileResource, callback: ServiceCallback<models.LogProfileResource>): void; createOrUpdate(logProfileName: string, parameters: models.LogProfileResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LogProfileResource>): void; /** * List the log profiles. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LogProfileCollection>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LogProfileCollection>>; /** * List the log profiles. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LogProfileCollection} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LogProfileCollection} [result] - The deserialized result object if an error did not occur. * See {@link LogProfileCollection} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LogProfileCollection>; list(callback: ServiceCallback<models.LogProfileCollection>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LogProfileCollection>): void; }
the_stack
import parseISO from 'date-fns/parseISO'; import loggerFactory from '~/utils/logger'; import ConfigModel from '../models/config'; import S2sMessage from '../models/vo/s2s-message'; import { S2sMessagingService } from './s2s-messaging/base'; import { S2sMessageHandlable } from './s2s-messaging/handlable'; import ConfigLoader, { ConfigObject } from './config-loader'; const logger = loggerFactory('growi:service:ConfigManager'); const KEYS_FOR_LOCAL_STRATEGY_USE_ONLY_ENV_OPTION = [ 'security:passport-local:isEnabled', ]; const KEYS_FOR_SAML_USE_ONLY_ENV_OPTION = [ 'security:passport-saml:isEnabled', 'security:passport-saml:entryPoint', 'security:passport-saml:issuer', 'security:passport-saml:cert', ]; const KEYS_FOR_FIEL_UPLOAD_USE_ONLY_ENV_OPTION = [ 'app:fileUploadType', ]; const KEYS_FOR_GCS_USE_ONLY_ENV_OPTION = [ 'gcs:apiKeyJsonPath', 'gcs:bucket', 'gcs:uploadNamespace', ]; export default class ConfigManager implements S2sMessageHandlable { private configLoader: ConfigLoader = new ConfigLoader(); private s2sMessagingService?: S2sMessagingService; private configObject: ConfigObject = { fromDB: null, fromEnvVars: null }; private configKeys: any[] = []; private lastLoadedAt?: Date; /** * load configs from the database and the environment variables */ async loadConfigs(): Promise<void> { this.configObject = await this.configLoader.load(); logger.debug('ConfigManager#loadConfigs', this.configObject); // cache all config keys this.reloadConfigKeys(); this.lastLoadedAt = new Date(); } /** * Set S2sMessagingServiceDelegator instance * @param s2sMessagingService */ setS2sMessagingService(s2sMessagingService: S2sMessagingService): void { this.s2sMessagingService = s2sMessagingService; } /** * get a config specified by namespace & key * * Basically, this searches a specified config from configs loaded from the database at first * and then from configs loaded from the environment variables. * * In some case, this search method changes. * * the followings are the meanings of each special return value. * - null: a specified config is not set. * - undefined: a specified config does not exist. */ getConfig(namespace, key) { let value; if (this.shouldSearchedFromEnvVarsOnly(namespace, key)) { value = this.searchOnlyFromEnvVarConfigs(namespace, key); } else { value = this.defaultSearch(namespace, key); } logger.debug(key, value); return value; } /** * get a config specified by namespace and regular expression */ getConfigByRegExp(namespace, regexp) { const result = {}; for (const key of this.configKeys) { if (regexp.test(key)) { result[key] = this.getConfig(namespace, key); } } return result; } /** * get a config specified by namespace and prefix */ getConfigByPrefix(namespace, prefix) { const regexp = new RegExp(`^${prefix}`); return this.getConfigByRegExp(namespace, regexp); } /** * generate an array of config keys from this.configObject */ getConfigKeys() { // type: fromDB, fromEnvVars const types = Object.keys(this.configObject); let namespaces: string[] = []; let keys: string[] = []; for (const type of types) { if (this.configObject[type] != null) { // ns: crowi, markdown, notification namespaces = [...namespaces, ...Object.keys(this.configObject[type])]; } } // remove duplicates namespaces = [...new Set(namespaces)]; for (const type of types) { for (const ns of namespaces) { if (this.configObject[type][ns] != null) { keys = [...keys, ...Object.keys(this.configObject[type][ns])]; } } } // remove duplicates keys = [...new Set(keys)]; return keys; } reloadConfigKeys() { this.configKeys = this.getConfigKeys(); } /** * get a config specified by namespace & key from configs loaded from the database * * **Do not use this unless absolutely necessary. Use getConfig instead.** */ getConfigFromDB(namespace, key) { return this.searchOnlyFromDBConfigs(namespace, key); } /** * get a config specified by namespace & key from configs loaded from the environment variables * * **Do not use this unless absolutely necessary. Use getConfig instead.** */ getConfigFromEnvVars(namespace, key) { return this.searchOnlyFromEnvVarConfigs(namespace, key); } /** * update configs in the same namespace * * Specified values are encoded by convertInsertValue. * In it, an empty string is converted to null that indicates a config is not set. * * For example: * ``` * updateConfigsInTheSameNamespace( * 'some namespace', * { * 'some key 1': 'value 1', * 'some key 2': 'value 2', * ... * } * ); * ``` */ async updateConfigsInTheSameNamespace(namespace, configs, withoutPublishingS2sMessage) { const queries: any[] = []; for (const key of Object.keys(configs)) { queries.push({ updateOne: { filter: { ns: namespace, key }, update: { ns: namespace, key, value: this.convertInsertValue(configs[key]) }, upsert: true, }, }); } await ConfigModel.bulkWrite(queries); await this.loadConfigs(); // publish updated date after reloading if (this.s2sMessagingService != null && !withoutPublishingS2sMessage) { this.publishUpdateMessage(); } } /** * return whether the specified namespace/key should be retrieved only from env vars */ shouldSearchedFromEnvVarsOnly(namespace, key) { return (namespace === 'crowi' && ( // local strategy ( KEYS_FOR_LOCAL_STRATEGY_USE_ONLY_ENV_OPTION.includes(key) && this.defaultSearch('crowi', 'security:passport-local:useOnlyEnvVarsForSomeOptions') ) // saml strategy || ( KEYS_FOR_SAML_USE_ONLY_ENV_OPTION.includes(key) && this.defaultSearch('crowi', 'security:passport-saml:useOnlyEnvVarsForSomeOptions') ) // file upload option || ( KEYS_FOR_FIEL_UPLOAD_USE_ONLY_ENV_OPTION.includes(key) && this.searchOnlyFromEnvVarConfigs('crowi', 'app:useOnlyEnvVarForFileUploadType') ) // gcs option || ( KEYS_FOR_GCS_USE_ONLY_ENV_OPTION.includes(key) && this.searchOnlyFromEnvVarConfigs('crowi', 'gcs:useOnlyEnvVarsForSomeOptions') ) )); } /* * All of the methods below are private APIs. */ /** * search a specified config from configs loaded from the database at first * and then from configs loaded from the environment variables */ defaultSearch(namespace, key) { // does not exist neither in db nor in env vars if (!this.configExistsInDB(namespace, key) && !this.configExistsInEnvVars(namespace, key)) { logger.debug(`${namespace}.${key} does not exist neither in db nor in env vars`); return undefined; } // only exists in db if (this.configExistsInDB(namespace, key) && !this.configExistsInEnvVars(namespace, key)) { logger.debug(`${namespace}.${key} only exists in db`); return this.configObject.fromDB[namespace][key]; } // only exists env vars if (!this.configExistsInDB(namespace, key) && this.configExistsInEnvVars(namespace, key)) { logger.debug(`${namespace}.${key} only exists in env vars`); return this.configObject.fromEnvVars[namespace][key]; } // exists both in db and in env vars [db > env var] if (this.configExistsInDB(namespace, key) && this.configExistsInEnvVars(namespace, key)) { if (this.configObject.fromDB[namespace][key] !== null) { logger.debug(`${namespace}.${key} exists both in db and in env vars. loaded from db`); return this.configObject.fromDB[namespace][key]; } /* eslint-disable-next-line no-else-return */ else { logger.debug(`${namespace}.${key} exists both in db and in env vars. loaded from env vars`); return this.configObject.fromEnvVars[namespace][key]; } } } /** * search a specified config from configs loaded from the database */ searchOnlyFromDBConfigs(namespace, key) { if (!this.configExistsInDB(namespace, key)) { return undefined; } return this.configObject.fromDB[namespace][key]; } /** * search a specified config from configs loaded from the environment variables */ searchOnlyFromEnvVarConfigs(namespace, key) { if (!this.configExistsInEnvVars(namespace, key)) { return undefined; } return this.configObject.fromEnvVars[namespace][key]; } /** * check whether a specified config exists in configs loaded from the database */ configExistsInDB(namespace, key) { if (this.configObject.fromDB[namespace] === undefined) { return false; } return this.configObject.fromDB[namespace][key] !== undefined; } /** * check whether a specified config exists in configs loaded from the environment variables */ configExistsInEnvVars(namespace, key) { if (this.configObject.fromEnvVars[namespace] === undefined) { return false; } return this.configObject.fromEnvVars[namespace][key] !== undefined; } convertInsertValue(value) { return JSON.stringify(value === '' ? null : value); } async publishUpdateMessage() { const s2sMessage = new S2sMessage('configUpdated', { updatedAt: new Date() }); try { await this.s2sMessagingService?.publish(s2sMessage); } catch (e) { logger.error('Failed to publish update message with S2sMessagingService: ', e.message); } } /** * @inheritdoc */ shouldHandleS2sMessage(s2sMessage) { const { eventName, updatedAt } = s2sMessage; if (eventName !== 'configUpdated' || updatedAt == null) { return false; } return this.lastLoadedAt == null || this.lastLoadedAt < parseISO(s2sMessage.updatedAt); } /** * @inheritdoc */ async handleS2sMessage(s2sMessage) { logger.info('Reload configs by pubsub notification'); return this.loadConfigs(); } }
the_stack
import { close, createReadStream, createWriteStream, fdatasync, mkdir, open, stat, unlink } from "fs"; import multistream = require("multistream"); import { join } from "path"; import { Writable } from "stream"; import { promisify } from "util"; import uuid = require("uuid"); import { ZERO_EXTENT_ID } from "../../blob/persistence/IBlobMetadataStore"; import ILogger from "../ILogger"; import BufferStream from "../utils/BufferStream"; import { DEFAULT_MAX_EXTENT_SIZE, DEFAULT_READ_CONCURRENCY } from "../utils/constants"; import { rimrafAsync } from "../utils/utils"; import ZeroBytesStream from "../ZeroBytesStream"; import IExtentMetadataStore, { IExtentModel } from "./IExtentMetadataStore"; import IExtentStore, { IExtentChunk, StoreDestinationArray } from "./IExtentStore"; import IOperationQueue from "./IOperationQueue"; import OperationQueue from "./OperationQueue"; const statAsync = promisify(stat); const mkdirAsync = promisify(mkdir); const unlinkAsync = promisify(unlink); // The max size of an extent. const MAX_EXTENT_SIZE = DEFAULT_MAX_EXTENT_SIZE; enum AppendStatusCode { Idle, Appending } interface IAppendExtent { id: string; offset: number; appendStatus: AppendStatusCode; // 0 for idle, 1 for appending locationId: string; fd?: number; } const openAsync = promisify(open); const closeAsync = promisify(close); /** * Persistency layer data store source implementation interacting with the storage media. * It provides the methods to read and write data with the storage. * * @export * @class FSExtentStore * @implements {IExtentStore} */ export default class FSExtentStore implements IExtentStore { private readonly metadataStore: IExtentMetadataStore; private readonly appendQueue: IOperationQueue; private readonly readQueue: IOperationQueue; private initialized: boolean = false; private closed: boolean = true; // The active extents to be appended data. private activeWriteExtents: IAppendExtent[]; private activeWriteExtentsNumber: number; private persistencyPath: Map<string, string>; public constructor( metadata: IExtentMetadataStore, private readonly persistencyConfiguration: StoreDestinationArray, private readonly logger: ILogger ) { this.activeWriteExtents = []; this.persistencyPath = new Map<string, string>(); for (const storeDestination of persistencyConfiguration) { this.persistencyPath.set( storeDestination.locationId, storeDestination.locationPath ); for (let i = 0; i < storeDestination.maxConcurrency; i++) { const appendExtent = this.createAppendExtent( storeDestination.locationId ); this.activeWriteExtents.push(appendExtent); } } this.activeWriteExtentsNumber = this.activeWriteExtents.length; this.metadataStore = metadata; this.appendQueue = new OperationQueue( this.activeWriteExtentsNumber, logger ); this.readQueue = new OperationQueue(DEFAULT_READ_CONCURRENCY, logger); } public isInitialized(): boolean { return this.initialized; } public isClosed(): boolean { return this.closed; } public async init(): Promise<void> { for (const storeDestination of this.persistencyConfiguration) { try { await statAsync(storeDestination.locationPath); } catch { await mkdirAsync(storeDestination.locationPath); } } if (!this.metadataStore.isInitialized()) { await this.metadataStore.init(); } this.initialized = true; this.closed = false; } public async close(): Promise<void> { if (!this.metadataStore.isClosed()) { await this.metadataStore.close(); } this.closed = true; } public async clean(): Promise<void> { if (this.isClosed()) { for (const path of this.persistencyConfiguration) { try { await rimrafAsync(path.locationPath); } catch { // TODO: Find out why sometimes it throws no permission error /* NOOP */ } } return; } throw new Error(`Cannot clean FSExtentStore, it's not closed.`); } /** * This method may create a new extent or append data to an existing extent. * Return the extent chunk information including the extentId, offset and count. * * @param {(NodeJS.ReadableStream | Buffer)} data * @param {string} [contextId] * @returns {Promise<IExtentChunk>} * @memberof FSExtentStore */ public async appendExtent( data: NodeJS.ReadableStream | Buffer, contextId?: string ): Promise<IExtentChunk> { const op = () => new Promise<IExtentChunk>((resolve, reject) => { (async (): Promise<IExtentChunk> => { let appendExtentIdx = 0; for (let i = 1; i < this.activeWriteExtentsNumber; i++) { if ( this.activeWriteExtents[i].appendStatus === AppendStatusCode.Idle ) { appendExtentIdx = i; break; } } this.activeWriteExtents[appendExtentIdx].appendStatus = AppendStatusCode.Appending; this.logger.info( `FSExtentStore:appendExtent() Select extent from idle location for extent append operation. LocationId:${appendExtentIdx} extentId:${this.activeWriteExtents[appendExtentIdx].id} offset:${this.activeWriteExtents[appendExtentIdx].offset} MAX_EXTENT_SIZE:${MAX_EXTENT_SIZE} `, contextId ); if ( this.activeWriteExtents[appendExtentIdx].offset >= MAX_EXTENT_SIZE ) { this.logger.info( `FSExtentStore:appendExtent() Size of selected extent offset is larger than maximum extent size ${MAX_EXTENT_SIZE} bytes, try appending to new extent.`, contextId ); const selectedFd = this.activeWriteExtents[appendExtentIdx].fd; if (selectedFd) { this.logger.info( `FSExtentStore:appendExtent() Close unused fd:${selectedFd}.`, contextId ); try { await closeAsync(selectedFd); } catch (err) { this.logger.error( `FSExtentStore:appendExtent() Close unused fd:${selectedFd} error:${JSON.stringify( err )}.`, contextId ); } } await this.getNewExtent(this.activeWriteExtents[appendExtentIdx]); this.logger.info( `FSExtentStore:appendExtent() Allocated new extent LocationID:${appendExtentIdx} extentId:${this.activeWriteExtents[appendExtentIdx].id} offset:${this.activeWriteExtents[appendExtentIdx].offset} MAX_EXTENT_SIZE:${MAX_EXTENT_SIZE} `, contextId ); } let rs: NodeJS.ReadableStream; if (data instanceof Buffer) { rs = new BufferStream(data); } else { rs = data; } const appendExtent = this.activeWriteExtents[appendExtentIdx]; const id = appendExtent.id; const path = this.generateExtentPath(appendExtent.locationId, id); let fd = appendExtent.fd; this.logger.debug( `FSExtentStore:appendExtent() Get fd:${fd} for extent:${id} from cache.`, contextId ); if (fd === undefined) { fd = await openAsync(path, "a"); appendExtent.fd = fd; this.logger.debug( `FSExtentStore:appendExtent() Open file:${path} for extent:${id}, get new fd:${fd}`, contextId ); } const ws = createWriteStream(path, { fd, autoClose: false }); this.logger.debug( `FSExtentStore:appendExtent() Created write stream for fd:${fd}`, contextId ); let count = 0; this.logger.debug( `FSExtentStore:appendExtent() Start writing to extent ${id}`, contextId ); try { count = await this.streamPipe(rs, ws, fd, contextId); const offset = appendExtent.offset; appendExtent.offset += count; const extent: IExtentModel = { id, locationId: appendExtent.locationId, path: id, size: count + offset, lastModifiedInMS: Date.now() }; this.logger.debug( `FSExtentStore:appendExtent() Write finish, start updating extent metadata. extent:${JSON.stringify( extent )}`, contextId ); await this.metadataStore.updateExtent(extent); this.logger.debug( `FSExtentStore:appendExtent() Update extent metadata done. Resolve()`, contextId ); appendExtent.appendStatus = AppendStatusCode.Idle; return { id, offset, count }; } catch (err) { appendExtent.appendStatus = AppendStatusCode.Idle; throw err; } })() .then(resolve) .catch(reject); }); return this.appendQueue.operate(op, contextId); } /** * Read data from persistency layer according to the given IExtentChunk. * * @param {IExtentChunk} [extentChunk] * @returns {Promise<NodeJS.ReadableStream>} * @memberof FSExtentStore */ public async readExtent( extentChunk?: IExtentChunk, contextId?: string ): Promise<NodeJS.ReadableStream> { if (extentChunk === undefined || extentChunk.count === 0) { return new ZeroBytesStream(0); } if (extentChunk.id === ZERO_EXTENT_ID) { const subRangeCount = Math.min(extentChunk.count); return new ZeroBytesStream(subRangeCount); } const persistencyId = await this.metadataStore.getExtentLocationId( extentChunk.id ); const path = this.generateExtentPath(persistencyId, extentChunk.id); const op = () => new Promise<NodeJS.ReadableStream>((resolve, reject) => { this.logger.verbose( `FSExtentStore:readExtent() Creating read stream. LocationId:${persistencyId} extentId:${ extentChunk.id } path:${path} offset:${extentChunk.offset} count:${ extentChunk.count } end:${extentChunk.offset + extentChunk.count - 1}`, contextId ); const stream = createReadStream(path, { start: extentChunk.offset, end: extentChunk.offset + extentChunk.count - 1 }).on("close", () => { this.logger.verbose( `FSExtentStore:readExtent() Read stream closed. LocationId:${persistencyId} extentId:${ extentChunk.id } path:${path} offset:${extentChunk.offset} count:${ extentChunk.count } end:${extentChunk.offset + extentChunk.count - 1}`, contextId ); }); resolve(stream); }); return this.readQueue.operate(op, contextId); } /** * Merge several extent chunks to a ReadableStream according to the offset and count. * * @param {(IExtentChunk)[]} extentChunkArray * @param {number} [offset=0] * @param {number} [count=Infinity] * @param {string} [contextId] * @returns {Promise<NodeJS.ReadableStream>} * @memberof FSExtentStore */ public async readExtents( extentChunkArray: (IExtentChunk)[], offset: number = 0, count: number = Infinity, contextId?: string ): Promise<NodeJS.ReadableStream> { this.logger.verbose( `FSExtentStore:readExtents() Start read from multi extents...`, contextId ); if (count === 0) { return new ZeroBytesStream(0); } const start = offset; // Start inclusive position in the merged stream const end = offset + count; // End exclusive position in the merged stream const streams: NodeJS.ReadableStream[] = []; let accumulatedOffset = 0; // Current payload offset in the merged stream for (const chunk of extentChunkArray) { const nextOffset = accumulatedOffset + chunk.count; if (nextOffset <= start) { accumulatedOffset = nextOffset; continue; } else if (end <= accumulatedOffset) { break; } else { let chunkStart = chunk.offset; let chunkEnd = chunk.offset + chunk.count; if (start > accumulatedOffset) { chunkStart = chunkStart + start - accumulatedOffset; // Inclusive } if (end <= nextOffset) { chunkEnd = chunkEnd - (nextOffset - end); // Exclusive } streams.push( await this.readExtent( { id: chunk.id, offset: chunkStart, count: chunkEnd - chunkStart }, contextId ) ); accumulatedOffset = nextOffset; } } // TODO: What happens when count exceeds merged payload length? // throw an error of just return as much data as we can? if (end !== Infinity && accumulatedOffset < end) { throw new RangeError( // tslint:disable-next-line:max-line-length `Not enough payload data error. Total length of payloads is ${accumulatedOffset}, while required data offset is ${offset}, count is ${count}.` ); } return multistream(streams); } /** * Delete the extents from persistency layer. * * @param {Iterable<string>} persistency * @returns {Promise<number>} Number of extents deleted * @memberof IExtentStore */ public async deleteExtents(extents: Iterable<string>): Promise<number> { let count = 0; for (const id of extents) { // Should not delete active write extents // Will not throw error because GC doesn't know extent is active, and will call this method to // delete active extents if (this.isActiveExtent(id)) { this.logger.debug( `FSExtentStore:deleteExtents() Skip deleting active extent:${id}` ); continue; } const locationId = await this.metadataStore.getExtentLocationId(id); const path = this.generateExtentPath(locationId, id); this.logger.debug( `FSExtentStore:deleteExtents() Delete extent:${id} location:${locationId} path:${path}` ); try { await unlinkAsync(path); await this.metadataStore.deleteExtent(id); } catch (err) { if (err.code === "ENOENT") { await this.metadataStore.deleteExtent(id); } } count++; } return count; } /** * Return its metadata store. * * @returns {IExtentMetadataStore} * @memberof IExtentStore */ public getMetadataStore(): IExtentMetadataStore { return this.metadataStore; } private async streamPipe( rs: NodeJS.ReadableStream, ws: Writable, fd?: number, contextId?: string ): Promise<number> { return new Promise<number>((resolve, reject) => { this.logger.debug( `FSExtentStore:streamPipe() Start piping data to write stream`, contextId ); let count: number = 0; let wsEnd = false; rs.on("data", data => { count += data.length; if (!ws.write(data)) { rs.pause(); } }) .on("end", () => { this.logger.debug( `FSExtentStore:streamPipe() Readable stream triggers close event, ${count} bytes piped`, contextId ); if (!wsEnd) { this.logger.debug( `FSExtentStore:streamPipe() Invoke write stream end()`, contextId ); ws.end(); wsEnd = true; } }) .on("close", () => { this.logger.debug( `FSExtentStore:streamPipe() Readable stream triggers close event, ${count} bytes piped`, contextId ); if (!wsEnd) { this.logger.debug( `FSExtentStore:streamPipe() Invoke write stream end()`, contextId ); ws.end(); wsEnd = true; } }) .on("error", err => { this.logger.debug( `FSExtentStore:streamPipe() Readable stream triggers error event, error:${JSON.stringify( err )}, after ${count} bytes piped. Invoke write stream destroy() method.`, contextId ); ws.destroy(err); }); ws.on("drain", () => { rs.resume(); }) .on("finish", () => { if (typeof fd === "number") { this.logger.debug( `FSExtentStore:streamPipe() Writable stream triggers finish event, after ${count} bytes piped. Flush data to fd:${fd}.`, contextId ); fdatasync(fd, err => { if (err) { this.logger.debug( `FSExtentStore:streamPipe() Flush data to fd:${fd} failed with error:${JSON.stringify( err )}. Reject streamPipe().`, contextId ); reject(err); } else { this.logger.debug( `FSExtentStore:streamPipe() Flush data to fd:${fd} successfully. Resolve streamPipe().`, contextId ); resolve(count); } }); } else { this.logger.debug( `FSExtentStore:streamPipe() Resolve streamPipe() without flushing data.`, contextId ); resolve(count); } }) .on("error", err => { this.logger.debug( `FSExtentStore:streamPipe() Writable stream triggers error event, error:${JSON.stringify( err )}, after ${count} bytes piped. Reject streamPipe().`, contextId ); reject(err); }); }); } /** * Check an extent is one of active extents or not. * * @private * @param {string} id * @returns {boolean} * @memberof FSExtentStore */ private isActiveExtent(id: string): boolean { // TODO: Use map instead of array to quick check for (const extent of this.activeWriteExtents) { if (extent.id === id) { return true; } } return false; } /** * Create a new append extent model for a new write directory. * * @private * @param {string} persistencyPath * @returns {IAppendExtent} * @memberof FSExtentStore */ private createAppendExtent(persistencyId: string): IAppendExtent { return { id: uuid(), offset: 0, appendStatus: AppendStatusCode.Idle, locationId: persistencyId }; } /** * Select a new extent to append for an exist write directory. * * @private * @param {IAppendExtent} appendExtent * @memberof FSExtentStore */ private getNewExtent(appendExtent: IAppendExtent) { appendExtent.id = uuid(); appendExtent.offset = 0; appendExtent.fd = undefined; } /** * Generate the file path for a new extent. * * @private * @param {string} extentId * @returns {string} * @memberof FSExtentStore */ private generateExtentPath(persistencyId: string, extentId: string): string { const directoryPath = this.persistencyPath.get(persistencyId); if (!directoryPath) { // To be completed } return join(directoryPath!, extentId); } }
the_stack
import { loggerSpy } from '../testhelpers/loggerSpy'; import { importSingleText } from '../testhelpers/importSingleText'; import { leftAlign } from '../utils/leftAlign'; describe('FSHErrorListener', () => { beforeEach(() => loggerSpy.reset()); it('should not log any errors for valid FSH', () => { const input = leftAlign(` Profile: MyPatient Parent: Patient * active = true `); importSingleText(input, 'MyPatient.fsh'); expect(loggerSpy.getAllMessages('error')).toBeEmpty(); }); it('should report mismatched input errors from antlr', () => { const input = leftAlign(` Profile: MismatchedPizza Pizza: Large `); importSingleText(input, 'Pizza.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Pizza\.fsh.*Line: 3\D*/s); }); it('should report extraneous input errors from antlr', () => { const input = leftAlign(` Profile: Something Spaced Parent: Spacious `); importSingleText(input, 'Space.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Space\.fsh.*Line: 2\D*/s); }); // ######################################################################## // # Missing space around = # // ######################################################################## it('should make sense of errors due to no space before = in an Alias definition', () => { const input = leftAlign(` Alias: $OrgType= http://terminology.hl7.org/CodeSystem/organization-type `); importSingleText(input, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Alias declarations must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 2\D*/s ); }); it('should make sense of errors due to no space after = in an Alias definition', () => { const input = leftAlign(` Alias: $OrgType =http://terminology.hl7.org/CodeSystem/organization-type `); importSingleText(input, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Alias declarations must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 2\D*/s ); }); it('should make sense of errors due to no space around = in an Alias definition', () => { const input = leftAlign(` Alias: $OrgType=http://terminology.hl7.org/CodeSystem/organization-type `); importSingleText(input, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Alias declarations must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 2\D*/s ); }); it('should make sense of errors due to no space before = in an assignment rule', () => { const input = leftAlign(` Profile: SampleObservation Parent: Observation * component= FOO#bar `); importSingleText(input, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Assignment rules must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 4\D*/s ); // Test with a multi-word string as well since sometimes that results in a different error loggerSpy.reset(); const input2 = leftAlign(` Profile: SampleObservation Parent: Observation * valueString= "My Value" `); importSingleText(input2, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Assignment rules must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 4\D*/s ); }); it('should make sense of errors due to no space after = in an assignment rule', () => { const input = leftAlign(` Profile: SampleObservation Parent: Observation * component =FOO#bar `); importSingleText(input, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Assignment rules must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 4\D*/s ); // Test with a multi-word string as well since sometimes that results in a different error loggerSpy.reset(); const input2 = leftAlign(` Profile: SampleObservation Parent: Observation * valueString ="My Value" `); importSingleText(input2, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Assignment rules must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 4\D*/s ); }); it('should make sense of errors due to no space around = in an assignment rule', () => { const input = leftAlign(` Profile: SampleObservation Parent: Observation * component=FOO#bar `); importSingleText(input, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Assignment rules must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 4\D*/s ); // Test with a multi-word string as well since sometimes that results in a different error loggerSpy.reset(); const input2 = leftAlign(` Profile: SampleObservation Parent: Observation * valueString="My Value" `); importSingleText(input2, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Assignment rules must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 4\D*/s ); }); it('should make sense of errors due to no space before = in a caret rule', () => { const input = leftAlign(` Profile: SampleObservation Parent: Observation * component ^short= "Component1" `); importSingleText(input, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Assignment rules must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 4\D*/s ); // Test with a multi-word string as well since sometimes that results in a different error loggerSpy.reset(); const input2 = leftAlign(` Profile: SampleObservation Parent: Observation * component ^short= "A component" `); importSingleText(input2, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Assignment rules must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 4\D*/s ); }); it('should make sense of errors due to no space after = in a caret rule', () => { const input = leftAlign(` Profile: SampleObservation Parent: Observation * component ^short ="Component1" `); importSingleText(input, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Assignment rules must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 4\D*/s ); // Test with a multi-word string as well since sometimes that results in a different error loggerSpy.reset(); const input2 = leftAlign(` Profile: SampleObservation Parent: Observation * component ^short ="A component" `); importSingleText(input2, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Assignment rules must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 4\D*/s ); }); it('should make sense of errors due to no space around = in a caret rule', () => { const input = leftAlign(` Profile: SampleObservation Parent: Observation * component ^short="Component1" `); importSingleText(input, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Assignment rules must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 4\D*/s ); // Test with a multi-word string as well since sometimes that results in a different error loggerSpy.reset(); const input2 = leftAlign(` Profile: SampleObservation Parent: Observation * component ^short="A component" `); importSingleText(input2, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Assignment rules must include at least one space both before and after the '=' sign.*File: Invalid\.fsh.*Line: 4\D*/s ); }); // ######################################################################## // # Missing spaces around -> # // ######################################################################## it('should make sense of errors due to no space after -> in a mapping rule', () => { const input = leftAlign(` Mapping: USCorePatientToArgonaut Source: USCorePatient Target: "http://unknown.org/Argonaut-DQ-DSTU2" Title: "Argonaut DSTU2" Id: argonaut-dq-dstu2 * identifier ->"Patient.identifier" `); importSingleText(input, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Mapping rules must include at least one space both before and after the '->' operator.*File: Invalid\.fsh.*Line: 7\D*/s ); // Test with a multi-word string as well since sometimes that results in a different error loggerSpy.reset(); const input2 = leftAlign(` Mapping: USCorePatientToArgonaut Source: USCorePatient Target: "http://unknown.org/Argonaut-DQ-DSTU2" Title: "Argonaut DSTU2" Id: argonaut-dq-dstu2 * identifier ->"Patient identifier" `); importSingleText(input2, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Mapping rules must include at least one space both before and after the '->' operator.*File: Invalid\.fsh.*Line: 7\D*/s ); }); it('should make sense of errors due to no space before -> in a mapping rule', () => { const input = leftAlign(` Mapping: USCorePatientToArgonaut Source: USCorePatient Target: "http://unknown.org/Argonaut-DQ-DSTU2" Title: "Argonaut DSTU2" Id: argonaut-dq-dstu2 * identifier-> "Patient.identifier" `); importSingleText(input, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Mapping rules must include at least one space both before and after the '->' operator.*File: Invalid\.fsh.*Line: 7\D*/s ); // Test with a multi-word string as well since sometimes that results in a different error loggerSpy.reset(); const input2 = leftAlign(` Mapping: USCorePatientToArgonaut Source: USCorePatient Target: "http://unknown.org/Argonaut-DQ-DSTU2" Title: "Argonaut DSTU2" Id: argonaut-dq-dstu2 * identifier-> "Patient identifier" `); importSingleText(input2, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Mapping rules must include at least one space both before and after the '->' operator.*File: Invalid\.fsh.*Line: 7\D*/s ); }); it('should make sense of errors due to no space around -> in a mapping rule', () => { const input = leftAlign(` Mapping: USCorePatientToArgonaut Source: USCorePatient Target: "http://unknown.org/Argonaut-DQ-DSTU2" Title: "Argonaut DSTU2" Id: argonaut-dq-dstu2 * identifier->"Patient.identifier" `); importSingleText(input, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Mapping rules must include at least one space both before and after the '->' operator.*File: Invalid\.fsh.*Line: 7\D*/s ); // Test with a multi-word string as well since sometimes that results in a different error loggerSpy.reset(); const input2 = leftAlign(` Mapping: USCorePatientToArgonaut Source: USCorePatient Target: "http://unknown.org/Argonaut-DQ-DSTU2" Title: "Argonaut DSTU2" Id: argonaut-dq-dstu2 * identifier->"Patient identifier" `); importSingleText(input2, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Mapping rules must include at least one space both before and after the '->' operator.*File: Invalid\.fsh.*Line: 7\D*/s ); }); // ######################################################################## // # Missing space after * # // ######################################################################## it('should make sense of errors due to no space after * in a rule', () => { const input = leftAlign(` Profile: SampleObservation Parent: Observation *component = FOO#bar `); importSingleText(input, 'Invalid.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch( /Rules must start with a '\*' symbol followed by at least one space.*File: Invalid\.fsh.*Line: 4\D*/s ); }); });
the_stack
import { RequestService } from '@salesforce/salesforcedx-utils-vscode/out/src/requestService'; import { expect } from 'chai'; import * as sinon from 'sinon'; import { DebugProtocol } from 'vscode-debugprotocol/lib/debugProtocol'; import { ApexDebug, ApexDebugStackFrameInfo, ApexVariable, ApexVariableKind, CollectionReferenceContainer, MapReferenceContainer, MapTupleContainer, ObjectReferenceContainer, ScopeContainer, VariableContainer } from '../../../src/adapter/apexDebug'; import { LocalValue, Reference, Value } from '../../../src/commands'; import { BreakpointService } from '../../../src/core/breakpointService'; import { ApexDebugForTest } from './apexDebugForTest'; describe('Debugger adapter variable handling - unit', () => { describe('ApexVariable', () => { let value: Value; let variable: ApexVariable; beforeEach(() => { value = { name: 'variableName', nameForMessages: 'String', declaredTypeRef: 'java/lang/String', value: 'a string' }; variable = new ApexVariable(value, ApexVariableKind.Local, 20); }); it('Should use proper values from Value', async () => { expect(variable.name).to.equal(value.name); expect(variable.type).to.equal(value.nameForMessages); expect(variable.declaredTypeRef).to.equal(value.declaredTypeRef); expect(variable.value).to.equal(ApexVariable.valueAsString(value)); expect(variable.evaluateName).to.equal(ApexVariable.valueAsString(value)); expect(variable.variablesReference).to.equal(20); expect(variable['kind']).to.equal(ApexVariableKind.Local); }); it('Should set slot to MAX integer for non local value', async () => { expect(variable['slot']).to.equal(Number.MAX_SAFE_INTEGER); }); it('Should set slot to specific value for LocalValue', async () => { const localvalue: LocalValue = { name: 'name', nameForMessages: 'nameForMessages', declaredTypeRef: 'declaredTypeRef', value: 'value', slot: 15 }; variable = new ApexVariable(localvalue, ApexVariableKind.Local, 20); expect(variable['slot']).to.equal(localvalue.slot); }); it('Should correctly print null string as "null"', async () => { value.value = undefined; value.declaredTypeRef = 'java/lang/String'; variable = new ApexVariable(value, ApexVariableKind.Local, 20); expect(variable.value).to.equal('null'); expect(variable.evaluateName).to.equal('null'); }); it('Should correctly print empty string', async () => { value.value = ''; value.declaredTypeRef = 'java/lang/String'; variable = new ApexVariable(value, ApexVariableKind.Local, 20); expect(variable.value).to.equal("''"); expect(variable.evaluateName).to.equal("''"); }); it('Should correctly print string', async () => { value.value = '123'; value.declaredTypeRef = 'java/lang/String'; variable = new ApexVariable(value, ApexVariableKind.Local, 20); expect(variable.value).to.equal("'123'"); expect(variable.evaluateName).to.equal("'123'"); }); it('Should correctly print value', async () => { value.value = '123'; value.nameForMessages = 'a-type'; value.declaredTypeRef = 'a/specific/type'; variable = new ApexVariable(value, ApexVariableKind.Local, 20); expect(variable.value).to.equal('123'); expect(variable.evaluateName).to.equal('123'); }); it('Should correctly print null', async () => { value.value = undefined; value.nameForMessages = 'a-type'; value.declaredTypeRef = 'a/specific/type'; variable = new ApexVariable(value, ApexVariableKind.Local, 20); expect(variable.value).to.equal('null'); expect(variable.evaluateName).to.equal('null'); }); it('Should compare Value of different kinds', async () => { // given const v1 = new ApexVariable(value, ApexVariableKind.Local); const v2 = new ApexVariable(value, ApexVariableKind.Static); // when const result = ApexVariable.compareVariables(v1, v2); // expect expect(result).to.not.equal(0); expect(result).to.equal(ApexVariableKind.Local - ApexVariableKind.Static); }); it('Should compare Value of same kinds', async () => { // given const v1 = new ApexVariable(value, ApexVariableKind.Local); const v2 = new ApexVariable(value, ApexVariableKind.Local); // when const result = ApexVariable.compareVariables(v1, v2); // expect expect(result).to.equal(0); }); it('Should compare based on slot for Local', async () => { // given const v1 = new ApexVariable( newStringValue('a_name', 'value', 10), ApexVariableKind.Local ); const v2 = new ApexVariable( newStringValue('z_name', 'value', 9), ApexVariableKind.Local ); // when const result1 = ApexVariable.compareVariables(v1, v2); const result2 = ApexVariable.compareVariables(v2, v1); // expect expect(result1).to.be.greaterThan(0); // slot 10 is greater than 9 expect(result2).to.be.lessThan(0); // slot 9 is less than 10 }); it('Should compare based on slot for Field', async () => { // given const v1 = new ApexVariable( newStringValue('a_name', 'value', 10), ApexVariableKind.Field ); const v2 = new ApexVariable( newStringValue('z_name', 'value', 9), ApexVariableKind.Field ); // when const result1 = ApexVariable.compareVariables(v1, v2); const result2 = ApexVariable.compareVariables(v2, v1); // expect expect(result1).to.be.greaterThan(0); // slot 10 is greater than 9 expect(result2).to.be.lessThan(0); // slot 9 is less than 10 }); it('Should compare based on name for others', async () => { // given const v1 = new ApexVariable( newStringValue('a_name', 'value'), ApexVariableKind.Static ); const v2 = new ApexVariable( newStringValue('z_name', 'value'), ApexVariableKind.Static ); // when const result1 = ApexVariable.compareVariables(v1, v2); const result2 = ApexVariable.compareVariables(v2, v1); // expect expect(result1).to.be.lessThan(0); // 'a...' before 'z...' expect(result2).to.be.greaterThan(0); // 'z...' after 'a...' }); it('Should compare based on numbered name (eg. array index)', async () => { // given const v1 = new ApexVariable( newStringValue('[124]', 'value'), ApexVariableKind.Static ); const v2 = new ApexVariable( newStringValue('123', 'value'), ApexVariableKind.Static ); // when const result1 = ApexVariable.compareVariables(v1, v2); const result2 = ApexVariable.compareVariables(v2, v1); // expect expect(result1).to.be.greaterThan(0); // '[124]' after '123' (if [124] properly treated as number, see following test) expect(result2).to.be.lessThan(0); // '123' before '124' }); it('Should compare numbered name with string', async () => { // given const v1 = new ApexVariable( newStringValue('12', 'value'), ApexVariableKind.Static ); const v2 = new ApexVariable( newStringValue('a_name', 'value'), ApexVariableKind.Static ); // when const result1 = ApexVariable.compareVariables(v1, v2); const result2 = ApexVariable.compareVariables(v2, v1); // expect expect(result1).to.be.greaterThan(0, 'numbers after names'); expect(result2).to.be.lessThan(0), 'names before numbers'; }); }); describe('populateReferences', () => { let adapter: ApexDebugForTest; it('Should expand object correctly', async () => { adapter = new ApexDebugForTest(new RequestService()); const references: Reference[] = [ { type: 'object', nameForMessages: 'Object', typeRef: 'Type', id: 0, fields: [ { name: 'var', nameForMessages: 'varNameForMessages', value: 'varValue', declaredTypeRef: 'varDeclaredTypeRef', index: 0 } ] } ]; adapter.populateReferences(references, 'FakeRequestId'); const variableRef = await adapter.resolveApexIdToVariableReference( 'FakeRequestId', 0 ); expect(variableRef).to.be.at.least(0); const container = adapter.getVariableContainer(variableRef as number); expect(container).to.be.ok; expect(container).to.be.instanceOf(ObjectReferenceContainer); expect(adapter.getVariableContainerReferenceByApexId().size).to.equal(1); }); it('Should expand list correctly', async () => { adapter = new ApexDebugForTest(new RequestService()); const references: Reference[] = [ { type: 'list', nameForMessages: 'List<List<String>>', typeRef: 'List<List<String>>', id: 0, size: 1, value: [ { name: '0', nameForMessages: 'List<String>', value: '(a, b)', declaredTypeRef: 'List<String>', ref: 1 } ] }, { type: 'list', nameForMessages: '<List<String>', typeRef: 'List<List<String>>', id: 1, size: 2, value: [ { name: '0', nameForMessages: 'String', value: 'a', declaredTypeRef: 'String' }, { name: '1', nameForMessages: 'String', value: 'b', declaredTypeRef: 'String' } ] } ]; adapter.populateReferences(references, 'FakeRequestId'); const variableRef = await adapter.resolveApexIdToVariableReference( 'FakeRequestId', 0 ); expect(variableRef).to.be.at.least(0); const container = adapter.getVariableContainer(variableRef as number); expect(container).to.be.ok; expect(container).to.be.instanceOf(CollectionReferenceContainer); expect(container!.getNumberOfChildren()).to.equal(1); expect(adapter.getNumberOfChildren(variableRef)).to.equal(1); const expandedVariables = await container!.expand(adapter, 'all'); expect(expandedVariables.length).to.equal(1); expect(expandedVariables[0].indexedVariables).to.equal(2); }); it('Should expand set correctly', async () => { adapter = new ApexDebugForTest(new RequestService()); const references: Reference[] = [ { type: 'set', nameForMessages: 'Set', typeRef: 'Type', id: 0, size: 1, fields: [ { name: 'var', nameForMessages: 'varNameForMessages', value: 'varValue', declaredTypeRef: 'varDeclaredTypeRef', index: 0 } ] } ]; adapter.populateReferences(references, 'FakeRequestId'); const variableRef = await adapter.resolveApexIdToVariableReference( 'FakeRequestId', 0 ); expect(variableRef).to.be.at.least(0); const container = adapter.getVariableContainer(variableRef as number); expect(container).to.be.ok; expect(container).to.be.instanceOf(CollectionReferenceContainer); expect(container!.getNumberOfChildren()).to.equal(1); expect(adapter.getNumberOfChildren(variableRef)).to.equal(1); }); it('Should expand map correctly', async () => { adapter = new ApexDebugForTest(new RequestService()); const tupleA = { key: { name: 'key', declaredTypeRef: 'Integer', nameForMessages: '0' }, value: { name: 'value', declaredTypeRef: 'String', nameForMessages: 'foo' } }; const expectedTupleContainer = new MapTupleContainer( tupleA, 'FakeRequestId' ); const references: Reference[] = [ { type: 'map', nameForMessages: 'Map', typeRef: 'Type', id: 0, size: 1, fields: [ { name: 'var', nameForMessages: 'varNameForMessages', value: 'varValue', declaredTypeRef: 'varDeclaredTypeRef', index: 0 } ], tuple: [tupleA] } ]; adapter.populateReferences(references, 'FakeRequestId'); const variableRef = await adapter.resolveApexIdToVariableReference( 'FakeRequestId', 0 ); expect(variableRef).to.be.at.least(0); const container = adapter.getVariableContainer(variableRef as number); expect(container).to.be.ok; expect(container).to.be.instanceOf(MapReferenceContainer); const mapContainer = container as MapReferenceContainer; expect(mapContainer.getNumberOfChildren()).to.equal(1); expect(mapContainer.tupleContainers.size).to.equal(1); expect(mapContainer.tupleContainers.get(1000)).to.deep.equal( expectedTupleContainer ); expect(mapContainer.tupleContainers.get(1000)!.getNumberOfChildren()).to .be.undefined; }); it('Should not expand unknown reference type', async () => { adapter = new ApexDebugForTest(new RequestService()); const references: Reference[] = [ { type: 'foo', nameForMessages: 'foo', typeRef: 'Type', id: 0, fields: [ { name: 'var', nameForMessages: 'varNameForMessages', value: 'varValue', declaredTypeRef: 'varDeclaredTypeRef', index: 0 } ] } ]; adapter.populateReferences(references, 'FakeRequestId'); expect(adapter.getVariableContainerReferenceByApexId().size).to.equal(0); }); }); describe('resolveApexIdToVariableReference', () => { let adapter: ApexDebugForTest; let referencesSpy: sinon.SinonStub; beforeEach(() => { adapter = new ApexDebugForTest(new RequestService()); }); afterEach(() => { if (referencesSpy) { referencesSpy.restore(); } }); it('Should handle undefined input', async () => { // given const apexId = undefined; // when const variableRef = await adapter.resolveApexIdToVariableReference( 'FakeRequestId', apexId ); // then expect(variableRef).to.be.undefined; }); it('Should call fetchReferences for unknown input', async () => { // given const apexId = 12345; const references: Reference[] = [ { type: 'object', nameForMessages: 'Object', typeRef: 'Type', id: apexId, fields: [ { name: 'var', nameForMessages: 'varNameForMessages', value: 'varValue', declaredTypeRef: 'varDeclaredTypeRef', index: 0 } ] } ]; referencesSpy = sinon.stub(RequestService.prototype, 'execute').returns( Promise.resolve( JSON.stringify({ referencesResponse: { references: { references } } }) ) ); // when const variableRef = await adapter.resolveApexIdToVariableReference( 'FakeRequestId', apexId ); // then expect(referencesSpy.callCount).to.equal(1); expect(variableRef).to.be.ok; const container = adapter.getVariableContainer(variableRef as number); expect(container).to.be.ok; }); }); describe('ApexDebugStackFrameInfo', () => { let stateSpy: sinon.SinonStub; let sourcePathSpy: sinon.SinonStub; let adapter: ApexDebugForTest; beforeEach(() => { adapter = new ApexDebugForTest(new RequestService()); adapter.setSfdxProject('someProjectPath'); adapter.addRequestThread('07cFAKE'); }); afterEach(() => { stateSpy.restore(); if (sourcePathSpy) { sourcePathSpy.restore(); } }); it('Should create as part of stackTraceRequest with variables info', async () => { // given const stateResponse: any = { stateResponse: { state: { stack: { stackFrame: [ { typeRef: 'FooDebug', fullName: 'FooDebug.test()', lineNumber: 1, frameNumber: 0 }, { typeRef: 'BarDebug', fullName: 'BarDebug.test()', lineNumber: 2, frameNumber: 1 } ] }, locals: { local: [newStringValue('localvar1', 'value', 0)] }, statics: { static: [newStringValue('staticvar1')] }, globals: { global: [newStringValue('globalvar')] } } } }; stateSpy = sinon .stub(RequestService.prototype, 'execute') .returns(Promise.resolve(JSON.stringify(stateResponse))); sourcePathSpy = sinon .stub(BreakpointService.prototype, 'getSourcePathFromTyperef') .returns('file:///foo.cls'); // when await adapter.stackTraceRequest( {} as DebugProtocol.StackTraceResponse, { threadId: 1 } as DebugProtocol.StackTraceArguments ); // then expect(stateSpy.called).to.equal(true); const response = adapter.getResponse( 0 ) as DebugProtocol.StackTraceResponse; expect(response.success).to.equal(true); const stackFrames = response.body.stackFrames; expect(stackFrames.length).to.equal(2); expect(stackFrames[0].id).to.be.ok; // should have frame id const frameInfo = adapter.getStackFrameInfo(stackFrames[0].id); expect(frameInfo).to.be.ok; // should have frame info for frame id expect(frameInfo.locals).to.be.ok; expect(frameInfo.locals).to.deep.equal( stateResponse.stateResponse.state.locals.local ); expect(frameInfo.statics).to.be.ok; expect(frameInfo.statics).to.deep.equal( stateResponse.stateResponse.state.statics.static ); expect(frameInfo.globals).to.be.ok; expect(frameInfo.globals).to.deep.equal( stateResponse.stateResponse.state.globals.global ); }); it('Should create as part of stackTraceRequest without variables info', async () => { // given const stateResponse: any = { stateResponse: { state: { stack: { stackFrame: [ { typeRef: 'FooDebug', fullName: 'FooDebug.test()', lineNumber: 1, frameNumber: 0 }, { typeRef: 'BarDebug', fullName: 'BarDebug.test()', lineNumber: 2, frameNumber: 1 } ] } } } }; stateSpy = sinon .stub(RequestService.prototype, 'execute') .returns(Promise.resolve(JSON.stringify(stateResponse))); sourcePathSpy = sinon .stub(BreakpointService.prototype, 'getSourcePathFromTyperef') .returns('file:///foo.cls'); // when await adapter.stackTraceRequest( {} as DebugProtocol.StackTraceResponse, { threadId: 1 } as DebugProtocol.StackTraceArguments ); // then expect(stateSpy.called).to.equal(true); const response = adapter.getResponse( 0 ) as DebugProtocol.StackTraceResponse; expect(response.success).to.equal(true); const stackFrames = response.body.stackFrames; expect(stackFrames.length).to.equal(2); expect(stackFrames[0].id).to.be.ok; // should have frame id const frameInfo = adapter.getStackFrameInfo(stackFrames[0].id); expect(frameInfo).to.be.ok; // should have frame info for frame id expect(frameInfo.locals).to.be.ok; expect(frameInfo.statics).to.be.ok; expect(frameInfo.globals).to.be.ok; }); it('Should propulates as part of fetchFrameVariables', async () => { // given const frameInfo = new ApexDebugStackFrameInfo('07cFAKE', 1000); const frameRespObj: any = { frameResponse: { frame: { locals: { local: [newStringValue('localvar1', 'value', 0)] }, statics: { static: [newStringValue('staticvar1')] }, globals: { global: [newStringValue('globalvar')] } } } }; stateSpy = sinon .stub(RequestService.prototype, 'execute') .returns(Promise.resolve(JSON.stringify(frameRespObj))); // when await adapter.fetchFrameVariables(frameInfo); // then expect(stateSpy.called).to.equal(true); expect(frameInfo).to.be.ok; // should have frame info for frame id expect(frameInfo.locals).to.be.ok; expect(frameInfo.locals).to.deep.equal( frameRespObj.frameResponse.frame.locals.local ); expect(frameInfo.statics).to.be.ok; expect(frameInfo.statics).to.deep.equal( frameRespObj.frameResponse.frame.statics.static ); expect(frameInfo.globals).to.be.ok; expect(frameInfo.globals).to.deep.equal( frameRespObj.frameResponse.frame.globals.global ); }); }); describe('scopesRequest', () => { let adapter: ApexDebugForTest; let resolveApexIdToVariableReferenceSpy: sinon.SinonStub; beforeEach(() => { adapter = new ApexDebugForTest(new RequestService()); adapter.setSfdxProject('someProjectPath'); adapter.addRequestThread('07cFAKE'); }); afterEach(() => { if (resolveApexIdToVariableReferenceSpy) { resolveApexIdToVariableReferenceSpy.restore(); } }); it('Should return no scopes for unknown frameId', async () => { // given const args: DebugProtocol.ScopesArguments = { frameId: 1234567 }; // when await adapter.scopesRequest({} as DebugProtocol.ScopesResponse, args); // then const response = adapter.getResponse(0) as DebugProtocol.ScopesResponse; expect(response.success).to.equal(true); expect(response.body).to.be.ok; expect(response.body.scopes).to.be.ok; expect(response.body.scopes.length).to.equal(0); }); it('Should return three scopes for known frameId', async () => { // given const frameInfo = new ApexDebugStackFrameInfo('07cFAKE', 0); frameInfo.locals = []; frameInfo.statics = []; frameInfo.globals = []; const frameId = adapter.createStackFrameInfo(frameInfo); // when await adapter.scopesRequest( {} as DebugProtocol.ScopesResponse, { frameId } as DebugProtocol.ScopesArguments ); // then const response = adapter.getResponse(0) as DebugProtocol.ScopesResponse; expect(response.success).to.equal(true); expect(response.body).to.be.ok; expect(response.body.scopes).to.be.ok; expect(response.body.scopes.length).to.equal(3); expect(response.body.scopes[0]).to.deep.equal({ name: 'Local', variablesReference: 1000, expensive: false }); expect(response.body.scopes[1]).to.deep.equal({ name: 'Static', variablesReference: 1001, expensive: false }); expect(response.body.scopes[2]).to.deep.equal({ name: 'Global', variablesReference: 1002, expensive: false }); }); it('Should expand local scope', async () => { const variableValue: LocalValue = { slot: 0, name: 'foo', declaredTypeRef: 'String', nameForMessages: 'String' }; const frameInfo = new ApexDebugStackFrameInfo('07cFAKE', 0); frameInfo.locals = []; frameInfo.statics = []; frameInfo.globals = []; frameInfo.locals[0] = variableValue; resolveApexIdToVariableReferenceSpy = sinon .stub(ApexDebugForTest.prototype, 'resolveApexIdToVariableReference') .returns(1001); const expectedVariableObj = new ApexVariable( variableValue, ApexVariableKind.Local, 1001 ); const localScope = new ScopeContainer('local', frameInfo); const vars = await localScope.expand(adapter, 'all', 0, 0); expect(vars.length).to.equal(1); expect( ApexVariable.compareVariables(expectedVariableObj, vars[0]) ).to.equal(0); }); it('Should expand static scope', async () => { const variableValue: Value = { name: 'foo', declaredTypeRef: 'String', nameForMessages: 'String' }; const frameInfo = new ApexDebugStackFrameInfo('07cFAKE', 0); frameInfo.locals = []; frameInfo.statics = []; frameInfo.globals = []; frameInfo.statics[0] = variableValue; resolveApexIdToVariableReferenceSpy = sinon .stub(ApexDebugForTest.prototype, 'resolveApexIdToVariableReference') .returns(1001); const expectedVariableObj = new ApexVariable( variableValue, ApexVariableKind.Static, 1001 ); const localScope = new ScopeContainer('static', frameInfo); const vars = await localScope.expand(adapter, 'all', 0, 0); expect(vars.length).to.equal(1); expect( ApexVariable.compareVariables(expectedVariableObj, vars[0]) ).to.equal(0); }); it('Should expand global scope', async () => { const variableValue: Value = { name: 'foo', declaredTypeRef: 'String', nameForMessages: 'String' }; const frameInfo = new ApexDebugStackFrameInfo('07cFAKE', 0); frameInfo.locals = []; frameInfo.statics = []; frameInfo.globals = []; frameInfo.globals[0] = variableValue; resolveApexIdToVariableReferenceSpy = sinon .stub(ApexDebugForTest.prototype, 'resolveApexIdToVariableReference') .returns(1001); const expectedVariableObj = new ApexVariable( variableValue, ApexVariableKind.Global, 1001 ); const localScope = new ScopeContainer('global', frameInfo); const vars = await localScope.expand(adapter, 'all', 0, 0); expect(vars.length).to.equal(1); expect( ApexVariable.compareVariables(expectedVariableObj, vars[0]) ).to.equal(0); }); }); describe('variablesRequest', () => { let adapter: ApexDebugForTest; let resetIdleTimersSpy: sinon.SinonSpy; beforeEach(() => { adapter = new ApexDebugForTest(new RequestService()); adapter.setSfdxProject('someProjectPath'); adapter.addRequestThread('07cFAKE'); resetIdleTimersSpy = sinon.spy( ApexDebugForTest.prototype, 'resetIdleTimer' ); }); afterEach(() => { resetIdleTimersSpy.restore(); }); it('Should return no variables for unknown variablesReference', async () => { // given const args: DebugProtocol.VariablesArguments = { variablesReference: 1234567 }; // when await adapter.variablesRequest( {} as DebugProtocol.VariablesResponse, args ); // then const response = adapter.getResponse( 0 ) as DebugProtocol.VariablesResponse; expect(response.success).to.equal(true); expect(response.body).to.be.ok; expect(response.body.variables).to.be.ok; expect(response.body.variables.length).to.equal(0); expect(resetIdleTimersSpy.called).to.equal(false); }); it('Should return variables for known variablesReference', async () => { // given const variables = [ new ApexVariable(newStringValue('var1'), ApexVariableKind.Static), new ApexVariable(newStringValue('var2'), ApexVariableKind.Global) ]; const variableReference = adapter.createVariableContainer( new DummyContainer(variables) ); // when await adapter.variablesRequest( {} as DebugProtocol.VariablesResponse, { variablesReference: variableReference } as DebugProtocol.VariablesArguments ); // then const response = adapter.getResponse( 0 ) as DebugProtocol.VariablesResponse; expect(response.success).to.equal(true); expect(response.body).to.be.ok; expect(response.body.variables).to.be.ok; expect(response.body.variables.length).to.equal(2); expect(response.body.variables).to.deep.equal(variables); expect(resetIdleTimersSpy.calledOnce).to.equal(true); }); it('Should return no variables when expand errors out', async () => { const variables = [ new ApexVariable(newStringValue('var1'), ApexVariableKind.Static), new ApexVariable(newStringValue('var2'), ApexVariableKind.Global) ]; const variableReference = adapter.createVariableContainer( new ErrorDummyContainer(variables) ); await adapter.variablesRequest( {} as DebugProtocol.VariablesResponse, { variablesReference: variableReference } as DebugProtocol.VariablesArguments ); const response = adapter.getResponse( 0 ) as DebugProtocol.VariablesResponse; expect(response.success).to.equal(true); expect(response.body.variables.length).to.equal(0); expect(resetIdleTimersSpy.called).to.equal(false); }); }); }); export function newStringValue( name: string, value = 'value', slot?: number ): Value { const result: any = { name, declaredTypeRef: 'java/lang/String', nameForMessages: 'String', value }; if (typeof slot !== 'undefined') { result.slot = slot; } return result; } export class DummyContainer implements VariableContainer { public variables: ApexVariable[]; public constructor(variables: ApexVariable[]) { this.variables = variables; } public expand( session: ApexDebug, filter: 'named' | 'indexed' | 'all', start: number | undefined, count: number | undefined ): Promise<ApexVariable[]> { return Promise.resolve(this.variables); } public getNumberOfChildren(): number | undefined { return undefined; } } class ErrorDummyContainer implements VariableContainer { public variables: ApexVariable[]; public constructor(variables: ApexVariable[]) { this.variables = variables; } public expand( session: ApexDebug, filter: 'named' | 'indexed' | 'all', start: number | undefined, count: number | undefined ): Promise<ApexVariable[]> { return Promise.reject('error'); } public getNumberOfChildren(): number | undefined { return undefined; } }
the_stack
'use strict'; import * as React from 'react'; // DataSet import { DataSet } from '@antv/data-set/lib/data-set'; import { View as DataView } from '@antv/data-set/lib/view'; import '@antv/data-set/lib/api/statistics'; import '@antv/data-set/lib/api/geo'; import '@antv/data-set/lib/connector/geojson'; import '@antv/data-set/lib/transform/map'; import '@antv/data-set/lib/transform/filter'; import '@antv/data-set/lib/transform/geo/projection'; import '@antv/data-set/lib/transform/geo/region'; import { Chart, View, Types, BaseChartConfig, ChartData, Colors } from '../common/types'; import Base, { ChartProps, rootClassName } from "../common/Base"; import errorWrap from '../common/errorWrap'; // @ts-ignore import chinaGeo from './mapData/chinaGeo.json'; import SouthChinaSea from './mapData/southChinaSea'; import { provinceName, positionMap } from './mapData/chinaGeoInfo'; import themes from '../themes/index'; import rectTooltip, { TooltipConfig } from '../common/rectTooltip'; import rectLegend, { LegendConfig } from '../common/rectLegend'; import label, { LabelConfig } from "../common/label"; import geomSize, { GeomSizeConfig } from '../common/geomSize'; import geomStyle, { GeomStyleConfig } from '../common/geomStyle'; import { MapChild, MapArea, MapPoint, MapHeatMap, MapShoot, MapCustom } from './child'; import './index.scss'; import Wshoot, { ShootProps } from "../Wshoot"; import { FullCrossName } from '../constants'; import { warn } from '../common/log'; import { filterKey, merge } from '../common/common'; // 这几个地点太小,需要特殊处理边框颜色 const minArea = ['钓鱼岛', '赤尾屿', '香港', '澳门']; // 这几个地点需要特殊处理标签的文字大小 const minLabel = ['钓鱼岛', '赤尾屿']; // 特殊处理一些地区的label const fixLngLatMap = { 甘肃: [104.4948862, 35.0248462], 河北: [115.5193875, 38.3062153], 天津: [118.2141694, 38.8206246], 澳门: [113.2573035, 21.7906005], 香港: [114.9040905, 21.9265955], 陕西: [108.5133047, 33.8799429], 上海: [122.2818331, 31.0480268], }; interface WmapConfig extends BaseChartConfig { background?: { fill?: string; stroke?: string; }; areaColors?: Colors; pointColors?: Colors; heatColors?: Colors; showSouthChinaSea?: boolean; type?: string; projection?: Function; legend?: LegendConfig | boolean, tooltip?: TooltipConfig | boolean, /** @deprecated labels 已废弃,请使用 label */ labels?: LabelConfig | boolean; label?: LabelConfig | boolean; size?: GeomSizeConfig; geomStyle?: GeomStyleConfig; } export interface MapProps extends ChartProps<WmapConfig> { geoData?: any; children?: MapChild; } interface MapState { customPointLayer: CustomProps[]; shootLayer: ShootProps[]; southChinaSeaKey: number; } interface CustomProps { data: MapData; render(data: Types.LooseObject, index: number, otherProps: any): React.ReactNode; } interface CustomView { id: string | number; view: View; dataView: DataView; } export class Map extends Base<WmapConfig, MapProps> { public static Area = MapArea; public static Point = MapPoint; public static HeatMap = MapHeatMap; public static Shoot = MapShoot; public static Custom = MapCustom; // 元数据 public static chinaGeoData = chinaGeo; public static provinceName = provinceName; public static positionMap = positionMap; public static getGeoProjection = DataSet.View.prototype.getGeoProjection; state: MapState = { customPointLayer: [], shootLayer: [], southChinaSeaKey: 0, }; componentDidMount() { super.componentDidMount(); this.convertChildren(this.props.children, this.props.config, true); } componentDidUpdate(prevProps: MapProps) { if (!this.isReRendering && this.props.children !== prevProps.children) { this.convertChildren(this.props.children, this.props.config); } super.componentDidUpdate(prevProps); } shouldComponentUpdate() { return !(this.isReRendering || !this.chart); } rerender() { super.rerender(); const config = this.props.config || {}; // fix: 动态切换主题后南海诸岛地图没有更新 if (config.showSouthChinaSea === undefined || config.showSouthChinaSea) { this.setState({ southChinaSeaKey: this.state.southChinaSeaKey + 1, }); } } convertPosition = (d: Types.LooseObject) => { if (!d) { return undefined; } let point = convertPointPosition(this, d); return this.bgMapView.getXY(point); }; convertChildren(children = this.props.children, config = this.props.config, isInit = false) { const customPointLayer: CustomProps[] = []; const shootLayer: ShootProps[] = []; React.Children.forEach(children, (child, index) => { if (!child) { return; } // @ts-ignore const { props, type, key } = child; if (type.displayName === MapCustom.displayName) { let newData = props.data; if (Array.isArray(newData)) { newData = newData.map((d) => { const position = this.convertPosition(d ? { ...d } : null); if (!position) { return null; } return { ...d, x: position.x, y: position.y }; }); } customPointLayer.push({ ...props, data: newData }); return; } if (type.displayName === MapShoot.displayName) { // 数据转换在 Shoot 内部完成 shootLayer.push(props); return; } if (!isInit) { const { data, config: propsConfig } = props; const layerConfig = Object.assign({}, filterKey(config, ['padding']), propsConfig); this.changeChildData(this.chart, layerConfig, type.displayName, data, key || index); } }); if (!isInit) { this.chart.render(true); } this.setState({ customPointLayer, shootLayer, }); } renderCustomPointLayer(layer: CustomProps, layerIndex: number) { if (!this.chart) { return null; } const { data, render, ...otherProps } = layer; return ( <div key={layerIndex} className={`${FullCrossName}-map-custom-container`}> { Array.isArray(data) && data.map((d, i) => { if (!d) { return null; } const pointStyle = { left: d.x, top: d.y, }; return ( <div key={i} className={`${FullCrossName}-map-custom-point`} style={pointStyle}> {render && render(d, i, otherProps)} </div> ); }) } </div> ); } renderShootLayer(shootProps: ShootProps, shootIndex: number) { if (!this.chart) { return null; } const { className, style, ...otherShootProps } = shootProps; const { width: chartWidth, height: chartHeight } = this.chart; // const [width, height] = this.bgMapSize; // const layerStyle = { // left: (chartWidth - width) / 2, // top: (chartHeight - height) / 2, // width, // height, // ...(style || {}) // }; return ( <Wshoot key={shootIndex} className={`${FullCrossName}-map-shoot ${className || ''}`} width={chartWidth} height={chartHeight} style={style} getPosition={this.convertPosition} {...otherShootProps} /> ); } renderSouthChinaSea(rootConfig: WmapConfig) { const config = merge({}, this.defaultConfig, rootConfig || {}); if (config.showSouthChinaSea === undefined || config.showSouthChinaSea) { const { southChinaSeaKey } = this.state; const { fill } = config.background || {}; const mapColor = fill || themes['widgets-map-area-bg']; return <SouthChinaSea key={southChinaSeaKey} className={`${FullCrossName}-map-south-china-sea`} fontColor={mapColor} landColor={mapColor} lineColor={mapColor} boxColor={mapColor} islandColor={mapColor} />; } else { return null; } } render() { const { className = '', style, children, data, width, height, padding, geoData, config, language, event, interaction, getChartInstance, enableFunctionUpdate, renderer, animate, ...otherProps } = this.props; const { customPointLayer, shootLayer } = this.state; return ( <div ref={dom => this.chartDom = dom} id={this.chartId} className={rootClassName + 'G2Map ' + className} style={style} {...otherProps}> {this.renderSouthChinaSea(config)} { shootLayer.length > 0 && shootLayer.map((shoot, i) => { return this.renderShootLayer(shoot, i); }) } { customPointLayer.length > 0 && customPointLayer.map((layer, i) => { return this.renderCustomPointLayer(layer, i); }) } </div> ); } chartName = 'G2Map'; convertData = false; getDefaultConfig(): WmapConfig { return { padding: [20, 20, 20, 20], background: { fill: themes['widgets-map-area-bg'], stroke: themes['widgets-map-area-border'], }, areaColors: themes.order_10, pointColors: themes.category_12, heatColors: 'rgb(0,0,255)-rgb(0,255,0)-rgb(255,255,0)-rgb(255,0,0)', type: 'china', showSouthChinaSea: true, projection: null, legend: { position: 'left', align: 'bottom', nameFormatter: null, // 可以强制覆盖,手动设置label }, tooltip: { nameFormatter: null, valueFormatter: null, }, labels: false, label: false, }; } beforeInit(props: MapProps) { const { geoData } = props; if (geoData) { this.geoData = geoData; } return props; } geoData: any = null; ds: DataSet = null; projection: Function = null; bgMapDataView: DataView = null; bgMapView: View = null; areaMapList: CustomView[] = []; areaMapDataView: DataView = null; areaMapView: View = null; pointMapList: CustomView[] = []; pointMapDataView: DataView = null; pointMapView: View = null; heatMapList: CustomView[] = []; heatMapDataView: DataView = null; heatMapView: View = null; labelMapView: View = null; init(chart: Chart, config: WmapConfig) { // 同步度量 chart.scale({ longitude: { sync: true, }, latitude: { sync: true, }, x: { nice: false, sync: true, }, y: { nice: false, sync: true, }, }); // 设置了 geo.projection 变换后,几何体的坐标系和图表的坐标系(从左下角到右上角)上下相反,所以设置镜像使地图的坐标正确。 chart.coordinate().reflect('y'); chart.axis(false); rectTooltip( this, chart, config, { showTitle: false, }, (ev: any) => { if (typeof config.tooltip === 'boolean') { return; } const { nameFormatter, valueFormatter } = config.tooltip; const { items } = ev.data; items.forEach((item: any, index: number) => { const raw = item.data || {}; if (valueFormatter) { item.value = valueFormatter(item.value, raw, index, items); } if (nameFormatter) { item.name = nameFormatter(item.name, raw, index, items); } }); }, { showTitle: false, showCrosshairs: false, // crosshairs: null, showMarkers: false, } ); // 设置图例 rectLegend(this, chart, config, {}, false); const ds = new DataSet(); this.ds = ds; drawMapBackground(this, chart, ds, config); React.Children.forEach(this.props.children, (child: MapChild, index) => { if (!child) { return; } // @ts-ignore const { props, type, key } = child; const layerConfig = Object.assign({}, filterKey(config, ['padding']), props.config); // G2 图层需要转化数据格式 let { data } = props; if (layerConfig.dataType !== 'g2') { data = convertMapData(data, type.displayName); } if (type.displayName === MapArea.displayName) { drawMapArea(this, chart, ds, layerConfig, data, key || index); } if (type.displayName === MapPoint.displayName) { drawMapPoint(this, chart, ds, layerConfig, data, key || index); } if (type.displayName === MapHeatMap.displayName) { drawHeatMap(this, chart, ds, layerConfig, data, key || index); } }); if (config.labels || config.label) { drawMapLabel(this, chart, config); } // chart.render(); } // addLayer(child: MapChild) { // if (child && child.addParent) { // child.addParent(this); // } // } /** 地图正确的长宽比 */ bgMapRatio: number = 1; /** 地图正确的尺寸 */ bgMapSize: [number, number] = [0, 0]; changeSize(chart: Chart, config: WmapConfig, chartWidth: number, chartHeight: number) { const chartRatio = chartWidth / chartHeight; const ratio = this.bgMapRatio || chartRatio; let width = chartWidth; let height = chartHeight; if (chartRatio > ratio) { width = chartHeight * ratio; } else if (chartRatio < ratio) { height = chartWidth / ratio; } if (width !== chartWidth || height !== chartHeight) { const p1 = (chartWidth - width) / 2; const p2 = (chartHeight - height) / 2; chart.appendPadding = [p2, p1, p2, p1]; } this.bgMapSize = [width, height]; chart.changeSize(chartWidth, chartHeight); // React 版方法 this.convertChildren(this.props.children, this.props.config, true); } changeChildData(chart: Chart, config: WmapConfig, viewName: string, newData: ChartData, key: string | number) { const { ds } = this; let data = newData; if (config.dataType !== 'g2') { data = convertMapData(newData, viewName); } if (viewName === MapArea.displayName) { drawMapArea(this, chart, ds, config, data, key); } if (viewName === MapPoint.displayName) { drawMapPoint(this, chart, ds, config, data, key); } if (viewName === MapHeatMap.displayName) { drawHeatMap(this, chart, ds, config, data, key); } } /** @override Map 使用自定义 changeData 方法,覆盖原方法逻辑 */ changeData() {} // 销毁时需要清空 dataView,否则切换主题时,更新会进入到旧的图表实例中 destroy() { this.bgMapDataView = null; this.areaMapDataView = null; this.pointMapDataView = null; this.heatMapDataView = null; this.areaMapList = []; this.pointMapList = []; this.heatMapList = []; } } // 绘制地图背景 function drawMapBackground(ctx: Map, chart: Chart, ds: DataSet, config: WmapConfig) { let geoData = null; if (ctx.geoData) { // 如果用户有传geoData,优先使用 geoData = ctx.geoData; } else if (config.type === 'china') { // 自带中国地图数据 geoData = chinaGeo; } else { warn('Wmap', 'no geo data, can\'t draw the map!'); } const bgMapDataView = ds.createView('bgMap').source(geoData, { type: 'GeoJSON', }); let { projection } = config; if (!projection) { projection = bgMapDataView.getGeoProjection('geoConicEqualArea'); projection // @ts-ignore .center([0, 36.4]) .parallels([25, 47]) .scale(1000) .rotate([-105, 0]) .translate([0, 0]); } bgMapDataView.transform({ type: 'geo.projection', // 因为G2的投影函数不支持设置投影参数,这里使用自定义的投影函数设置参数 // @ts-ignore projection() { return projection; }, as: ['x', 'y', 'cX', 'cY'], }); if (config.type === 'china') { // 过滤掉南海诸岛 bgMapDataView.transform({ type: 'filter', callback(row) { return row.properties.name !== '南海诸岛'; }, }); } // start: 按照投影后尺寸比例调整图表的真实比例 const longitudeRange = bgMapDataView.range('x'); const latitudeRange = bgMapDataView.range('y'); const ratio = (longitudeRange[1] - longitudeRange[0]) / (latitudeRange[1] - latitudeRange[0]); ctx.bgMapRatio = ratio; const { width: chartWidth, height: chartHeight } = chart; const chartRatio = chartWidth / chartHeight; let width = chartWidth; let height = chartHeight; if (chartRatio > ratio) { width = chartHeight * ratio; } else if (chartRatio < ratio) { height = chartWidth / ratio; } if (width !== chartWidth || height !== chartHeight) { const p1 = (chartWidth - width) / 2; const p2 = (chartHeight - height) / 2; // 不设置尺寸,通过padding控制地图形状 chart.appendPadding = [p2, p1, p2, p1]; } ctx.bgMapSize = [width, height]; // end: 按照投影后尺寸比例调整图表的真实比例 const { fill: bgFill, stroke: bgStroke, ...otherBgStyle } = config.background || {}; const bgMapView = chart.createView({ padding: 0, }); bgMapView.data(bgMapDataView.rows); bgMapView.tooltip(false); bgMapView .polygon() .position('x*y') .style('name', function(name) { const result = { fill: bgFill || themes['widgets-map-area-bg'], stroke: bgStroke || themes['widgets-map-area-border'], lineWidth: 1, ...otherBgStyle, }; // 对一些尺寸非常小的形状特殊处理,以显示出来。 if (minArea.indexOf(name) > -1) { result.stroke = bgFill || themes['widgets-map-area-bg']; } return result; }); ctx.bgMapDataView = bgMapDataView; ctx.bgMapView = bgMapView; ctx.projection = projection; } function getView(list: CustomView[], key: string | number) { return list.find(item => item.id === key); } // 绘制分级统计地图 function drawMapArea(ctx: Map, chart: Chart, ds: DataSet, config: WmapConfig, data: MapData, key: string | number) { const areaMap = getView(ctx.areaMapList, key); if (areaMap) { let { dataView: areaMapDataView, view: areaMapView } = areaMap; if (areaMapDataView.origin !== data) { areaMapDataView.source(data); areaMapView.data(areaMapDataView.rows); } } else { const areaMapDataView = ds .createView() .source(data) .transform({ type: 'map', callback(obj) { const { name, type, ...others } = obj; return { // @ts-ignore 将省份全称转化为简称 name: provinceName[name] ? provinceName[name] : name, type: String(type), ...others, }; }, }) .transform({ geoDataView: ctx.bgMapDataView, field: 'name', type: 'geo.region', as: ['x', 'y'], }); const areaMapView = chart.createView({ padding: config.padding || 0, }); areaMapView.data(areaMapDataView.rows); const areaGeom = areaMapView .polygon() .position('x*y') // 如果用连续型颜色,需要对数组倒序,否则颜色对应的数值会从小开始 .color('areaType', getMapContinuousColor(config.areaColors)) // .opacity('value') .tooltip('name*value', (name, value) => ({ name, value, })); geomStyle(areaGeom, config.geomStyle); ctx.areaMapList.push({ id: key, view: areaMapView, dataView: areaMapDataView, }); } } // 绘制散点图 function drawMapPoint(ctx: Map, chart: Chart, ds: DataSet, config: WmapConfig, data: MapData, key: string | number) { const pointMap = getView(ctx.pointMapList, key); if (pointMap) { let { dataView: pointMapDataView, view: pointMapView } = pointMap; if (pointMapDataView.origin !== data) { pointMapDataView.source(data); pointMapView.data(pointMapDataView.rows); } } else { const pointMapDataView = ds .createView() .source(data) .transform({ type: 'map', callback: point => { const newPoint = Object.assign({}, point); newPoint.type = String(newPoint.type); return convertPointPosition(ctx, newPoint); }, }); const pointMapView = chart.createView({ padding: config.padding || 0, }); pointMapView.data(pointMapDataView.rows); const pointGeom = pointMapView .point() .position('x*y') .shape('circle') .color('pointType', config.pointColors) .tooltip('name*value', (name, value) => ({ name, value, })) // .active(false); geomSize(pointGeom, config.size, 4, 'value', 'name*value'); geomStyle(pointGeom, config.geomStyle); if (config.labels) { warn('config.labels', '属性已废弃,请使用 config.label'); } label(pointGeom, config, 'name', { // FIXME 默认的动画会导致部分label不显示,暂时关闭动画 animate: false, }); if (config.labels || config.label) { // let labelConfig = {}; // if (typeof config.labels === 'object') { // labelConfig = config.labels; // } else if (typeof config.label === 'object') { // labelConfig = config.label; // } // // const { offset = 0, textStyle = {}, formatter } = labelConfig; // pointGeom.label('name', { // FIXME 默认的动画会导致部分label不显示,暂时关闭动画 // animate: false, // offset: `${offset - Number(themes['widgets-font-size-1'].replace('px', ''))}`, // textStyle: { // fill: themes['widgets-map-label'], // // 需要去掉 px 的字符串 // fontSize: themes['widgets-font-size-1'].replace('px', ''), // textBaseline: 'middle', // ...textStyle, // }, // formatter: formatter || null, // }); } ctx.pointMapList.push({ id: key, view: pointMapView, dataView: pointMapDataView, }); } } // 绘制热力图 function drawHeatMap(ctx: Map, chart: Chart, ds: DataSet, config: WmapConfig, data: MapData, key: string | number) { const heatMap = getView(ctx.heatMapList, key); if (heatMap) { let { dataView: heatMapDataView, view: heatMapView } = heatMap; if (heatMapDataView.origin !== data) { heatMapDataView.source(data); heatMapView.data(heatMapDataView.rows); } } else { const heatMapDataView = ds .createView() .source(data) .transform({ type: 'map', callback: point => { const newPoint = Object.assign({}, point); newPoint.type = String(newPoint.type); return convertPointPosition(ctx, newPoint); }, }); const heatMapView = chart.createView({ padding: config.padding || 0, }); heatMapView.data(heatMapDataView.rows); chart.legend('value', false); const heatGeom = heatMapView .heatmap() .position('x*y') .color('value', config.heatColors) .tooltip('name*value', (name, value) => ({ name, value, })) geomSize(heatGeom, config.size, 16, 'value', 'name*value'); ctx.heatMapList.push({ id: key, view: heatMapView, dataView: heatMapDataView, }); } } // 绘制背景地图标签 function drawMapLabel(ctx: Map, chart: Chart, config: WmapConfig) { const labelConfig = config.labels || config.label; // 将背景数据集中的中心点坐标(cX, cY)映射为新数据中的x, y。保证scale可以同步这个view的度量。 const labelData = ctx.bgMapDataView.rows.map(row => { const label = { name: row.name, x: row.cX, y: row.cY, }; // @ts-ignore fix 某些地区label位置不好,需要重新定位 const fixLngLat = fixLngLatMap[row.name]; if (fixLngLat) { // @ts-ignore 第二个参数支持函数 const position = ctx.bgMapDataView.geoProjectPosition(fixLngLat, ctx.projection, true); label.x = position[0]; label.y = position[1]; } return label; }); // @ts-ignore label 需要函数处理,无法放到 label 工具函数中 const { offset = 0, style, textStyle = {}, labelFormatter } = typeof labelConfig === 'object' ? labelConfig : {}; const labelMapView = chart.createView({ padding: 0, }); labelMapView.data(labelData); labelMapView .point() .position('x*y') .size(0) // 由于需要根据 name 判断小尺寸 label 的字号,这里暂时不能用标准 label 函数处理 .label('name', function (name) { let fontSize = themes['widgets-font-size-1'].replace('px', ''); // 对一些尺寸非常小的形状特殊处理,以显示出来。 if (minLabel.indexOf(name) > -1) { fontSize = String(Number(fontSize) * 2 / 3); } if (textStyle) { warn('Wmap.config.label', 'textStyle 属性已废弃,请使用 style 属性'); } const labelStyle = { fill: themes['widgets-map-label'], // 需要去掉 px 的字符串 fontSize: fontSize, textBaseline: 'middle', ...textStyle, ...style, } const result: Types.GeometryLabelCfg = { offset, style: labelStyle, // FIXME 默认的动画会导致部分label不显示,暂时关闭动画 animate: false, }; if (labelFormatter) { result.content = (v, item, index) => { return labelFormatter(v['name'], item, index); } } return result; }) .tooltip(false) // .active(false); ctx.labelMapView = labelMapView; } type MapData = Types.LooseObject[]; interface RawMapData { name: string; data: MapData; } // 转换地图数据结构,因为和默认结构不同,需要特殊处理。 function convertMapData(data: RawMapData[], viewName: string) { if (!Array.isArray(data)) { return []; } let typeName = 'type'; if (viewName === MapArea.displayName) { typeName = 'areaType'; } if (viewName === MapPoint.displayName) { typeName = 'pointType'; } // if (viewName === MapHeatMap.displayName) { // typeName = 'heatmapType'; // } const result: MapData = []; data.forEach(item => { const { name = '', data: itemData } = item; if (!Array.isArray(itemData)) { return; } itemData.forEach(d => { result.push({ ...d, [typeName]: d.type || name, }); }); }); return result; } // 计算数据的坐标点 export function convertPointPosition(ctx: Map, point: Types.LooseObject) { if (point.x && point.y) { return point; } if (!ctx.bgMapDataView) { return point; } const { projection } = ctx; if (point.lng && point.lat) { return getProjectionPosition( point, ctx.bgMapDataView, projection, Number(point.lng), Number(point.lat) ); } if (point.name) { let { name } = point; if (!/^\w/.test(name)) { if (/^\u963F\u62C9/.test(name) || /^\u5F20\u5BB6/.test(name)) { // 阿拉、张家 两个开头的需要截取三个字符 name = name.slice(0, 3); } else if (!/\u7701$/.test(name) && !/\u81ea\u6cbb\u533a$/.test(name)) { // 以"省" / "自治区"结尾的不截断 name = name.slice(0, 2); } } // @ts-ignore const position = positionMap[name]; if (position) { return getProjectionPosition( point, ctx.bgMapDataView, projection, position.lng, position.lat ); } } if (!point.x || !point.y) { warn('Wmap', '无法定位地点', point); } return point; } function getProjectionPosition(point: Types.LooseObject, view: DataView, projection: Function, lng: number, lat: number) { // @ts-ignore const projectedCoord = view.geoProjectPosition([lng, lat], projection, true); point.x = projectedCoord[0]; point.y = projectedCoord[1]; return point; } // // 地图的tooltip逻辑 // function mapTooltip(chart, config) { // // tooltip // if (config.tooltip !== false) { // const { nameFormatter, valueFormatter, customConfig } = // config.tooltip || {}; // // const tooltipCfg = { // showTitle: false, // crosshairs: null, // itemTpl: // '<li data-index={index}>' + // '<svg viewBox="0 0 6 6" class="g2-tooltip-marker"></svg>' + // '<span class="g2-tooltip-item-name">{name}</span>:<span class="g2-tooltip-item-value">{value}</span></li>', // }; // // if (customConfig) { // merge(tooltipCfg, customConfig); // } // // chart.tooltip(tooltipCfg); // // if (nameFormatter || valueFormatter) { // chart.on('tooltip:change', ev => { // ev.items.forEach((item, index) => { // const raw = item.point._origin || {}; // // if (valueFormatter) { // item.value = valueFormatter(item.value, raw, index, ev.items); // } // if (nameFormatter) { // item.name = nameFormatter(item.name, raw, index, ev.items); // } // }); // }); // } // } else { // chart.tooltip(false); // } // } function getMapContinuousColor(color: Colors) { if (Array.isArray(color)) { return color.join('-'); } else { return color; } } const Wmap: typeof Map = errorWrap(Map); Wmap.Area = Map.Area; Wmap.Point = Map.Point; Wmap.HeatMap = Map.HeatMap; Wmap.Shoot = Map.Shoot; Wmap.Custom = Map.Custom; Wmap.chinaGeoData = Map.chinaGeoData; Wmap.provinceName = Map.provinceName; Wmap.positionMap = Map.positionMap; Wmap.getGeoProjection = Map.getGeoProjection; export default Wmap;
the_stack
import { Storage } from '../types'; import { Group, Match, MatchGame, Round, SeedOrdering, Stage, StageType } from 'brackets-model'; import { BracketKind, RoundPositionalInfo } from '../types'; import { Create } from '../create'; import * as helpers from '../helpers'; export class BaseGetter { protected readonly storage: Storage; /** * Creates an instance of a Storage getter. * * @param storage The implementation of Storage. */ constructor(storage: Storage) { this.storage = storage; } /** * Gets all the rounds that contain ordered participants. * * @param stage The stage to get rounds from. */ protected async getOrderedRounds(stage: Stage): Promise<Round[]> { if (!stage?.settings.size) throw Error('The stage has no size.'); if (stage.type === 'single_elimination') return this.getOrderedRoundsSingleElimination(stage.id); return this.getOrderedRoundsDoubleElimination(stage.id); } /** * Gets all the rounds that contain ordered participants in a single elimination stage. * * @param stageId ID of the stage. */ private async getOrderedRoundsSingleElimination(stageId: number): Promise<Round[]> { return [await this.getUpperBracketFirstRound(stageId)]; } /** * Gets all the rounds that contain ordered participants in a double elimination stage. * * @param stageId ID of the stage. */ private async getOrderedRoundsDoubleElimination(stageId: number): Promise<Round[]> { // Getting all rounds instead of cherry-picking them is the least expensive. const rounds = await this.storage.select('round', { stage_id: stageId }); if (!rounds) throw Error('Error getting rounds.'); const loserBracket = await this.getLoserBracket(stageId); if (!loserBracket) throw Error('Loser bracket not found.'); const firstRoundWB = rounds[0]; const roundsLB = rounds.filter(r => r.group_id === loserBracket.id); const orderedRoundsLB = roundsLB.filter(r => helpers.isOrderingSupportedLoserBracket(r.number, roundsLB.length)); return [firstRoundWB, ...orderedRoundsLB]; } /** * Gets the positional information (number in group and total number of rounds in group) of a round based on its id. * * @param roundId ID of the round. */ protected async getRoundPositionalInfo(roundId: number): Promise<RoundPositionalInfo> { const round = await this.storage.select('round', roundId); if (!round) throw Error('Round not found.'); const rounds = await this.storage.select('round', { group_id: round.group_id }); if (!rounds) throw Error('Error getting rounds.'); return { roundNumber: round.number, roundCount: rounds.length, }; } /** * Gets the matches leading to the given match. * * @param match The current match. * @param matchLocation Location of the current match. * @param stage The parent stage. * @param roundNumber Number of the round. */ protected async getPreviousMatches(match: Match, matchLocation: BracketKind, stage: Stage, roundNumber: number): Promise<Match[]> { if (matchLocation === 'loser_bracket') return this.getPreviousMatchesLB(match, stage, roundNumber); if (matchLocation === 'final_group') return this.getPreviousMatchesFinal(match, roundNumber); if (roundNumber === 1) return []; // The match is in the first round of an upper bracket. return this.getMatchesBeforeMajorRound(match, roundNumber); } /** * Gets the matches leading to the given match, which is in a final group (consolation final or grand final). * * @param match The current match. * @param roundNumber Number of the current round. */ private async getPreviousMatchesFinal(match: Match, roundNumber: number): Promise<Match[]> { if (roundNumber > 1) return [await this.findMatch(match.group_id, roundNumber - 1, 1)]; const upperBracket = await this.getUpperBracket(match.stage_id); const lastRound = await this.getLastRound(upperBracket.id); const upperBracketFinalMatch = await this.storage.selectFirst('match', { round_id: lastRound.id, number: 1, }); if (upperBracketFinalMatch === null) throw Error('Match not found.'); return [upperBracketFinalMatch]; } /** * Gets the matches leading to a given match from the loser bracket. * * @param match The current match. * @param stage The parent stage. * @param roundNumber Number of the round. */ private async getPreviousMatchesLB(match: Match, stage: Stage, roundNumber: number): Promise<Match[]> { if (stage.settings.skipFirstRound && roundNumber === 1) return []; if (helpers.hasBye(match)) return []; // Shortcut because we are coming from propagateByes(). const winnerBracket = await this.getUpperBracket(match.stage_id); const actualRoundNumberWB = Math.ceil((roundNumber + 1) / 2); const roundNumberWB = stage.settings.skipFirstRound ? actualRoundNumberWB - 1 : actualRoundNumberWB; if (roundNumber === 1) return this.getMatchesBeforeFirstRoundLB(match, winnerBracket.id, roundNumberWB); if (roundNumber % 2 === 0) return this.getMatchesBeforeMinorRoundLB(match, winnerBracket.id, roundNumber, roundNumberWB); return this.getMatchesBeforeMajorRound(match, roundNumber); } /** * Gets the matches leading to a given match in a major round (every round of upper bracket or specific ones in lower bracket). * * @param match The current match. * @param roundNumber Number of the round. */ private async getMatchesBeforeMajorRound(match: Match, roundNumber: number): Promise<Match[]> { return [ await this.findMatch(match.group_id, roundNumber - 1, match.number * 2 - 1), await this.findMatch(match.group_id, roundNumber - 1, match.number * 2), ]; } /** * Gets the matches leading to a given match in the first round of the loser bracket. * * @param match The current match. * @param winnerBracketId ID of the winner bracket. * @param roundNumberWB The number of the previous round in the winner bracket. */ private async getMatchesBeforeFirstRoundLB(match: Match, winnerBracketId: number, roundNumberWB: number): Promise<Match[]> { return [ await this.findMatch(winnerBracketId, roundNumberWB, helpers.getOriginPosition(match, 'opponent1')), await this.findMatch(winnerBracketId, roundNumberWB, helpers.getOriginPosition(match, 'opponent2')), ]; } /** * Gets the matches leading to a given match in a minor round of the loser bracket. * * @param match The current match. * @param winnerBracketId ID of the winner bracket. * @param roundNumber Number of the current round. * @param roundNumberWB The number of the previous round in the winner bracket. */ private async getMatchesBeforeMinorRoundLB(match: Match, winnerBracketId: number, roundNumber: number, roundNumberWB: number): Promise<Match[]> { const matchNumber = helpers.getOriginPosition(match, 'opponent1'); return [ await this.findMatch(winnerBracketId, roundNumberWB, matchNumber), await this.findMatch(match.group_id, roundNumber - 1, match.number), ]; } /** * Gets the match(es) where the opponents of the current match will go just after. * * @param match The current match. * @param matchLocation Location of the current match. * @param stage The parent stage. * @param roundNumber The number of the current round. * @param roundCount Count of rounds. */ protected async getNextMatches(match: Match, matchLocation: BracketKind, stage: Stage, roundNumber: number, roundCount: number): Promise<(Match | null)[]> { switch (matchLocation) { case 'single_bracket': return this.getNextMatchesUpperBracket(match, stage.type, roundNumber, roundCount); case 'winner_bracket': return this.getNextMatchesWB(match, stage, roundNumber, roundCount); case 'loser_bracket': return this.getNextMatchesLB(match, stage.type, roundNumber, roundCount); case 'final_group': return this.getNextMatchesFinal(match, roundNumber, roundCount); default: throw Error('Unknown bracket kind.'); } } /** * Gets the match(es) where the opponents of the current match of winner bracket will go just after. * * @param match The current match. * @param stage The parent stage. * @param roundNumber The number of the current round. * @param roundCount Count of rounds. */ private async getNextMatchesWB(match: Match, stage: Stage, roundNumber: number, roundCount: number): Promise<(Match | null)[]> { const loserBracket = await this.getLoserBracket(match.stage_id); if (loserBracket === null) // Only one match in the stage, there is no loser bracket. return []; const actualRoundNumber = stage.settings.skipFirstRound ? roundNumber + 1 : roundNumber; const roundNumberLB = actualRoundNumber > 1 ? (actualRoundNumber - 1) * 2 : 1; const matchNumberLB = actualRoundNumber > 1 ? match.number : helpers.getDiagonalMatchNumber(match.number); const participantCount = stage.settings.size!; const method = helpers.getLoserOrdering(stage.settings.seedOrdering!, roundNumberLB); const actualMatchNumberLB = helpers.findLoserMatchNumber(participantCount, roundNumberLB, matchNumberLB, method); return [ ...await this.getNextMatchesUpperBracket(match, stage.type, roundNumber, roundCount), await this.findMatch(loserBracket.id, roundNumberLB, actualMatchNumberLB), ]; } /** * Gets the match(es) where the opponents of the current match of an upper bracket will go just after. * * @param match The current match. * @param stageType Type of the stage. * @param roundNumber The number of the current round. * @param roundCount Count of rounds. */ private async getNextMatchesUpperBracket(match: Match, stageType: StageType, roundNumber: number, roundCount: number): Promise<(Match | null)[]> { if (stageType === 'single_elimination') return this.getNextMatchesUpperBracketSingleElimination(match, stageType, roundNumber, roundCount); if (stageType === 'double_elimination' && roundNumber === roundCount) return [await this.getFirstMatchFinal(match, stageType)]; return [await this.getDiagonalMatch(match.group_id, roundNumber, match.number)]; } /** * Gets the match(es) where the opponents of the current match of the unique bracket of a single elimination will go just after. * * @param match The current match. * @param stageType Type of the stage. * @param roundNumber The number of the current round. * @param roundCount Count of rounds. */ private async getNextMatchesUpperBracketSingleElimination(match: Match, stageType: StageType, roundNumber: number, roundCount: number): Promise<Match[]> { if (roundNumber === roundCount - 1) { const final = await this.getFirstMatchFinal(match, stageType); return [ await this.getDiagonalMatch(match.group_id, roundNumber, match.number), ...final ? [final] : [], ]; } if (roundNumber === roundCount) return []; return [await this.getDiagonalMatch(match.group_id, roundNumber, match.number)]; } /** * Gets the match(es) where the opponents of the current match of loser bracket will go just after. * * @param match The current match. * @param stageType Type of the stage. * @param roundNumber The number of the current round. * @param roundCount Count of rounds. */ private async getNextMatchesLB(match: Match, stageType: StageType, roundNumber: number, roundCount: number): Promise<Match[]> { if (roundNumber === roundCount) { const final = await this.getFirstMatchFinal(match, stageType); return final ? [final] : []; } if (roundNumber % 2 === 1) return this.getMatchAfterMajorRoundLB(match, roundNumber); return this.getMatchAfterMinorRoundLB(match, roundNumber); } /** * Gets the first match of the final group (consolation final or grand final). * * @param match The current match. * @param stageType Type of the stage. */ private async getFirstMatchFinal(match: Match, stageType: StageType): Promise<Match | null> { const finalGroupId = await this.getFinalGroupId(match.stage_id, stageType); if (finalGroupId === null) return null; return this.findMatch(finalGroupId, 1, 1); } /** * Gets the matches following the current match, which is in the final group (consolation final or grand final). * * @param match The current match. * @param roundNumber The number of the current round. * @param roundCount The count of rounds. */ private async getNextMatchesFinal(match: Match, roundNumber: number, roundCount: number): Promise<Match[]> { if (roundNumber === roundCount) return []; return [await this.findMatch(match.group_id, roundNumber + 1, 1)]; } /** * Gets the match(es) where the opponents of the current match of a winner bracket's major round will go just after. * * @param match The current match. * @param roundNumber The number of the current round. */ private async getMatchAfterMajorRoundLB(match: Match, roundNumber: number): Promise<Match[]> { return [await this.getParallelMatch(match.group_id, roundNumber, match.number)]; } /** * Gets the match(es) where the opponents of the current match of a winner bracket's minor round will go just after. * * @param match The current match. * @param roundNumber The number of the current round. */ private async getMatchAfterMinorRoundLB(match: Match, roundNumber: number): Promise<Match[]> { return [await this.getDiagonalMatch(match.group_id, roundNumber, match.number)]; } /** * Returns the good seeding ordering based on the stage's type. * * @param stageType The type of the stage. * @param create A reference to a Create instance. */ protected static getSeedingOrdering(stageType: StageType, create: Create): SeedOrdering { return stageType === 'round_robin' ? create.getRoundRobinOrdering() : create.getStandardBracketFirstRoundOrdering(); } /** * Returns the matches which contain the seeding of a stage based on its type. * * @param stageId ID of the stage. * @param stageType The type of the stage. */ protected async getSeedingMatches(stageId: number, stageType: StageType): Promise<Match[] | null> { if (stageType === 'round_robin') return this.storage.select('match', { stage_id: stageId }); const firstRound = await this.getUpperBracketFirstRound(stageId); return this.storage.select('match', { round_id: firstRound.id }); } /** * Gets the first round of the upper bracket. * * @param stageId ID of the stage. */ private async getUpperBracketFirstRound(stageId: number): Promise<Round> { // Considering the database is ordered, this round will always be the first round of the upper bracket. const firstRound = await this.storage.selectFirst('round', { stage_id: stageId, number: 1 }); if (!firstRound) throw Error('Round not found.'); return firstRound; } /** * Gets the last round of a group. * * @param groupId ID of the group. */ private async getLastRound(groupId: number): Promise<Round> { const round = await this.storage.selectLast('round', { group_id: groupId }); if (!round) throw Error('Error getting rounds.'); return round; } /** * Returns the id of the final group (consolation final or grand final). * * @param stageId ID of the stage. * @param stageType Type of the stage. */ private async getFinalGroupId(stageId: number, stageType: StageType): Promise<number | null> { const groupNumber = stageType === 'single_elimination' ? 2 /* Consolation final */ : 3 /* Grand final */; const finalGroup = await this.storage.selectFirst('group', { stage_id: stageId, number: groupNumber }); if (!finalGroup) return null; return finalGroup.id; } /** * Gets the upper bracket (the only bracket if single elimination or the winner bracket in double elimination). * * @param stageId ID of the stage. */ protected async getUpperBracket(stageId: number): Promise<Group> { const winnerBracket = await this.storage.selectFirst('group', { stage_id: stageId, number: 1 }); if (!winnerBracket) throw Error('Winner bracket not found.'); return winnerBracket; } /** * Gets the loser bracket. * * @param stageId ID of the stage. */ protected async getLoserBracket(stageId: number): Promise<Group | null> { return this.storage.selectFirst('group', { stage_id: stageId, number: 2 }); } /** * Gets the corresponding match in the next round ("diagonal match") the usual way. * * Just like from Round 1 to Round 2 in a single elimination stage. * * @param groupId ID of the group. * @param roundNumber Number of the round in its parent group. * @param matchNumber Number of the match in its parent round. */ private async getDiagonalMatch(groupId: number, roundNumber: number, matchNumber: number): Promise<Match> { return this.findMatch(groupId, roundNumber + 1, helpers.getDiagonalMatchNumber(matchNumber)); } /** * Gets the corresponding match in the next round ("parallel match") the "major round to minor round" way. * * Just like from Round 1 to Round 2 in the loser bracket of a double elimination stage. * * @param groupId ID of the group. * @param roundNumber Number of the round in its parent group. * @param matchNumber Number of the match in its parent round. */ private async getParallelMatch(groupId: number, roundNumber: number, matchNumber: number): Promise<Match> { return this.findMatch(groupId, roundNumber + 1, matchNumber); } /** * Finds a match in a given group. The match must have the given number in a round of which the number in group is given. * * **Example:** In group of id 1, give me the 4th match in the 3rd round. * * @param groupId ID of the group. * @param roundNumber Number of the round in its parent group. * @param matchNumber Number of the match in its parent round. */ protected async findMatch(groupId: number, roundNumber: number, matchNumber: number): Promise<Match> { const round = await this.storage.selectFirst('round', { group_id: groupId, number: roundNumber, }); if (!round) throw Error('Round not found.'); const match = await this.storage.selectFirst('match', { round_id: round.id, number: matchNumber, }); if (!match) throw Error('Match not found.'); return match; } /** * Finds a match game based on its `id` or based on the combination of its `parent_id` and `number`. * * @param game Values to change in a match game. */ protected async findMatchGame(game: Partial<MatchGame>): Promise<MatchGame> { if (game.id !== undefined) { const stored = await this.storage.select('match_game', game.id); if (!stored) throw Error('Match game not found.'); return stored; } if (game.parent_id !== undefined && game.number) { const stored = await this.storage.selectFirst('match_game', { parent_id: game.parent_id, number: game.number, }); if (!stored) throw Error('Match game not found.'); return stored; } throw Error('No match game id nor parent id and number given.'); } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages a Cloud Dataproc cluster resource within GCP. * * * [API documentation](https://cloud.google.com/dataproc/docs/reference/rest/v1/projects.regions.clusters) * * How-to Guides * * [Official Documentation](https://cloud.google.com/dataproc/docs) * * !> **Warning:** Due to limitations of the API, all arguments except * `labels`,`cluster_config.worker_config.num_instances` and `cluster_config.preemptible_worker_config.num_instances` are non-updatable. Changing others will cause recreation of the * whole cluster! * * ## Example Usage * ### Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const simplecluster = new gcp.dataproc.Cluster("simplecluster", { * region: "us-central1", * }); * ``` * ### Advanced * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const _default = new gcp.serviceaccount.Account("default", { * accountId: "service-account-id", * displayName: "Service Account", * }); * const mycluster = new gcp.dataproc.Cluster("mycluster", { * region: "us-central1", * gracefulDecommissionTimeout: "120s", * labels: { * foo: "bar", * }, * clusterConfig: { * stagingBucket: "dataproc-staging-bucket", * masterConfig: { * numInstances: 1, * machineType: "e2-medium", * diskConfig: { * bootDiskType: "pd-ssd", * bootDiskSizeGb: 30, * }, * }, * workerConfig: { * numInstances: 2, * machineType: "e2-medium", * minCpuPlatform: "Intel Skylake", * diskConfig: { * bootDiskSizeGb: 30, * numLocalSsds: 1, * }, * }, * preemptibleWorkerConfig: { * numInstances: 0, * }, * softwareConfig: { * imageVersion: "1.3.7-deb9", * overrideProperties: { * "dataproc:dataproc.allow.zero.workers": "true", * }, * }, * gceClusterConfig: { * tags: [ * "foo", * "bar", * ], * serviceAccount: _default.email, * serviceAccountScopes: ["cloud-platform"], * }, * initializationActions: [{ * script: "gs://dataproc-initialization-actions/stackdriver/stackdriver.sh", * timeoutSec: 500, * }], * }, * }); * ``` * ### Using A GPU Accelerator * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const acceleratedCluster = new gcp.dataproc.Cluster("accelerated_cluster", { * clusterConfig: { * gceClusterConfig: { * zone: "us-central1-a", * }, * masterConfig: { * accelerators: [{ * acceleratorCount: 1, * acceleratorType: "nvidia-tesla-k80", * }], * }, * }, * region: "us-central1", * }); * ``` * * ## Import * * This resource does not support import. */ export class Cluster extends pulumi.CustomResource { /** * Get an existing Cluster resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ClusterState, opts?: pulumi.CustomResourceOptions): Cluster { return new Cluster(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:dataproc/cluster:Cluster'; /** * Returns true if the given object is an instance of Cluster. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Cluster { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Cluster.__pulumiType; } /** * Allows you to configure various aspects of the cluster. * Structure defined below. */ public readonly clusterConfig!: pulumi.Output<outputs.dataproc.ClusterClusterConfig>; /** * The timeout duration which allows graceful decomissioning when you change the number of worker nodes directly through a * terraform apply */ public readonly gracefulDecommissionTimeout!: pulumi.Output<string | undefined>; /** * The list of labels (key/value pairs) to be applied to * instances in the cluster. GCP generates some itself including `goog-dataproc-cluster-name` * which is the name of the cluster. */ public readonly labels!: pulumi.Output<{[key: string]: string}>; /** * The name of the cluster, unique within the project and * zone. */ public readonly name!: pulumi.Output<string>; /** * The ID of the project in which the `cluster` will exist. If it * is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * The region in which the cluster and associated nodes will be created in. * Defaults to `global`. */ public readonly region!: pulumi.Output<string | undefined>; /** * Create a Cluster resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args?: ClusterArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ClusterArgs | ClusterState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ClusterState | undefined; inputs["clusterConfig"] = state ? state.clusterConfig : undefined; inputs["gracefulDecommissionTimeout"] = state ? state.gracefulDecommissionTimeout : undefined; inputs["labels"] = state ? state.labels : undefined; inputs["name"] = state ? state.name : undefined; inputs["project"] = state ? state.project : undefined; inputs["region"] = state ? state.region : undefined; } else { const args = argsOrState as ClusterArgs | undefined; inputs["clusterConfig"] = args ? args.clusterConfig : undefined; inputs["gracefulDecommissionTimeout"] = args ? args.gracefulDecommissionTimeout : undefined; inputs["labels"] = args ? args.labels : undefined; inputs["name"] = args ? args.name : undefined; inputs["project"] = args ? args.project : undefined; inputs["region"] = args ? args.region : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Cluster.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Cluster resources. */ export interface ClusterState { /** * Allows you to configure various aspects of the cluster. * Structure defined below. */ clusterConfig?: pulumi.Input<inputs.dataproc.ClusterClusterConfig>; /** * The timeout duration which allows graceful decomissioning when you change the number of worker nodes directly through a * terraform apply */ gracefulDecommissionTimeout?: pulumi.Input<string>; /** * The list of labels (key/value pairs) to be applied to * instances in the cluster. GCP generates some itself including `goog-dataproc-cluster-name` * which is the name of the cluster. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The name of the cluster, unique within the project and * zone. */ name?: pulumi.Input<string>; /** * The ID of the project in which the `cluster` will exist. If it * is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The region in which the cluster and associated nodes will be created in. * Defaults to `global`. */ region?: pulumi.Input<string>; } /** * The set of arguments for constructing a Cluster resource. */ export interface ClusterArgs { /** * Allows you to configure various aspects of the cluster. * Structure defined below. */ clusterConfig?: pulumi.Input<inputs.dataproc.ClusterClusterConfig>; /** * The timeout duration which allows graceful decomissioning when you change the number of worker nodes directly through a * terraform apply */ gracefulDecommissionTimeout?: pulumi.Input<string>; /** * The list of labels (key/value pairs) to be applied to * instances in the cluster. GCP generates some itself including `goog-dataproc-cluster-name` * which is the name of the cluster. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The name of the cluster, unique within the project and * zone. */ name?: pulumi.Input<string>; /** * The ID of the project in which the `cluster` will exist. If it * is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The region in which the cluster and associated nodes will be created in. * Defaults to `global`. */ region?: pulumi.Input<string>; }
the_stack
import AWS from 'aws-sdk'; import AWSMock from 'aws-sdk-mock'; import { mockProcessStdout } from 'jest-mock-process'; import { ListrTaskWrapper } from 'listr2'; import nock from 'nock'; import { createMockTask } from '../util'; import { SnapshotRemoveElasticacheRedisTrick, SnapshotRemoveElasticacheRedisState, } from '../../src/tricks/snapshot-remove-elasticache-redis.trick'; import { ElasticacheReplicationGroupState } from '../../src/states/elasticache-replication-group.state'; import { TrickContext } from '../../src/types/trick-context'; import { TrickOptionsInterface } from '../../src/types/trick-options.interface'; const SampleReplicationGroupState = { id: 'foo', snapshotName: 'foo-12345567', status: 'available', createParams: { AtRestEncryptionEnabled: true, AutoMinorVersionUpgrade: true, AutomaticFailoverEnabled: true, CacheNodeType: 'cache.t2.small', CacheParameterGroupName: 'baz', CacheSecurityGroupNames: ['quuz'], CacheSubnetGroupName: 'qux', Engine: 'redis', EngineVersion: '5.0.6', // GlobalReplicationGroupId: undefined, KmsKeyId: 'secret-key-id', MultiAZEnabled: true, // NodeGroupConfiguration: undefined, NotificationTopicArn: 'arn:topic/quux', NumCacheClusters: 1, // NumNodeGroups: undefined, Port: 3333, PreferredCacheClusterAZs: ['eu-central-1c'], PreferredMaintenanceWindow: 'sun:23:00-mon:01:30', ReplicationGroupDescription: 'something', ReplicationGroupId: 'foo', SecurityGroupIds: ['my-sec'], SnapshotName: 'foo-12345567', SnapshotRetentionLimit: 10, SnapshotWindow: '05:00-09:00', Tags: [{ Key: 'Name', Value: 'my-cluster' }], TransitEncryptionEnabled: true, }, }; beforeAll(async done => { nock.abortPendingRequests(); nock.cleanAll(); nock.disableNetConnect(); // AWSMock cannot mock waiters and listTagsForResource at the moment AWS.ElastiCache.prototype.waitFor = jest.fn().mockImplementation(() => ({ promise: jest.fn(), })); AWS.ElastiCache.prototype.listTagsForResource = jest .fn() .mockImplementation(() => ({ promise: () => ({ TagList: [{ Key: 'Name', Value: 'my-cluster' }], } as AWS.ElastiCache.TagListMessage), })); mockProcessStdout(); done(); }); afterEach(async () => { const pending = nock.pendingMocks(); if (pending.length > 0) { // eslint-disable-next-line no-console console.log(pending); throw new Error(`${pending.length} mocks are pending!`); } }); afterEach(async () => { const pending = nock.pendingMocks(); if (pending.length > 0) { // eslint-disable-next-line no-console console.log(pending); throw new Error(`${pending.length} mocks are pending!`); } }); describe('snapshot-remove-elasticache-redis', () => { let task: ListrTaskWrapper<any, any>; beforeEach(() => { task = createMockTask(); }); it('returns correct machine name', async () => { const instance = new SnapshotRemoveElasticacheRedisTrick(); expect(instance.getMachineName()).toBe( SnapshotRemoveElasticacheRedisTrick.machineName, ); }); it('returns an empty Listr if no replication groups found', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'ElastiCache', 'describeReplicationGroups', ( params: AWS.ElastiCache.Types.DescribeReplicationGroupsMessage, callback: Function, ) => { callback(null, { ReplicationGroups: [], } as AWS.ElastiCache.Types.ReplicationGroupMessage); }, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [] } as TrickContext, stateObject, { dryRun: false, }, ); expect(listr.tasks.length).toBe(0); AWSMock.restore('ElastiCache'); }); it('prepares resource tags', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'ResourceGroupsTaggingAPI', 'getResources', ( params: AWS.ResourceGroupsTaggingAPI.GetResourcesInput, callback: Function, ) => { callback(null, { ResourceTagMappingList: [ { ResourceARN: 'arn:elasticache/foo' }, { ResourceARN: 'arn:elasticache/bar' }, ], } as AWS.ResourceGroupsTaggingAPI.GetResourcesOutput); }, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const trickContext: TrickContext = {}; await instance.prepareTags(task, trickContext, {} as TrickOptionsInterface); expect(trickContext).toMatchObject({ resourceTagMappings: [ { ResourceARN: 'arn:elasticache/foo' }, { ResourceARN: 'arn:elasticache/bar' }, ], }); AWSMock.restore('ResourceGroupsTaggingAPI'); }); it('errors if required fields were not returned by AWS', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'ElastiCache', 'describeReplicationGroups', ( params: AWS.ElastiCache.Types.DescribeReplicationGroupsMessage, callback: Function, ) => { callback(null, { ReplicationGroups: [ { Status: 'available' }, { ReplicationGroupId: 'foo', Status: 'available' }, { ReplicationGroupId: 'foo', ARN: 'arn:elasticachecluster/foo' }, { ReplicationGroupId: 'foo', ARN: 'arn:elasticachecluster/foo', Status: 'available', MemberClusters: null, }, { ReplicationGroupId: 'foo', ARN: 'arn:elasticachecluster/foo', Status: 'available', MemberClusters: [], }, ], } as AWS.ElastiCache.Types.ReplicationGroupMessage); }, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [] } as TrickContext, stateObject, { dryRun: false, }, ); await listr.run(); expect(listr.err).toStrictEqual([ expect.objectContaining({ errors: [ expect.objectContaining({ message: expect.stringMatching(/ReplicationGroupId is missing/gi), }), expect.objectContaining({ message: expect.stringMatching(/ARN is missing/gi), }), expect.objectContaining({ message: expect.stringMatching(/Status is missing/gi), }), expect.objectContaining({ message: expect.stringMatching(/No member clusters/gi), }), expect.objectContaining({ message: expect.stringMatching(/No member clusters/gi), }), ], }), ]); AWSMock.restore('ElastiCache'); }); it('errors if AuthToken is enabled for Redis cluster', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'ElastiCache', 'describeReplicationGroups', ( params: AWS.ElastiCache.Types.DescribeReplicationGroupsMessage, callback: Function, ) => { callback(null, { ReplicationGroups: [ { ReplicationGroupId: 'foo', ARN: 'arn:elasticachecluster/foo', Status: 'available', AuthTokenEnabled: true, MemberClusters: ['bar'], }, ], } as AWS.ElastiCache.Types.ReplicationGroupMessage); }, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [] } as TrickContext, stateObject, { dryRun: false, }, ); await listr.run(); expect(listr.err).toStrictEqual([ expect.objectContaining({ errors: [ expect.objectContaining({ message: expect.stringMatching(/Cannot conserve an AuthToken/gi), }), ], }), ]); AWSMock.restore('ElastiCache'); }); it('errors if could not describe sample cluster', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'ElastiCache', 'describeReplicationGroups', ( params: AWS.ElastiCache.Types.DescribeReplicationGroupsMessage, callback: Function, ) => { callback(null, { ReplicationGroups: [ { ReplicationGroupId: 'foo', Status: 'available', ARN: 'arn:elasticachecluster/foo', MemberClusters: ['bar'], AtRestEncryptionEnabled: true, TransitEncryptionEnabled: true, MultiAZ: 'enabled', Description: 'something', KmsKeyId: 'secret-key-id', AutomaticFailover: 'enabled', }, ], } as AWS.ElastiCache.Types.ReplicationGroupMessage); }, ); AWSMock.mock( 'ElastiCache', 'describeCacheClusters', ( params: AWS.ElastiCache.Types.DescribeCacheClustersMessage, callback: Function, ) => { callback(null, { CacheClusters: [], } as AWS.ElastiCache.Types.CacheClusterMessage); }, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [{ ResourceARN: 'arn:elasticachecluster/foo' }], } as TrickContext, stateObject, { dryRun: false, }, ); await listr.run(); expect(listr.err).toStrictEqual([ expect.objectContaining({ errors: [ expect.objectContaining({ message: expect.stringMatching(/Could not find sample/gi), }), ], }), ]); AWSMock.restore('ElastiCache'); }); it('generates state object for ElastiCache redis clusters', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'ElastiCache', 'describeReplicationGroups', ( params: AWS.ElastiCache.Types.DescribeReplicationGroupsMessage, callback: Function, ) => { callback(null, { ReplicationGroups: [ { ReplicationGroupId: 'foo', Status: 'available', ARN: 'arn:elasticache:replicationgroup/foo', MemberClusters: ['bar'], AtRestEncryptionEnabled: true, TransitEncryptionEnabled: true, MultiAZ: 'enabled', Description: 'something', KmsKeyId: 'secret-key-id', AutomaticFailover: 'enabled', NodeGroups: [{ NodeGroupId: 'qux', Slots: '0-50000' }], }, ], } as AWS.ElastiCache.Types.ReplicationGroupMessage); }, ); AWSMock.mock( 'ElastiCache', 'describeCacheClusters', ( params: AWS.ElastiCache.Types.DescribeCacheClustersMessage, callback: Function, ) => { callback(null, { CacheClusters: [ { ARN: 'arn:elasticache:cluster/bar', AutoMinorVersionUpgrade: true, CacheNodeType: 'cache.t2.small', SnapshotRetentionLimit: 10, Engine: 'redis', EngineVersion: '5.0.6', CacheParameterGroup: { CacheParameterGroupName: 'baz' }, CacheSubnetGroupName: 'qux', CacheSecurityGroups: [{ CacheSecurityGroupName: 'quuz' }], SecurityGroups: [{ SecurityGroupId: 'my-sec' }], NotificationConfiguration: { TopicArn: 'arn:topic/quux' }, SnapshotWindow: '05:00-09:00', PreferredMaintenanceWindow: 'sun:23:00-mon:01:30', PreferredAvailabilityZone: 'eu-central-1c', CacheNodes: [{ Endpoint: { Port: 3333 } }], }, ], } as AWS.ElastiCache.Types.CacheClusterMessage); }, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [{ ResourceARN: 'arn:elasticache:cluster/bar' }], } as TrickContext, stateObject, { dryRun: false, }, ); await listr.run({}); expect(stateObject.pop()).toStrictEqual( expect.objectContaining({ id: 'foo', snapshotName: expect.any(String), status: 'available', createParams: { AtRestEncryptionEnabled: true, AutoMinorVersionUpgrade: true, AutomaticFailoverEnabled: true, CacheNodeType: 'cache.t2.small', CacheParameterGroupName: 'baz', CacheSecurityGroupNames: ['quuz'], CacheSubnetGroupName: 'qux', Engine: 'redis', EngineVersion: '5.0.6', // GlobalReplicationGroupId: undefined, KmsKeyId: 'secret-key-id', MultiAZEnabled: true, // NodeGroupConfiguration: undefined, NotificationTopicArn: 'arn:topic/quux', NumCacheClusters: 1, // NumNodeGroups: undefined, Port: 3333, PreferredCacheClusterAZs: ['eu-central-1c'], PreferredMaintenanceWindow: 'sun:23:00-mon:01:30', ReplicationGroupDescription: 'something', ReplicationGroupId: 'foo', SecurityGroupIds: ['my-sec'], SnapshotName: expect.any(String), SnapshotRetentionLimit: 10, SnapshotWindow: '05:00-09:00', Tags: [{ Key: 'Name', Value: 'my-cluster' }], TransitEncryptionEnabled: true, }, } as ElasticacheReplicationGroupState), ); AWSMock.restore('ElastiCache'); }); it('generates state object for tagged resources', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'ElastiCache', 'describeReplicationGroups', ( params: AWS.ElastiCache.Types.DescribeReplicationGroupsMessage, callback: Function, ) => { callback(null, { ReplicationGroups: [ { ReplicationGroupId: 'foo', Status: 'available', ARN: 'arn:elasticachecluster/foo', MemberClusters: ['foo-member'], AtRestEncryptionEnabled: true, TransitEncryptionEnabled: true, MultiAZ: 'enabled', Description: 'something', KmsKeyId: 'secret-key-id', AutomaticFailover: 'enabled', NodeGroups: [{ NodeGroupId: 'qux', Slots: '0-50000' }], }, { ReplicationGroupId: 'bar', Status: 'available', ARN: 'arn:elasticachecluster/bar', MemberClusters: ['bar-member'], AtRestEncryptionEnabled: true, TransitEncryptionEnabled: true, MultiAZ: 'enabled', Description: 'something', KmsKeyId: 'secret-key-id', AutomaticFailover: 'enabled', NodeGroups: [{ NodeGroupId: 'qux', Slots: '0-50000' }], }, ], } as AWS.ElastiCache.Types.ReplicationGroupMessage); }, ); AWSMock.mock( 'ElastiCache', 'describeCacheClusters', ( params: AWS.ElastiCache.Types.DescribeCacheClustersMessage, callback: Function, ) => { callback(null, { CacheClusters: [ { ARN: `arn:elasticachecluster/${params.CacheClusterId}`, AutoMinorVersionUpgrade: true, CacheNodeType: 'cache.t2.small', SnapshotRetentionLimit: 10, Engine: 'redis', EngineVersion: '5.0.6', CacheParameterGroup: { CacheParameterGroupName: 'baz' }, CacheSubnetGroupName: 'qux', CacheSecurityGroups: [{ CacheSecurityGroupName: 'quuz' }], SecurityGroups: [{ SecurityGroupId: 'my-sec' }], NotificationConfiguration: { TopicArn: 'arn:topic/quux' }, SnapshotWindow: '05:00-09:00', PreferredMaintenanceWindow: 'sun:23:00-mon:01:30', PreferredAvailabilityZone: 'eu-central-1c', CacheNodes: [{ Endpoint: { Port: 3333 } }], }, ], } as AWS.ElastiCache.Types.CacheClusterMessage); }, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [ { ResourceARN: 'arn:elasticachecluster/bar-member' }, ], } as TrickContext, stateObject, { dryRun: false, }, ); await listr.run({}); expect(stateObject.length).toBe(1); expect(stateObject.pop()).toStrictEqual( expect.objectContaining({ id: 'bar', } as ElasticacheReplicationGroupState), ); AWSMock.restore('ElastiCache'); }); it('generates state object for ElastiCache redis clusters without PreferredAvailabilityZone', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'ElastiCache', 'describeReplicationGroups', ( params: AWS.ElastiCache.Types.DescribeReplicationGroupsMessage, callback: Function, ) => { callback(null, { ReplicationGroups: [ { ReplicationGroupId: 'foo', Status: 'available', ARN: 'arn:elasticache:replicationgroup/foo', MemberClusters: ['bar'], AtRestEncryptionEnabled: true, TransitEncryptionEnabled: true, MultiAZ: 'enabled', Description: 'something', KmsKeyId: 'secret-key-id', AutomaticFailover: 'enabled', NodeGroups: [{ NodeGroupId: 'qux', Slots: '0-50000' }], }, ], } as AWS.ElastiCache.Types.ReplicationGroupMessage); }, ); AWSMock.mock( 'ElastiCache', 'describeCacheClusters', ( params: AWS.ElastiCache.Types.DescribeCacheClustersMessage, callback: Function, ) => { callback(null, { CacheClusters: [ { ARN: 'arn:elasticache:cluster/bar', AutoMinorVersionUpgrade: true, CacheNodeType: 'cache.t2.small', SnapshotRetentionLimit: 10, Engine: 'redis', EngineVersion: '5.0.6', CacheParameterGroup: { CacheParameterGroupName: 'baz' }, CacheSubnetGroupName: 'qux', CacheSecurityGroups: [{ CacheSecurityGroupName: 'quuz' }], SecurityGroups: [{ SecurityGroupId: 'my-sec' }], NotificationConfiguration: { TopicArn: 'arn:topic/quux' }, SnapshotWindow: '05:00-09:00', PreferredMaintenanceWindow: 'sun:23:00-mon:01:30', // PreferredAvailabilityZone: 'eu-central-1c', CacheNodes: [{ Endpoint: { Port: 3333 } }], }, ], } as AWS.ElastiCache.Types.CacheClusterMessage); }, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [{ ResourceARN: 'arn:elasticache:cluster/bar' }], } as TrickContext, stateObject, { dryRun: false, }, ); await listr.run({}); expect(stateObject.pop()).toStrictEqual( expect.objectContaining({ id: 'foo', snapshotName: expect.any(String), status: 'available', createParams: { AtRestEncryptionEnabled: true, AutoMinorVersionUpgrade: true, AutomaticFailoverEnabled: true, CacheNodeType: 'cache.t2.small', CacheParameterGroupName: 'baz', CacheSecurityGroupNames: ['quuz'], CacheSubnetGroupName: 'qux', Engine: 'redis', EngineVersion: '5.0.6', // GlobalReplicationGroupId: undefined, KmsKeyId: 'secret-key-id', MultiAZEnabled: true, // NodeGroupConfiguration: undefined, NotificationTopicArn: 'arn:topic/quux', NumCacheClusters: 1, // NumNodeGroups: undefined, Port: 3333, // PreferredCacheClusterAZs: ['eu-central-1c'], PreferredMaintenanceWindow: 'sun:23:00-mon:01:30', ReplicationGroupDescription: 'something', ReplicationGroupId: 'foo', SecurityGroupIds: ['my-sec'], SnapshotName: expect.any(String), SnapshotRetentionLimit: 10, SnapshotWindow: '05:00-09:00', Tags: [{ Key: 'Name', Value: 'my-cluster' }], TransitEncryptionEnabled: true, }, } as ElasticacheReplicationGroupState), ); AWSMock.restore('ElastiCache'); }); it('generates state object for ElastiCache redis clusters without description', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'ElastiCache', 'describeReplicationGroups', ( params: AWS.ElastiCache.Types.DescribeReplicationGroupsMessage, callback: Function, ) => { callback(null, { ReplicationGroups: [ { ReplicationGroupId: 'foo', Status: 'available', ARN: 'arn:elasticache:replicationgroup/foo', MemberClusters: ['bar'], AtRestEncryptionEnabled: true, TransitEncryptionEnabled: true, MultiAZ: 'enabled', KmsKeyId: 'secret-key-id', AutomaticFailover: 'enabled', NodeGroups: [{ NodeGroupId: 'qux', Slots: '0-50000' }], }, ], } as AWS.ElastiCache.Types.ReplicationGroupMessage); }, ); AWSMock.mock( 'ElastiCache', 'describeCacheClusters', ( params: AWS.ElastiCache.Types.DescribeCacheClustersMessage, callback: Function, ) => { callback(null, { CacheClusters: [ { ARN: 'arn:elasticache:cluster/bar', AutoMinorVersionUpgrade: true, CacheNodeType: 'cache.t2.small', SnapshotRetentionLimit: 10, Engine: 'redis', EngineVersion: '5.0.6', CacheParameterGroup: { CacheParameterGroupName: 'baz' }, CacheSubnetGroupName: 'qux', CacheSecurityGroups: [{ CacheSecurityGroupName: 'quuz' }], SecurityGroups: [{ SecurityGroupId: 'my-sec' }], NotificationConfiguration: { TopicArn: 'arn:topic/quux' }, SnapshotWindow: '05:00-09:00', PreferredMaintenanceWindow: 'sun:23:00-mon:01:30', PreferredAvailabilityZone: 'eu-central-1c', CacheNodes: [{ Endpoint: { Port: 3333 } }], }, ], } as AWS.ElastiCache.Types.CacheClusterMessage); }, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [{ ResourceARN: 'arn:elasticache:cluster/bar' }], } as TrickContext, stateObject, { dryRun: false, }, ); await listr.run({}); expect(stateObject.pop()).toStrictEqual( expect.objectContaining({ id: 'foo', snapshotName: expect.any(String), status: 'available', createParams: { AtRestEncryptionEnabled: true, AutoMinorVersionUpgrade: true, AutomaticFailoverEnabled: true, CacheNodeType: 'cache.t2.small', CacheParameterGroupName: 'baz', CacheSecurityGroupNames: ['quuz'], CacheSubnetGroupName: 'qux', Engine: 'redis', EngineVersion: '5.0.6', // GlobalReplicationGroupId: undefined, KmsKeyId: 'secret-key-id', MultiAZEnabled: true, // NodeGroupConfiguration: undefined, NotificationTopicArn: 'arn:topic/quux', NumCacheClusters: 1, // NumNodeGroups: undefined, Port: 3333, PreferredCacheClusterAZs: ['eu-central-1c'], PreferredMaintenanceWindow: 'sun:23:00-mon:01:30', ReplicationGroupDescription: expect.any(String), ReplicationGroupId: 'foo', SecurityGroupIds: ['my-sec'], SnapshotName: expect.any(String), SnapshotRetentionLimit: 10, SnapshotWindow: '05:00-09:00', Tags: [{ Key: 'Name', Value: 'my-cluster' }], TransitEncryptionEnabled: true, }, } as ElasticacheReplicationGroupState), ); AWSMock.restore('ElastiCache'); }); it('generates state object for ElastiCache redis clusters with multiple NodeGroups', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'ElastiCache', 'describeReplicationGroups', ( params: AWS.ElastiCache.Types.DescribeReplicationGroupsMessage, callback: Function, ) => { callback(null, { ReplicationGroups: [ { ReplicationGroupId: 'foo', Status: 'available', ARN: 'arn:elasticache:replicationgroup/foo', MemberClusters: ['bar'], AtRestEncryptionEnabled: true, TransitEncryptionEnabled: true, MultiAZ: 'enabled', Description: 'something', KmsKeyId: 'secret-key-id', AutomaticFailover: 'enabled', NodeGroups: [ { NodeGroupId: 'qux', Slots: '0-1000' }, { NodeGroupId: 'quuz', Slots: '1000-50000' }, ], }, ], } as AWS.ElastiCache.Types.ReplicationGroupMessage); }, ); AWSMock.mock( 'ElastiCache', 'describeCacheClusters', ( params: AWS.ElastiCache.Types.DescribeCacheClustersMessage, callback: Function, ) => { callback(null, { CacheClusters: [ { ARN: 'arn:elasticache:cluster/bar', AutoMinorVersionUpgrade: true, CacheNodeType: 'cache.t2.small', SnapshotRetentionLimit: 10, Engine: 'redis', EngineVersion: '5.0.6', CacheParameterGroup: { CacheParameterGroupName: 'baz' }, CacheSubnetGroupName: 'qux', CacheSecurityGroups: [{ CacheSecurityGroupName: 'quuz' }], SecurityGroups: [{ SecurityGroupId: 'my-sec' }], NotificationConfiguration: { TopicArn: 'arn:topic/quux' }, SnapshotWindow: '05:00-09:00', PreferredMaintenanceWindow: 'sun:23:00-mon:01:30', PreferredAvailabilityZone: 'eu-central-1c', CacheNodes: [{ Endpoint: { Port: 3333 } }], }, ], } as AWS.ElastiCache.Types.CacheClusterMessage); }, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [{ ResourceARN: 'arn:elasticache:cluster/bar' }], } as TrickContext, stateObject, { dryRun: false, }, ); await listr.run({}); expect(stateObject).toStrictEqual([ { id: 'foo', snapshotName: expect.any(String), status: 'available', createParams: { AtRestEncryptionEnabled: true, AutoMinorVersionUpgrade: true, AutomaticFailoverEnabled: true, CacheNodeType: 'cache.t2.small', CacheParameterGroupName: 'baz', CacheSecurityGroupNames: ['quuz'], CacheSubnetGroupName: 'qux', Engine: 'redis', EngineVersion: '5.0.6', GlobalReplicationGroupId: undefined, KmsKeyId: 'secret-key-id', MultiAZEnabled: true, NodeGroupConfiguration: [ { NodeGroupId: 'qux', ReplicaCount: undefined, Slots: '0-1000', }, { NodeGroupId: 'quuz', ReplicaCount: undefined, Slots: '1000-50000', }, ], NotificationTopicArn: 'arn:topic/quux', NumCacheClusters: undefined, NumNodeGroups: 2, Port: 3333, PreferredCacheClusterAZs: undefined, PreferredMaintenanceWindow: 'sun:23:00-mon:01:30', ReplicationGroupDescription: 'something', ReplicationGroupId: 'foo', SecurityGroupIds: ['my-sec'], SnapshotName: expect.any(String), SnapshotRetentionLimit: 10, SnapshotWindow: '05:00-09:00', Tags: [{ Key: 'Name', Value: 'my-cluster' }], TransitEncryptionEnabled: true, }, } as ElasticacheReplicationGroupState, ]); AWSMock.restore('ElastiCache'); }); it('generates state object for ElastiCache redis clusters without NodeGroups', async () => { AWSMock.setSDKInstance(AWS); AWSMock.mock( 'ElastiCache', 'describeReplicationGroups', ( params: AWS.ElastiCache.Types.DescribeReplicationGroupsMessage, callback: Function, ) => { callback(null, { ReplicationGroups: [ { ARN: 'arn:elasticache:replicationgroup/foo', ReplicationGroupId: 'foo', Status: 'available', MemberClusters: ['bar'], AtRestEncryptionEnabled: true, TransitEncryptionEnabled: true, MultiAZ: 'enabled', Description: 'something', KmsKeyId: 'secret-key-id', AutomaticFailover: 'enabled', NodeGroups: undefined, }, ], } as AWS.ElastiCache.Types.ReplicationGroupMessage); }, ); AWSMock.mock( 'ElastiCache', 'describeCacheClusters', ( params: AWS.ElastiCache.Types.DescribeCacheClustersMessage, callback: Function, ) => { callback(null, { CacheClusters: [ { ARN: 'arn:elasticache:cluster/bar', AutoMinorVersionUpgrade: true, CacheNodeType: 'cache.t2.small', SnapshotRetentionLimit: 10, Engine: 'redis', EngineVersion: '5.0.6', CacheParameterGroup: { CacheParameterGroupName: 'baz' }, CacheSubnetGroupName: 'qux', CacheSecurityGroups: [{ CacheSecurityGroupName: 'quuz' }], SecurityGroups: [{ SecurityGroupId: 'my-sec' }], NotificationConfiguration: { TopicArn: 'arn:topic/quux' }, SnapshotWindow: '05:00-09:00', PreferredMaintenanceWindow: 'sun:23:00-mon:01:30', PreferredAvailabilityZone: 'eu-central-1c', CacheNodes: [{ Endpoint: { Port: 3333 } }], }, ], } as AWS.ElastiCache.Types.CacheClusterMessage); }, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = []; const listr = await instance.getCurrentState( task, { resourceTagMappings: [{ ResourceARN: 'arn:elasticache:cluster/bar' }], } as TrickContext, stateObject, { dryRun: false, }, ); await listr.run({}); expect(stateObject).toStrictEqual([ { id: 'foo', snapshotName: expect.any(String), status: 'available', createParams: { AtRestEncryptionEnabled: true, AutoMinorVersionUpgrade: true, AutomaticFailoverEnabled: true, CacheNodeType: 'cache.t2.small', CacheParameterGroupName: 'baz', CacheSecurityGroupNames: ['quuz'], CacheSubnetGroupName: 'qux', Engine: 'redis', EngineVersion: '5.0.6', GlobalReplicationGroupId: undefined, KmsKeyId: 'secret-key-id', MultiAZEnabled: true, NodeGroupConfiguration: undefined, NotificationTopicArn: 'arn:topic/quux', NumCacheClusters: 1, NumNodeGroups: undefined, Port: 3333, PreferredCacheClusterAZs: ['eu-central-1c'], PreferredMaintenanceWindow: 'sun:23:00-mon:01:30', ReplicationGroupDescription: 'something', ReplicationGroupId: 'foo', SecurityGroupIds: ['my-sec'], SnapshotName: expect.any(String), SnapshotRetentionLimit: 10, SnapshotWindow: '05:00-09:00', Tags: [{ Key: 'Name', Value: 'my-cluster' }], TransitEncryptionEnabled: true, }, } as ElasticacheReplicationGroupState, ]); AWSMock.restore('ElastiCache'); }); it('conserves ElastiCache redis cluster', async () => { AWSMock.setSDKInstance(AWS); const deleteReplicationGroupSpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, {}); }); AWSMock.mock( 'ElastiCache', 'deleteReplicationGroup', deleteReplicationGroupSpy, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = [ SampleReplicationGroupState, ]; const conserveListr = await instance.conserve(task, stateObject, { dryRun: false, }); await conserveListr.run({}); expect(deleteReplicationGroupSpy).toBeCalledWith( expect.objectContaining({ ReplicationGroupId: SampleReplicationGroupState.id, FinalSnapshotIdentifier: SampleReplicationGroupState.snapshotName, }), expect.anything(), ); AWSMock.restore('ElastiCache'); }); it('skips conserve if no clusters found', async () => { AWSMock.setSDKInstance(AWS); const deleteReplicationGroupSpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, {}); }); AWSMock.mock( 'ElastiCache', 'deleteReplicationGroup', deleteReplicationGroupSpy, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = []; const conserveListr = await instance.conserve(task, stateObject, { dryRun: false, }); await conserveListr.run({}); expect(deleteReplicationGroupSpy).not.toBeCalled(); AWSMock.restore('ElastiCache'); }); it('skips conserve if status is not "available"', async () => { AWSMock.setSDKInstance(AWS); const deleteReplicationGroupSpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, {}); }); AWSMock.mock( 'ElastiCache', 'deleteReplicationGroup', deleteReplicationGroupSpy, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = [ { ...SampleReplicationGroupState, status: 'pending', }, ]; const conserveListr = await instance.conserve(task, stateObject, { dryRun: false, }); await conserveListr.run({}); expect(deleteReplicationGroupSpy).not.toBeCalled(); AWSMock.restore('ElastiCache'); }); it('skips conserve if dry-run option is enabled', async () => { AWSMock.setSDKInstance(AWS); const deleteReplicationGroupSpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, {}); }); AWSMock.mock( 'ElastiCache', 'deleteReplicationGroup', deleteReplicationGroupSpy, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = [ SampleReplicationGroupState, ]; const conserveListr = await instance.conserve(task, stateObject, { dryRun: true, }); await conserveListr.run({}); expect(deleteReplicationGroupSpy).not.toBeCalled(); AWSMock.restore('ElastiCache'); }); it('restores removed ElastiCache Redis cluster', async () => { AWSMock.setSDKInstance(AWS); const createReplicationGroupSpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, { ReplicationGroup: { ReplicationGroupId: 'newfoo', }, } as AWS.ElastiCache.CreateReplicationGroupResult); }); AWSMock.mock( 'ElastiCache', 'createReplicationGroup', createReplicationGroupSpy, ); const describeReplicationGroupsSpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, { ReplicationGroups: [], } as AWS.ElastiCache.ReplicationGroupMessage); }); AWSMock.mock( 'ElastiCache', 'describeReplicationGroups', describeReplicationGroupsSpy, ); const deleteSnapshotSpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, {}); }); AWSMock.mock('ElastiCache', 'deleteSnapshot', deleteSnapshotSpy); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = [ SampleReplicationGroupState, ]; const restoreListr = await instance.restore(task, stateObject, { dryRun: false, }); await restoreListr.run({}); expect(createReplicationGroupSpy).toBeCalledWith( expect.objectContaining(SampleReplicationGroupState.createParams), expect.anything(), ); expect(deleteSnapshotSpy).toBeCalledWith( expect.objectContaining({ SnapshotName: SampleReplicationGroupState.snapshotName, }), expect.anything(), ); AWSMock.restore('ElastiCache'); }); it('skips restore if ElastiCache Redis cluster already exists', async () => { AWSMock.setSDKInstance(AWS); const createReplicationGroupSpy = jest.fn(); AWSMock.mock( 'ElastiCache', 'createReplicationGroup', createReplicationGroupSpy, ); const describeReplicationGroupsSpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, { ReplicationGroups: [ { ReplicationGroupId: SampleReplicationGroupState.id, Status: 'available', }, ], } as AWS.ElastiCache.ReplicationGroupMessage); }); AWSMock.mock( 'ElastiCache', 'describeReplicationGroups', describeReplicationGroupsSpy, ); const deleteSnapshotSpy = jest.fn(); AWSMock.mock('ElastiCache', 'deleteSnapshot', deleteSnapshotSpy); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = [ SampleReplicationGroupState, ]; const restoreListr = await instance.restore(task, stateObject, { dryRun: false, }); await restoreListr.run({}); expect(createReplicationGroupSpy).not.toBeCalled(); expect(deleteSnapshotSpy).not.toBeCalled(); AWSMock.restore('ElastiCache'); }); it('skips restore if status was not "available"', async () => { AWSMock.setSDKInstance(AWS); const createReplicationGroupSpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, {}); }); AWSMock.mock( 'ElastiCache', 'createReplicationGroup', createReplicationGroupSpy, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = [ { ...SampleReplicationGroupState, status: 'pending' }, ]; const restoreListr = await instance.restore(task, stateObject, { dryRun: false, }); await restoreListr.run({}); expect(createReplicationGroupSpy).not.toBeCalled(); AWSMock.restore('ElastiCache'); }); it('skips restore if no clusters were conserved', async () => { AWSMock.setSDKInstance(AWS); const createReplicationGroupSpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, {}); }); AWSMock.mock( 'ElastiCache', 'createReplicationGroup', createReplicationGroupSpy, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = []; const restoreListr = await instance.restore(task, stateObject, { dryRun: false, }); await restoreListr.run({}); expect(createReplicationGroupSpy).not.toBeCalled(); AWSMock.restore('ElastiCache'); }); it('skips restore if dry-run option is enabled', async () => { AWSMock.setSDKInstance(AWS); const createReplicationGroupSpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, {}); }); AWSMock.mock( 'ElastiCache', 'createReplicationGroup', createReplicationGroupSpy, ); const describeReplicationGroupsSpy = jest .fn() .mockImplementationOnce((params, callback) => { callback(null, { ReplicationGroups: [], } as AWS.ElastiCache.ReplicationGroupMessage); }); AWSMock.mock( 'ElastiCache', 'describeReplicationGroups', describeReplicationGroupsSpy, ); const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject: SnapshotRemoveElasticacheRedisState = [ SampleReplicationGroupState, ]; const restoreListr = await instance.restore(task, stateObject, { dryRun: true, }); await restoreListr.run({}); expect(createReplicationGroupSpy).not.toBeCalled(); AWSMock.restore('ElastiCache'); }); it('errors on restore if required fields are missing in state', async () => { const instance = new SnapshotRemoveElasticacheRedisTrick(); const stateObject = ([ { id: 'foo', createParams: SampleReplicationGroupState.createParams, }, { id: 'foo', snapshotName: SampleReplicationGroupState.snapshotName, }, ] as unknown) as SnapshotRemoveElasticacheRedisState; const listr = await instance.restore(task, stateObject, { dryRun: false, }); await listr.run(); expect(listr.err).toStrictEqual([ expect.objectContaining({ errors: [ expect.objectContaining({ message: expect.stringMatching(/snapshotName is missing/gi), }), expect.objectContaining({ message: expect.stringMatching(/createParams is missing/gi), }), ], }), ]); }); });
the_stack
const params : {[index: string]: any} = { '2048': { publicKey:{ jwk: { e: 'AQAB', kty: 'RSA', n: 'scsBr8BRbrcyZIKFT9i_ev6pPYLoGkZhie4vis1JnlEgkpKmgzDDzdqE5HmHxK5QXcKeTAZWuEsQFMmDJOYfkcINMYtopiLTYFo6YLvs6MyZt_lm5CUPnURi1wu3ni5gZ2EbhDECyvUxZHWswJKF19kZ-haa5cE5otHzMUENeodhaVnsKiWJLYH2EyWRhYZbid_62g_j3kXiUDXQvbP2DmpvFHQaFUsmZVJmPDS0HyKgO2Q-uskH62Is--0EUTlkcjHBXCxR2Ai_m8B7H0k6zXMxB8FT7BvpjCc-j1rdUlC90KKclbNi5n_XObhkHlmGmP9pPrUuIsZghDMHEGQFrQ' }, pem: '-----BEGIN PUBLIC KEY-----\n' + 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAscsBr8BRbrcyZIKFT9i/\n' + 'ev6pPYLoGkZhie4vis1JnlEgkpKmgzDDzdqE5HmHxK5QXcKeTAZWuEsQFMmDJOYf\n' + 'kcINMYtopiLTYFo6YLvs6MyZt/lm5CUPnURi1wu3ni5gZ2EbhDECyvUxZHWswJKF\n' + '19kZ+haa5cE5otHzMUENeodhaVnsKiWJLYH2EyWRhYZbid/62g/j3kXiUDXQvbP2\n' + 'DmpvFHQaFUsmZVJmPDS0HyKgO2Q+uskH62Is++0EUTlkcjHBXCxR2Ai/m8B7H0k6\n' + 'zXMxB8FT7BvpjCc+j1rdUlC90KKclbNi5n/XObhkHlmGmP9pPrUuIsZghDMHEGQF\n' + 'rQIDAQAB\n' + '-----END PUBLIC KEY-----' }, privateKey:{ jwk: { d: 'RrkXvycz3WQ_Re8Lg6MXLCBgBwlrNYR4qUrXm5Gkrrbby6JNXVNJGDpL8ayMPscOTfWsTVaaKW4mg_ZS1hs6RJtZ7zLi2m9xANtzbGZky4gTv7SUYr2BVBBPdvaAwIn3LDhbHz71uvFFCA6tPN8sIZwJMsvKKwmtWSDF6fpUF8BXvQ6RqDRjHuNFvs5ZtuaAT89Fj_f76-CjDwJb6fJeT0FYgVhd_-xaizptfDY662HPoGa8kJ4n8cSGsseJVxEt_KApagEu8r8Ttwj_bPebHxcf8nlKCh9n2o5E-tqTlNYOyeEaUGhtGrfw28ZG7vfbaYTI38KqgGAtwdMRppvT2w', dp: 'gsGanIB8kc6VO55NKb5FBj3c1Y4nr7HZbg-iSL6mVQ3_cP5NBkyZ3VNq_SxoMv_Tnara5tmNb37iewB5lknHN2gFCflSbmGuy5J4ricLXhwaIPQjQLocZx5wsasQAt2Er7UGvCwXz8q8_nROZH0sWxQaGVAfm7IdeFBghn5XGOM', dq: 'sRjeLtWa7hRhH5HgqonFmSRH_T0ILRxSCg7ER_SWQ0GjTbTYR2MJqcQK4LsGN7N2MScpXTalENF6XJxSlvXVGsw3vmG7gdYVMT1dZ5jeylMSxROheSQoh1NrumMPffDDU8BLvlYt_MLQsAzsGVD6iH-IfIdjWXggdwKIlVMIb40', e: 'AQAB', kty: 'RSA', n: 'scsBr8BRbrcyZIKFT9i_ev6pPYLoGkZhie4vis1JnlEgkpKmgzDDzdqE5HmHxK5QXcKeTAZWuEsQFMmDJOYfkcINMYtopiLTYFo6YLvs6MyZt_lm5CUPnURi1wu3ni5gZ2EbhDECyvUxZHWswJKF19kZ-haa5cE5otHzMUENeodhaVnsKiWJLYH2EyWRhYZbid_62g_j3kXiUDXQvbP2DmpvFHQaFUsmZVJmPDS0HyKgO2Q-uskH62Is--0EUTlkcjHBXCxR2Ai_m8B7H0k6zXMxB8FT7BvpjCc-j1rdUlC90KKclbNi5n_XObhkHlmGmP9pPrUuIsZghDMHEGQFrQ', p: '3Wb4o6CvKEtXg06qw5N-XctVCLekmtw35u0ecoX034HHeA0piLtCqdHZQiF2ntvAg6M4gKk-iyZ2BZaxlM6irQHmtR-w5JyT2O6c9R4wujKSv4VE_2uc4CHPac3-usetfXzv8TP6-PWncdTJ8q0ft2gD2HZR15KVYFw7punR8oM', q: 'zZN7FoQ_Y4HxDfhmyVFbFw1TuE69os_6OZb-xRpRfZLcYmC3raKUQjDmuqRpGa5ap0TeteZYj_fHsWL7KcNim1D8YA_u5P3YqC5s7_xmx-aFnmVBIDEyNgNL9V2yd539yiFaMzXljQfjI2cDDFRIoPXf7vNGrRnKgktb5HKU8A8', qi: 'mgemyFmEO_RUbyQE1l7tG5vvvj0-XORmJexkINhAgtHJPkpNa55JCQdyQRgmN-ERU0Ml22zimw6PS0OD1uCgqLgLkb67Nj2oD_la8vgk7Cg9IRcvFcNuyNROA92VrnF5i1oMeYF5O-3NUF6BlEBBhTt5KdOQFJOu8jIX6Vt77vo' }, pem: '-----BEGIN PRIVATE KEY-----\n' + 'MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCxywGvwFFutzJk\n' + 'goVP2L96/qk9gugaRmGJ7i+KzUmeUSCSkqaDMMPN2oTkeYfErlBdwp5MBla4SxAU\n' + 'yYMk5h+Rwg0xi2imItNgWjpgu+zozJm3+WbkJQ+dRGLXC7eeLmBnYRuEMQLK9TFk\n' + 'dazAkoXX2Rn6FprlwTmi0fMxQQ16h2FpWewqJYktgfYTJZGFhluJ3/raD+PeReJQ\n' + 'NdC9s/YOam8UdBoVSyZlUmY8NLQfIqA7ZD66yQfrYiz77QRROWRyMcFcLFHYCL+b\n' + 'wHsfSTrNczEHwVPsG+mMJz6PWt1SUL3QopyVs2Lmf9c5uGQeWYaY/2k+tS4ixmCE\n' + 'MwcQZAWtAgMBAAECggEARrkXvycz3WQ/Re8Lg6MXLCBgBwlrNYR4qUrXm5Gkrrbb\n' + 'y6JNXVNJGDpL8ayMPscOTfWsTVaaKW4mg/ZS1hs6RJtZ7zLi2m9xANtzbGZky4gT\n' + 'v7SUYr2BVBBPdvaAwIn3LDhbHz71uvFFCA6tPN8sIZwJMsvKKwmtWSDF6fpUF8BX\n' + 'vQ6RqDRjHuNFvs5ZtuaAT89Fj/f76+CjDwJb6fJeT0FYgVhd/+xaizptfDY662HP\n' + 'oGa8kJ4n8cSGsseJVxEt/KApagEu8r8Ttwj/bPebHxcf8nlKCh9n2o5E+tqTlNYO\n' + 'yeEaUGhtGrfw28ZG7vfbaYTI38KqgGAtwdMRppvT2wKBgQDdZvijoK8oS1eDTqrD\n' + 'k35dy1UIt6Sa3Dfm7R5yhfTfgcd4DSmIu0Kp0dlCIXae28CDoziAqT6LJnYFlrGU\n' + 'zqKtAea1H7DknJPY7pz1HjC6MpK/hUT/a5zgIc9pzf66x619fO/xM/r49adx1Mny\n' + 'rR+3aAPYdlHXkpVgXDum6dHygwKBgQDNk3sWhD9jgfEN+GbJUVsXDVO4Tr2iz/o5\n' + 'lv7FGlF9ktxiYLetopRCMOa6pGkZrlqnRN615liP98exYvspw2KbUPxgD+7k/dio\n' + 'Lmzv/GbH5oWeZUEgMTI2A0v1XbJ3nf3KIVozNeWNB+MjZwMMVEig9d/u80atGcqC\n' + 'S1vkcpTwDwKBgQCCwZqcgHyRzpU7nk0pvkUGPdzVjievsdluD6JIvqZVDf9w/k0G\n' + 'TJndU2r9LGgy/9Odqtrm2Y1vfuJ7AHmWScc3aAUJ+VJuYa7LkniuJwteHBog9CNA\n' + 'uhxnHnCxqxAC3YSvtQa8LBfPyrz+dE5kfSxbFBoZUB+bsh14UGCGflcY4wKBgQCx\n' + 'GN4u1ZruFGEfkeCqicWZJEf9PQgtHFIKDsRH9JZDQaNNtNhHYwmpxArguwY3s3Yx\n' + 'JyldNqUQ0XpcnFKW9dUazDe+YbuB1hUxPV1nmN7KUxLFE6F5JCiHU2u6Yw998MNT\n' + 'wEu+Vi38wtCwDOwZUPqIf4h8h2NZeCB3AoiVUwhvjQKBgQCaB6bIWYQ79FRvJATW\n' + 'Xu0bm+++PT5c5GYl7GQg2ECC0ck+Sk1rnkkJB3JBGCY34RFTQyXbbOKbDo9LQ4PW\n' + '4KCouAuRvrs2PagP+Vry+CTsKD0hFy8Vw27I1E4D3ZWucXmLWgx5gXk77c1QXoGU\n' + 'QEGFO3kp05AUk67yMhfpW3vu+g==\n' + '-----END PRIVATE KEY-----' } }, // '3072': { // publicKey: { // jwk: { // e: 'AQAB', // kty: 'RSA', // n: 'jp8P2mZy0A3QQ8QL1hW6mRMCGiHyOpTssmJlQ-LDXWsWxw7SwW9CpKPLlBs-5YJ7kq7h5gcMlZz44hqhwAWvTGJr_iy5w8HsfFSU8t8YURug4KvZywf7wILBZXmLnOElemvg9hzRHEEQ-3W4MmDQrxpxphYutAEkB_xh_sSdmnSaPnTxWyXilIoiW5-oJtNt50w-rT6C2xo4phHYkIqYfBT7eaeMSIvB68bxyOf8j-ZLFaPmyF6Fre7Bh4v3UOvnLk0l8yk1UPndvOJAmJQTiLD-iTterj4y3kZKM4J8wG-rqZfE41i3PiqIIQBC79CgIB3Ck9YoGiI8utPoDpFbpzEwo8xexO-5e8nNrSozKsilTsTwF9bMg1Oknp3LglrS33KFRf84TU8T8EIeRt7iEOAzdVb48eJZi001bMHtOUPVa7Ncrby3yrb6G-uwxbKJd0wpNO1b0UdSFMnU--nVn5Li0TT0zqwufG_HiyE5HZhfG_CDuyCdKJDKI2EeDqq9' // }, // pem: '-----BEGIN PUBLIC KEY-----\n' + // 'MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAjp8P2mZy0A3QQ8QL1hW6\n' + // 'mRMCGiHyOpTssmJlQ+LDXWsWxw7SwW9CpKPLlBs+5YJ7kq7h5gcMlZz44hqhwAWv\n' + // 'TGJr/iy5w8HsfFSU8t8YURug4KvZywf7wILBZXmLnOElemvg9hzRHEEQ+3W4MmDQ\n' + // 'rxpxphYutAEkB/xh/sSdmnSaPnTxWyXilIoiW5+oJtNt50w+rT6C2xo4phHYkIqY\n' + // 'fBT7eaeMSIvB68bxyOf8j+ZLFaPmyF6Fre7Bh4v3UOvnLk0l8yk1UPndvOJAmJQT\n' + // 'iLD+iTterj4y3kZKM4J8wG+rqZfE41i3PiqIIQBC79CgIB3Ck9YoGiI8utPoDpFb\n' + // 'pzEwo8xexO+5e8nNrSozKsilTsTwF9bMg1Oknp3LglrS33KFRf84TU8T8EIeRt7i\n' + // 'EOAzdVb48eJZi001bMHtOUPVa7Ncrby3yrb6G+uwxbKJd0wpNO1b0UdSFMnU++nV\n' + // 'n5Li0TT0zqwufG/HiyE5HZhfG/CDuyCdKJDKI2EeDqq9AgMBAAE=\n' + // ' -----END PUBLIC KEY-----' // }, // privateKey: { // jwk: { // d: 'CBzAklfq9m4et0gOs0vzm_Lilvlw1Ye0ifYCVBDxM15cwpBTiRiqxgIiGYfONVBNdpu3cjXa76So3HWO10ULglED2waQv3OHn8_Q1Bq__5cOeNEVl5CZ74qQdRTrjc4Zq2O4_U7Izy5dSKxawJTUse0TY1LWL7tz4PdoXI0y-L7iqiRNOTXHtFLCHwuPDTxP_0zNMN4CI_PTHpEbzCbyAvbPkg0nc9XtPxvHE3osmcPL6Ax1W1bTDEBtJiheNi5g13qLRTXxCbYmyMekZ1lKtFqVDlbWzI9RZPL8F0vPiNweuH_XL37bUDQBR6gXAF2mnQYkEuoMoW8V0xvXqnFy9bGOMd3M7zyCZRhEuJgLRzc9xIbgVQEZahWXGOgcS1ZWxdXj2Y2qv2RPcZqNR77ho_haQjwfMHnSlob0p78u_Zv5vXxZsog4tnz8tiZXixGgu3zcfuBgEyv7Pmf5vIxwYrxDHDJKTggOZdb2E5jhm6eObXz8H3gxqNKtByJr3t_h', // dp: 'Zq0JouHdV_CS6XP_n_dicj6fcfgaJHbNnrI8t0KV1bdEkeHfrFXTNtJF1DP5c5qtcLtOjqN9amoNE1zLy_oBJdY9_xvbmNP5aj7kzHjOJctc1101ZFr79TfbaTF9yy5wBhLJbQ_TUfUuy7WG8i4Z1bfuT1KTSNH8wBv16biliwARckyoI83BAUI5WuDJ-qWmq7gqz6heaq_z0uHkYQ_6c53O596IZjE56K_rGQHkqoZL0aUge7vQgsE61aijdzGh', // dq: 'i8IC8SSgUbdIm8iSrtoC7NbNoQsveVOf8tg67Wgg2NoNsq8PQqDBD0i-qqRMwgBgPK3-FuQMqEP6QqVSzgpc-kHOW-ZlQTto0Q0FvWjsI0dpbhL1_E1bqVRME9gLrRp0p0t0MDnMmZCSEXKIr7QWrqQJpMUcYjNk_a5AcYU0Q2zshDBp7zHc8zwgTuwQSl-ul22ioA0N83p_2CV6zJjoDrHWgfFlJq7Qi4SuNJN5tEQBsOqMfgKo9TQ83P_Pp40Z', // e: 'AQAB', // kty: 'RSA', // n: 'jp8P2mZy0A3QQ8QL1hW6mRMCGiHyOpTssmJlQ-LDXWsWxw7SwW9CpKPLlBs-5YJ7kq7h5gcMlZz44hqhwAWvTGJr_iy5w8HsfFSU8t8YURug4KvZywf7wILBZXmLnOElemvg9hzRHEEQ-3W4MmDQrxpxphYutAEkB_xh_sSdmnSaPnTxWyXilIoiW5-oJtNt50w-rT6C2xo4phHYkIqYfBT7eaeMSIvB68bxyOf8j-ZLFaPmyF6Fre7Bh4v3UOvnLk0l8yk1UPndvOJAmJQTiLD-iTterj4y3kZKM4J8wG-rqZfE41i3PiqIIQBC79CgIB3Ck9YoGiI8utPoDpFbpzEwo8xexO-5e8nNrSozKsilTsTwF9bMg1Oknp3LglrS33KFRf84TU8T8EIeRt7iEOAzdVb48eJZi001bMHtOUPVa7Ncrby3yrb6G-uwxbKJd0wpNO1b0UdSFMnU--nVn5Li0TT0zqwufG_HiyE5HZhfG_CDuyCdKJDKI2EeDqq9', // p: 'wQlwbT5nDDoYpW9KItjDxSszo5xb8w1nNuT2gCy_NQ2Jby6feyVL1IkDFKCjJfniBJpN377-EV8mmjho0UE6q0TviaFjAfyurtSZGbF735wkiKPzO6-4Fx39WWdQQF0GvPL2AP5G6Svt4cKjsVcTji7W5BAlcwWOYFeVSo0_IfZphPnqR7vxZKRgAdZHRoU9_-sD3nJ6EBm41E8pWH0qVZ3jxI35Q36pFaulj0djKtgHox8lc-VUL92N4f0z8STh', // q: 'vSPuIKAfaeftaHSL-zQfdWuiSBcCXEZhJ_97ENvSNCOvq-hekoS1Y0G4cJhfW6QHN1xODaZ3hFfv4TWvmc8l-Gb7js-tfNZCOwxlQiBBXMDJ7YVQK35AAEDnSsLa0kilB6_gV97pUWKhy9DQbGr9EIoq0wGKBlJGBNwIKTi7kLzfblUZ9EjDVAyUSh4WC_J4zOyBBMRDdR4eUNNjPK0J11jOvXGJb8lQL6XNPGPs4gj54hnumZ5oRMA5m3ohV-Vd', // qi: 'TCH3HFlW-7RRpLpJdSejpkkPqZ5ZcZEQ7Z_rBQYPaIVKyO45osm1mKVBvpLWNaaYpO9lRRE7JqOEBqysjp5ymfzgLYutaUPO3_q5PiKrNnYDWPOFOc4ULxFUb0Fm-SvanAaMN2fp1UB7n1ntVQgEeTMWTutNKMu1Cbky7YOBI1IdeUcENsxjjozCnINjUaVmOcdLObIHvjYpcxFzQEh2py34_SmvFp9bvgRVCYrtK4fpssH635FIVZhIAPpTXvD4' // }, // pem: '-----BEGIN PRIVATE KEY-----\n' + // 'MIIG/QIBADANBgkqhkiG9w0BAQEFAASCBucwggbjAgEAAoIBgQCOnw/aZnLQDdBD\n' + // 'xAvWFbqZEwIaIfI6lOyyYmVD4sNdaxbHDtLBb0Kko8uUGz7lgnuSruHmBwyVnPji\n' + // 'GqHABa9MYmv+LLnDwex8VJTy3xhRG6Dgq9nLB/vAgsFleYuc4SV6a+D2HNEcQRD7\n' + // 'dbgyYNCvGnGmFi60ASQH/GH+xJ2adJo+dPFbJeKUiiJbn6gm023nTD6tPoLbGjim\n' + // 'EdiQiph8FPt5p4xIi8HrxvHI5/yP5ksVo+bIXoWt7sGHi/dQ6+cuTSXzKTVQ+d28\n' + // '4kCYlBOIsP6JO16uPjLeRkozgnzAb6upl8TjWLc+KoghAELv0KAgHcKT1igaIjy6\n' + // '0+gOkVunMTCjzF7E77l7yc2tKjMqyKVOxPAX1syDU6SencuCWtLfcoVF/zhNTxPw\n' + // 'Qh5G3uIQ4DN1Vvjx4lmLTTVswe05Q9Vrs1ytvLfKtvob67DFsol3TCk07VvRR1IU\n' + // 'ydT76dWfkuLRNPTOrC58b8eLITkdmF8b8IO7IJ0okMojYR4Oqr0CAwEAAQKCAYAI\n' + // 'HMCSV+r2bh63SA6zS/Ob8uKW+XDVh7SJ9gJUEPEzXlzCkFOJGKrGAiIZh841UE12\n' + // 'm7dyNdrvpKjcdY7XRQuCUQPbBpC/c4efz9DUGr//lw540RWXkJnvipB1FOuNzhmr\n' + // 'Y7j9TsjPLl1IrFrAlNSx7RNjUtYvu3Pg92hcjTL4vuKqJE05Nce0UsIfC48NPE//\n' + // 'TM0w3gIj89MekRvMJvIC9s+SDSdz1e0/G8cTeiyZw8voDHVbVtMMQG0mKF42LmDX\n' + // 'eotFNfEJtibIx6RnWUq0WpUOVtbMj1Fk8vwXS8+I3B64f9cvfttQNAFHqBcAXaad\n' + // 'BiQS6gyhbxXTG9eqcXL1sY4x3czvPIJlGES4mAtHNz3EhuBVARlqFZcY6BxLVlbF\n' + // '1ePZjaq/ZE9xmo1HvuGj+FpCPB8wedKWhvSnvy79m/m9fFmyiDi2fPy2JleLEaC7\n' + // 'fNx+4GATK/s+Z/m8jHBivEMcMkpOCA5l1vYTmOGbp45tfPwfeDGo0q0HImve3+EC\n' + // 'gcEAwQlwbT5nDDoYpW9KItjDxSszo5xb8w1nNuT2gCy/NQ2Jby6feyVL1IkDFKCj\n' + // 'JfniBJpN377+EV8mmjho0UE6q0TviaFjAfyurtSZGbF735wkiKPzO6+4Fx39WWdQ\n' + // 'QF0GvPL2AP5G6Svt4cKjsVcTji7W5BAlcwWOYFeVSo0/IfZphPnqR7vxZKRgAdZH\n' + // 'RoU9/+sD3nJ6EBm41E8pWH0qVZ3jxI35Q36pFaulj0djKtgHox8lc+VUL92N4f0z\n' + // '8SThAoHBAL0j7iCgH2nn7Wh0i/s0H3VrokgXAlxGYSf/exDb0jQjr6voXpKEtWNB\n' + // 'uHCYX1ukBzdcTg2md4RX7+E1r5nPJfhm+47PrXzWQjsMZUIgQVzAye2FUCt+QABA\n' + // '50rC2tJIpQev4Ffe6VFiocvQ0Gxq/RCKKtMBigZSRgTcCCk4u5C8325VGfRIw1QM\n' + // 'lEoeFgvyeMzsgQTEQ3UeHlDTYzytCddYzr1xiW/JUC+lzTxj7OII+eIZ7pmeaETA\n' + // 'OZt6IVflXQKBwGatCaLh3Vfwkulz/5/3YnI+n3H4GiR2zZ6yPLdCldW3RJHh36xV\n' + // '0zbSRdQz+XOarXC7To6jfWpqDRNcy8v6ASXWPf8b25jT+Wo+5Mx4ziXLXNddNWRa\n' + // '+/U322kxfcsucAYSyW0P01H1Lsu1hvIuGdW37k9Sk0jR/MAb9em4pYsAEXJMqCPN\n' + // 'wQFCOVrgyfqlpqu4Ks+oXmqv89Lh5GEP+nOdzufeiGYxOeiv6xkB5KqGS9GlIHu7\n' + // '0ILBOtWoo3cxoQKBwQCLwgLxJKBRt0ibyJKu2gLs1s2hCy95U5/y2DrtaCDY2g2y\n' + // 'rw9CoMEPSL6qpEzCAGA8rf4W5AyoQ/pCpVLOClz6Qc5b5mVBO2jRDQW9aOwjR2lu\n' + // 'EvX8TVupVEwT2AutGnSnS3QwOcyZkJIRcoivtBaupAmkxRxiM2T9rkBxhTRDbOyE\n' + // 'MGnvMdzzPCBO7BBKX66XbaKgDQ3zen/YJXrMmOgOsdaB8WUmrtCLhK40k3m0RAGw\n' + // '6ox+Aqj1NDzc/8+njRkCgcBMIfccWVb7tFGkukl1J6OmSQ+pnllxkRDtn+sFBg9o\n' + // 'hUrI7jmiybWYpUG+ktY1ppik72VFETsmo4QGrKyOnnKZ/OAti61pQ87f+rk+Iqs2\n' + // 'dgNY84U5zhQvEVRvQWb5K9qcBow3Z+nVQHufWe1VCAR5MxZO600oy7UJuTLtg4Ej\n' + // 'Uh15RwQ2zGOOjMKcg2NRpWY5x0s5sge+NilzEXNASHanLfj9Ka8Wn1u+BFUJiu0r\n' + // 'h+mywfrfkUhVmEgA+lNe8Pg=\n' + // ' -----END PRIVATE KEY-----' // } // }, '4096': { publicKey: { jwk: { e: 'AQAB', kty: 'RSA', n: 'qUfmVrVz-i2GxL6CPmVMuR-mPgoZi5uUXJOkr19bUpYaXNmVUwozrREji73QBVcd2vXZLkW6DNsumItV20FaMy3WF0NtzBoQTOTwJnOi_bP5LjxFSCz-vcJrxCG7_N3glY0tWYCNLzQ5B-LXKI-gGvJL0TTj7zUCXzU9DYjMQw-7fXpc6D0uCPrJOKuO2Z4n9YrrY-uD5id5TkEQp_0m_ZKiGR1bKHJEiI3Rt-7kDUqJqjHGLLCgUSi4iIKgxoLJHa0vyWP4Ro1X6xPMbPpwPPAc6cSJoK85q5CUD6dzJn19pXhdZcdizXHn9iCYa7J8looC4jCDew6WHr2d0fSCQ3uDEXPHsmKZR8z1tPZawOND5IHw9HfSgHDkfztjDo4d7pw81LCGGS0C60C1J90ay2U1ArLHDxsXI7FRpuuCHWFdFIBrFb1xytNguWdM3kn1ZhPPJpayZDVVrh_nOUWobUBEZuoeph8VxO5R8pZAQ1w0AUr9AFpV1QErRrbGrqTc8ESXnYUZVJJDjZtIpIggTLdSPXwrVRAXhmxaLNcjD5KSIPO8rpnuslKnAUNqMLORn0oov7gxxrTcj_WLeT7r2Ta5MeOtfyReqNvzcmx6EF3-GyBM0NBleUrnkYloZPKOMEV9-NcjQnNeeJOgoG_Ia_9Bckl0w2VQhDqT0QNodvk' }, pem: '-----BEGIN PUBLIC KEY-----\n' + 'MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAqUfmVrVz+i2GxL6CPmVM\n' + 'uR+mPgoZi5uUXJOkr19bUpYaXNmVUwozrREji73QBVcd2vXZLkW6DNsumItV20Fa\n' + 'My3WF0NtzBoQTOTwJnOi/bP5LjxFSCz+vcJrxCG7/N3glY0tWYCNLzQ5B+LXKI+g\n' + 'GvJL0TTj7zUCXzU9DYjMQw+7fXpc6D0uCPrJOKuO2Z4n9YrrY+uD5id5TkEQp/0m\n' + '/ZKiGR1bKHJEiI3Rt+7kDUqJqjHGLLCgUSi4iIKgxoLJHa0vyWP4Ro1X6xPMbPpw\n' + 'PPAc6cSJoK85q5CUD6dzJn19pXhdZcdizXHn9iCYa7J8looC4jCDew6WHr2d0fSC\n' + 'Q3uDEXPHsmKZR8z1tPZawOND5IHw9HfSgHDkfztjDo4d7pw81LCGGS0C60C1J90a\n' + 'y2U1ArLHDxsXI7FRpuuCHWFdFIBrFb1xytNguWdM3kn1ZhPPJpayZDVVrh/nOUWo\n' + 'bUBEZuoeph8VxO5R8pZAQ1w0AUr9AFpV1QErRrbGrqTc8ESXnYUZVJJDjZtIpIgg\n' + 'TLdSPXwrVRAXhmxaLNcjD5KSIPO8rpnuslKnAUNqMLORn0oov7gxxrTcj/WLeT7r\n' + '2Ta5MeOtfyReqNvzcmx6EF3+GyBM0NBleUrnkYloZPKOMEV9+NcjQnNeeJOgoG/I\n' + 'a/9Bckl0w2VQhDqT0QNodvkCAwEAAQ==\n' + '-----END PUBLIC KEY-----' }, privateKey: { jwk: { d: 'FBX-MIUsyv9aaZ9iRGWQLjohZ2Sa5dwSxU5WgOGbbCf33lMJ-xWvjoZFVbgyxeNxnTDFMY6f9hUOyRZlXFP7kC2M5OtBDLH-A6W5khJwAVL4yuHnZZpDKsB2OYo4LFemZZBgFGnitrpnVvZ1SbCLEo9z7BGuxwwe6S2fviqgdAeam1eozPyvaOza8fC3TT6NJr8yUYOZPbaq19x0Db7FwNpEhh7b2Wd_lsVfIEhGAoa44Xsw9M4LY73lcXsweQV9OBp73FVSmQp951yMydSIe06RW7KQkwKfoOoRi272xJco0LjAukongNGWcLeq5kKCMnmTQIP5oeEX8nNU1dwBla9SAOwltxrmkEnIsH7U5KzTIvtbFybsuOI0_tdG5X5-532MK92tstu_hnObPF78WHBbBjiRdEKuzuxeZAy3j4YORZ1wnOaMj0bCIgRf89-QwbpFC5ZKx_0Gm_wzHbkoLtDGDYu1wm19mTk4ZrdPCm8XhyJ7qSQ0ofAMxI8kOunOEESjnvES_xNnUd9iILhZFzFIubz9uYkE9wMiuJLwblIuYNkNFeQPnNEfy5bI5s1YUwr_h4AFBaGlctuQxiNl3uvMHkaTW7kZmVJM4QGMeJu61hNlN10dDYP4QyEfGgqxsuLrE5HuTlmlFbCedmlO8U2NTnPQml8mv5Uu_5j1UsE', dp: 'Ct-XAV3WyJvGsg4Dd1x42g-TSoW1pjLEbrdqIJr4LpxgACSfuIZnILeGFl58VHBWiMUSJ68T0_De_f0SPImYDNN31gZvG4rSmA0E_O5IFRNYY4s4Z3PL-PFaUv_pn1oLHGaZ0nOg34W0jLwtlE3piLZ2ADcxAUKUM0QuzzrRlfCs8StANGI-nxwIXEi-YAGU9psiz0HwQyLHsYqDx9ZWgE8xo_yDcseL3fc79Bzm9fJCNeTRAhon1UqHt-zWui7fP4s0xEB3mU2QVne3ynQOA_gJQXybSiJMJ7wzLSbVzOkkfv-2UDjIpBQvUqkLQpqOD0UWUpQukrGxxAfVJTuZ8Q', dq: 'P55KNDfDbGUZyrk43S0cRWq0Jht47nNdhP9L-G_BRS-DCRzPXP8YgTMqY9oB5-Epz4IvURTrLcIEaUZMaJ5ZsM3ZYpN1Q9t4mi3GmsefRIRnWVewJGRUByVA8LpFYlEWqdEj4Hk8Zo8wfRK1V658d-1DxQyrmUA8AkDJ3HRQFdROQDdPbA7PRGRDdo15_UBu5d8AcFisSI4g_0BApavsqt6c_mm_zu-wc2-AMbOpWfpAk-c7tTczbqSunVuqQn-RcOOSH5YZPsQcuqKdSHANsC27OIav0X_k4opXMyqIVMc4-zurOlwFyhUEx68rWVCYV7L8ws_sbqJqJP7KT5i24Q', e: 'AQAB', kty: 'RSA', n: 'qUfmVrVz-i2GxL6CPmVMuR-mPgoZi5uUXJOkr19bUpYaXNmVUwozrREji73QBVcd2vXZLkW6DNsumItV20FaMy3WF0NtzBoQTOTwJnOi_bP5LjxFSCz-vcJrxCG7_N3glY0tWYCNLzQ5B-LXKI-gGvJL0TTj7zUCXzU9DYjMQw-7fXpc6D0uCPrJOKuO2Z4n9YrrY-uD5id5TkEQp_0m_ZKiGR1bKHJEiI3Rt-7kDUqJqjHGLLCgUSi4iIKgxoLJHa0vyWP4Ro1X6xPMbPpwPPAc6cSJoK85q5CUD6dzJn19pXhdZcdizXHn9iCYa7J8looC4jCDew6WHr2d0fSCQ3uDEXPHsmKZR8z1tPZawOND5IHw9HfSgHDkfztjDo4d7pw81LCGGS0C60C1J90ay2U1ArLHDxsXI7FRpuuCHWFdFIBrFb1xytNguWdM3kn1ZhPPJpayZDVVrh_nOUWobUBEZuoeph8VxO5R8pZAQ1w0AUr9AFpV1QErRrbGrqTc8ESXnYUZVJJDjZtIpIggTLdSPXwrVRAXhmxaLNcjD5KSIPO8rpnuslKnAUNqMLORn0oov7gxxrTcj_WLeT7r2Ta5MeOtfyReqNvzcmx6EF3-GyBM0NBleUrnkYloZPKOMEV9-NcjQnNeeJOgoG_Ia_9Bckl0w2VQhDqT0QNodvk', p: '2JlHgWN0cN7MUem1aGsV1CXEF7uKB9BF1aibAI1d9rS52rL0upoKM9-Jj_73C7lEZ51AVME-83LsJapswAaU9sffH8Sj3okdUzpwgvpSHnUkfCgljrjV4jk2VwMBV-arYCcUKEN85jYplevy9xcFB1BbZ0VY5VsnNHmMK7N_M_-aDgVl55olJMcoBRDbzFRsVAtQpLUboP7Rzg-qR3CyjNCvylJvrq-_sI_x8XAh1hOe5y4idtS7U8DlRKxTVn7J4CHzMly9YBwjy7cIar7UlT8fZhP67AxRFQlohzzEYGdxddKpAGWIjG-w2oX8PNWRBu_IknsIKRr1ZW9crbvF2Q', q: 'yBMWkrpBbhbaDO-YTDz_swlLTXmFM5yLBIS8PzBccPq1QWn2BcE-bAb4_3oFQaZqnVE5WRqATy1R94H65p3vdFekHbCp6bmEKpVRPsooLCvtpMMl01BuzRiIlKJ6b6YWnWnHiPNk9xBjaSJwYoVW60XCxvFzXUAz68PB527NTY7PZWFA0YFi0fz555ColDtcfrPmfTG_kdxedh68JqFG9CLvloh18O7OZWWgXc3LEsD5Z7FGbvdY5vP21g0jz9FEtrW6I5qJ96N3O1bQjqp2pejS4bFPB40xOt7wVLx9WBzEiRrStPGd0oHu4kIaqeVpaxO_QeQaw0mOzUnCxyvmIQ', qi: 'eQOoEKXImD78K0ETHHKAvq4bgl0Sju8ubaXXUlFKD4xZhNfg4O73zBpPWn95XejlfkO1ZI-UP2Gg0FtaWJm0it50CchNt5TXnx5x-NYnn07MTzjxGJEFrJoCArq4tiCZpYxV1-EWCAuqsJRgYl8ctG8oPD7g_mM9cRaG0hhPW_q6PvWb0NsmFG0BCXEtk78TuSKLA9VO3fWgm3jTaIdNE96yLd_S727_aQsGQvy58VfV_YLhQjGOTkAwBf5lh7g_dS61rkD5KYeLo1SwbrQbh60G9JwH4KHqcqYFFe5vb4PVelG_1vNffGEO3MuMclb8-baa3o1Su9h-HPTqQaijGg' }, pem: '-----BEGIN PRIVATE KEY-----\n' + 'MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQCpR+ZWtXP6LYbE\n' + 'voI+ZUy5H6Y+ChmLm5Rck6SvX1tSlhpc2ZVTCjOtESOLvdAFVx3a9dkuRboM2y6Y\n' + 'i1XbQVozLdYXQ23MGhBM5PAmc6L9s/kuPEVILP69wmvEIbv83eCVjS1ZgI0vNDkH\n' + '4tcoj6Aa8kvRNOPvNQJfNT0NiMxDD7t9elzoPS4I+sk4q47Znif1iutj64PmJ3lO\n' + 'QRCn/Sb9kqIZHVsockSIjdG37uQNSomqMcYssKBRKLiIgqDGgskdrS/JY/hGjVfr\n' + 'E8xs+nA88BzpxImgrzmrkJQPp3MmfX2leF1lx2LNcef2IJhrsnyWigLiMIN7DpYe\n' + 'vZ3R9IJDe4MRc8eyYplHzPW09lrA40PkgfD0d9KAcOR/O2MOjh3unDzUsIYZLQLr\n' + 'QLUn3RrLZTUCsscPGxcjsVGm64IdYV0UgGsVvXHK02C5Z0zeSfVmE88mlrJkNVWu\n' + 'H+c5RahtQERm6h6mHxXE7lHylkBDXDQBSv0AWlXVAStGtsaupNzwRJedhRlUkkON\n' + 'm0ikiCBMt1I9fCtVEBeGbFos1yMPkpIg87yume6yUqcBQ2ows5GfSii/uDHGtNyP\n' + '9Yt5PuvZNrkx461/JF6o2/NybHoQXf4bIEzQ0GV5SueRiWhk8o4wRX341yNCc154\n' + 'k6Cgb8hr/0FySXTDZVCEOpPRA2h2+QIDAQABAoICABQV/jCFLMr/WmmfYkRlkC46\n' + 'IWdkmuXcEsVOVoDhm2wn995TCfsVr46GRVW4MsXjcZ0wxTGOn/YVDskWZVxT+5At\n' + 'jOTrQQyx/gOluZIScAFS+Mrh52WaQyrAdjmKOCxXpmWQYBRp4ra6Z1b2dUmwixKP\n' + 'c+wRrscMHuktn74qoHQHmptXqMz8r2js2vHwt00+jSa/MlGDmT22qtfcdA2+xcDa\n' + 'RIYe29lnf5bFXyBIRgKGuOF7MPTOC2O95XF7MHkFfTgae9xVUpkKfedcjMnUiHtO\n' + 'kVuykJMCn6DqEYtu9sSXKNC4wLpKJ4DRlnC3quZCgjJ5k0CD+aHhF/JzVNXcAZWv\n' + 'UgDsJbca5pBJyLB+1OSs0yL7Wxcm7LjiNP7XRuV+fud9jCvdrbLbv4Zzmzxe/Fhw\n' + 'WwY4kXRCrs7sXmQMt4+GDkWdcJzmjI9GwiIEX/PfkMG6RQuWSsf9Bpv8Mx25KC7Q\n' + 'xg2LtcJtfZk5OGa3TwpvF4cie6kkNKHwDMSPJDrpzhBEo57xEv8TZ1HfYiC4WRcx\n' + 'SLm8/bmJBPcDIriS8G5SLmDZDRXkD5zRH8uWyObNWFMK/4eABQWhpXLbkMYjZd7r\n' + 'zB5Gk1u5GZlSTOEBjHibutYTZTddHQ2D+EMhHxoKsbLi6xOR7k5ZpRWwnnZpTvFN\n' + 'jU5z0JpfJr+VLv+Y9VLBAoIBAQDYmUeBY3Rw3sxR6bVoaxXUJcQXu4oH0EXVqJsA\n' + 'jV32tLnasvS6mgoz34mP/vcLuURnnUBUwT7zcuwlqmzABpT2x98fxKPeiR1TOnCC\n' + '+lIedSR8KCWOuNXiOTZXAwFX5qtgJxQoQ3zmNimV6/L3FwUHUFtnRVjlWyc0eYwr\n' + 's38z/5oOBWXnmiUkxygFENvMVGxUC1CktRug/tHOD6pHcLKM0K/KUm+ur7+wj/Hx\n' + 'cCHWE57nLiJ21LtTwOVErFNWfsngIfMyXL1gHCPLtwhqvtSVPx9mE/rsDFEVCWiH\n' + 'PMRgZ3F10qkAZYiMb7Dahfw81ZEG78iSewgpGvVlb1ytu8XZAoIBAQDIExaSukFu\n' + 'FtoM75hMPP+zCUtNeYUznIsEhLw/MFxw+rVBafYFwT5sBvj/egVBpmqdUTlZGoBP\n' + 'LVH3gfrmne90V6QdsKnpuYQqlVE+yigsK+2kwyXTUG7NGIiUonpvphadaceI82T3\n' + 'EGNpInBihVbrRcLG8XNdQDPrw8Hnbs1Njs9lYUDRgWLR/PnnkKiUO1x+s+Z9Mb+R\n' + '3F52HrwmoUb0Iu+WiHXw7s5lZaBdzcsSwPlnsUZu91jm8/bWDSPP0US2tbojmon3\n' + 'o3c7VtCOqnal6NLhsU8HjTE63vBUvH1YHMSJGtK08Z3Sge7iQhqp5WlrE79B5BrD\n' + 'SY7NScLHK+YhAoIBAArflwFd1sibxrIOA3dceNoPk0qFtaYyxG63aiCa+C6cYAAk\n' + 'n7iGZyC3hhZefFRwVojFEievE9Pw3v39EjyJmAzTd9YGbxuK0pgNBPzuSBUTWGOL\n' + 'OGdzy/jxWlL/6Z9aCxxmmdJzoN+FtIy8LZRN6Yi2dgA3MQFClDNELs860ZXwrPEr\n' + 'QDRiPp8cCFxIvmABlPabIs9B8EMix7GKg8fWVoBPMaP8g3LHi933O/Qc5vXyQjXk\n' + '0QIaJ9VKh7fs1rou3z+LNMRAd5lNkFZ3t8p0DgP4CUF8m0oiTCe8My0m1czpJH7/\n' + 'tlA4yKQUL1KpC0Kajg9FFlKULpKxscQH1SU7mfECggEAP55KNDfDbGUZyrk43S0c\n' + 'RWq0Jht47nNdhP9L+G/BRS+DCRzPXP8YgTMqY9oB5+Epz4IvURTrLcIEaUZMaJ5Z\n' + 'sM3ZYpN1Q9t4mi3GmsefRIRnWVewJGRUByVA8LpFYlEWqdEj4Hk8Zo8wfRK1V658\n' + 'd+1DxQyrmUA8AkDJ3HRQFdROQDdPbA7PRGRDdo15/UBu5d8AcFisSI4g/0BApavs\n' + 'qt6c/mm/zu+wc2+AMbOpWfpAk+c7tTczbqSunVuqQn+RcOOSH5YZPsQcuqKdSHAN\n' + 'sC27OIav0X/k4opXMyqIVMc4+zurOlwFyhUEx68rWVCYV7L8ws/sbqJqJP7KT5i2\n' + '4QKCAQB5A6gQpciYPvwrQRMccoC+rhuCXRKO7y5tpddSUUoPjFmE1+Dg7vfMGk9a\n' + 'f3ld6OV+Q7Vkj5Q/YaDQW1pYmbSK3nQJyE23lNefHnH41iefTsxPOPEYkQWsmgIC\n' + 'uri2IJmljFXX4RYIC6qwlGBiXxy0byg8PuD+Yz1xFobSGE9b+ro+9ZvQ2yYUbQEJ\n' + 'cS2TvxO5IosD1U7d9aCbeNNoh00T3rIt39Lvbv9pCwZC/LnxV9X9guFCMY5OQDAF\n' + '/mWHuD91LrWuQPkph4ujVLButBuHrQb0nAfgoepypgUV7m9vg9V6Ub/W8198YQ7c\n' + 'y4xyVvz5tprejVK72H4c9OpBqKMa\n' + '-----END PRIVATE KEY-----' } } }; export default params;
the_stack
import * as mqtt from 'mqtt'; import axios from 'axios'; import { BehaviorSubject, Subject } from 'rxjs'; import { Widget } from './widget'; import bonjour from 'bonjour'; import * as WebSocket from 'ws'; import * as schedule from 'node-schedule'; import * as pauseable from 'pauseable'; import { tip, warn, error, timerLog, mqttLog } from './debug' import getMAC from 'getmac' import { VoiceAssistant } from './voice-assistant'; export interface Message { fromDevice?: string, data: any } export interface authOption { "authKey"?: string, "version"?: string, "protocol"?: string, "webSocket"?: boolean } export class BlinkerDevice { options: authOption = { version: '1.0', protocol: 'mqtts', webSocket: true }; mqttClient: mqtt.MqttClient; wsServer; ws; config: { broker: string, deviceName: string, host: string, iotId: string, iotToken: string, port: string, productKey: string, uuid: string, authKey?: string }; subTopic; pubTopic; deviceName; targetDevice; dataRead = new Subject<Message>() heartbeat = new Subject<Message>() realtimeRequest = new Subject<string[]>() builtinSwitch = new BuiltinSwitch(); configReady = new BehaviorSubject(false) widgetKeyList = [] widgetDict = {} sharedUserList = [] private tempData; private tempDataPath; constructor(authkey = '', options?: authOption) { if (authkey == '') { authkey = loadJsonFile('.auth.json').authkey console.log(authkey); } for (const key in options) { this.options[key] = options[key] } this.options['authKey'] = authkey this.init(authkey) } init(authkey) { axios.get(API.AUTH, { params: this.options }).then(async resp => { console.log(resp.data); if (resp.data.message != 1000) { error(resp.data); return } this.config = resp.data.detail this.config['authKey'] = authkey if (this.config.broker == 'aliyun') { mqttLog('broker:aliyun') this.initBroker_Aliyun() } else if (this.config.broker == 'blinker') { mqttLog('broker:blinker') this.initBroker_Blinker() } await this.connectBroker() this.addWidget(this.builtinSwitch) this.getShareInfo() this.initLocalService() // 加载暂存数据 this.tempDataPath = `.${this.config.deviceName}.json` this.tempData = loadJsonFile(this.tempDataPath) this.loadTimingTask() this.configReady.next(true) }) } ready(): Promise<Boolean> { return new Promise((resolve, reject) => { setTimeout(() => { resolve(true) }, 5000); }) } // 本地服务:MDNS\WS SERVER initLocalService() { if (!this.options.webSocket) return // 开启mdns服务 bonjour().publish({ name: this.config.deviceName, type: 'blinker', host: this.config.deviceName + '.local', port: 81, txt: { mac: getMAC().replace(/:/g, '').toUpperCase() } }) this.wsServer = new WebSocket.Server({ port: 81 }); this.wsServer.on('connection', ws => { tip('local connection'); ws.send(`{"state":"connected"}`) this.ws = ws this.ws.on('message', (message) => { let data; let fromDevice; try { data = JSON.parse(message) this.processData(data, fromDevice) } catch (error) { console.log(error); console.log(message); } }); }) this.wsServer.on('close', () => { console.log('ws client disconnect'); }) } getShareInfo() { axios.get(API.SHARE + `?deviceName=${this.config.deviceName}&key=${this.config.authKey}`).then(resp => { if (resp.data.message != 1000) { error(resp.data); return } this.sharedUserList = resp.data.detail.users }) } exasubTopic; exapubTopic; initBroker_Aliyun() { this.subTopic = `/${this.config.productKey}/${this.config.deviceName}/r`; this.pubTopic = `/${this.config.productKey}/${this.config.deviceName}/s`; this.exasubTopic = `/sys/${this.config.productKey}/${this.config.deviceName}/rrpc/request/+` this.exapubTopic = `/sys/${this.config.productKey}/${this.config.deviceName}/rrpc/response/` this.targetDevice = this.config.uuid; } initBroker_Blinker() { this.subTopic = `/device/${this.config.deviceName}/r`; this.pubTopic = `/device/${this.config.deviceName}/s`; this.targetDevice = this.config.uuid; } connectBroker() { return new Promise((resolve, reject) => { this.mqttClient = mqtt.connect(this.config.host + ':' + this.config.port, { clientId: this.config.deviceName, username: this.config.iotId, password: this.config.iotToken }); this.mqttClient.on('connect', () => { mqttLog('blinker connected'); this.mqttClient.subscribe(this.subTopic); this.startHeartbeat2cloud(); resolve(true) }) this.mqttClient.on('message', (topic, message) => { if (topic == this.subTopic) { let data; let fromDevice; try { let messageString = u8aToString(message) // console.log(topic); console.log(messageString); let messageObject = JSON.parse(messageString) fromDevice = messageObject.fromDevice data = messageObject.data this.targetDevice = fromDevice } catch (error) { console.log(error); } // 检查 if (this.sharedUserList.indexOf(fromDevice) < 0 && fromDevice != this.config.uuid) return this.processData(data, fromDevice) } }) this.mqttClient.on('close', (err) => { mqttLog('blinker close'); this.stopHeartbeat2cloud() }) this.mqttClient.on('error', (err) => { mqttLog(err); }) }) } // 云端心跳 timer_heartbeat2cloud; startHeartbeat2cloud() { axios.get(API.HEARTBEAT + `?deviceName=${this.config.deviceName}&key=${this.config.authKey}&heartbeat=600`) this.timer_heartbeat2cloud = setInterval(() => { axios.get(API.HEARTBEAT + `?deviceName=${this.config.deviceName}&key=${this.config.authKey}&heartbeat=600`) }, 599000) } stopHeartbeat2cloud() { clearInterval(this.timer_heartbeat2cloud) } processData(data, fromDevice = this.targetDevice) { if (typeof data == 'string' || typeof data == 'number') { this.dataRead.next({ fromDevice: fromDevice, data: data }) return } if (typeof data['get'] != 'undefined') { if (data['get'] == 'state') { this.heartbeat.next(data); this.sendMessage(`{"state":"online"}`) } else if (data['get'] == 'timing') { // tip('反馈定时任务') // console.log(this.getTimingData()); this.sendMessage(this.getTimingData()) } else if (data['get'] == 'countdown') { // tip('反馈倒计时任务') this.sendMessage(this.getCountdownData()) } } else if (typeof data['set'] != 'undefined') { if (typeof data['set']['timing'] != 'undefined') { if (typeof data['set']['timing'][0]["dlt"] != 'undefined') { this.delTimingData(data['set']['timing'][0]["dlt"]) } else { this.setTimingData(data['set']['timing']); } this.sendMessage(this.getTimingData()) } else if (typeof data['set']['countdown'] != 'undefined') { // tip('设定倒计时任务') this.setCountdownData(data['set']['countdown']); this.sendMessage(this.getCountdownData()) } } else if (typeof data['rt'] != 'undefined') { this.realtimeRequest.next(data['rt']); } else { // tip(JSON.stringify(data)); let otherData = {} for (const key in data) { // 处理组件数据 if (this.widgetKeyList.indexOf(key) > -1) { let widget: Widget = this.widgetDict[key] widget.change.next({ fromDevice: fromDevice, data: data[key], }) } else { let temp = {}; temp[key] = data[key] otherData = Object.assign(otherData, temp) } } if (JSON.stringify(otherData) != '{}') this.dataRead.next({ fromDevice: fromDevice, data: otherData }) } } sendTimers = {}; messageDataCache = {} sendMessage(message: string | Object, toDevice = this.targetDevice) { // console.log(message); let sendMessage: string; if (typeof message == 'object') sendMessage = JSON.stringify(message) else sendMessage = message if (isJson(sendMessage)) { if (typeof this.messageDataCache[toDevice] == 'undefined') this.messageDataCache[toDevice] = ''; let ob = this.messageDataCache[toDevice] == '' ? {} : JSON.parse(this.messageDataCache[toDevice]); let ob2 = JSON.parse(sendMessage) this.messageDataCache[toDevice] = JSON.stringify(Object.assign(ob, ob2)) if (typeof this.sendTimers[toDevice] != 'undefined') clearTimeout(this.sendTimers[toDevice]); //检查设备是否是本地设备,是否已连接 // let deviceInLocal = false; // if (this.islocalDevice(device)) { // if (this.lanDeviceList[toDevice].state == 'connected') // deviceInLocal = true // } this.sendTimers[toDevice] = setTimeout(() => { this.mqttClient.publish(this.pubTopic, formatMess2Device(this.config.deviceName, toDevice, this.messageDataCache[toDevice])) this.messageDataCache[toDevice] = ''; delete this.sendTimers[toDevice]; }, 100) } else { console.log('not json'); if (!isNumber(sendMessage)) sendMessage = `"${sendMessage}"` this.mqttClient.publish(this.pubTopic, formatMess2Device(this.config.deviceName, toDevice, sendMessage)) } } // toDevice sendMessage2Device(message, toDevice = this.targetDevice) { this.sendMessage(message, toDevice) } // toGrounp sendMessage2Grounp(message, toGrounp) { } // toStorage storageCache = []; tsDataTimer; saveTsData(data: any) { if (this.config.broker != 'blinker') { warn('saveTsData:仅可用于blinker broker'); return } // console.log(JSON.stringify(this.storageCache)); clearTimeout(this.tsDataTimer); let currentData = Object.assign({ date: Math.floor((new Date).getTime() / 1000) }, data) if (this.storageCache.length == 0 || currentData.date - this.storageCache[this.storageCache.length - 1].date >= 5) { this.storageCache.push(currentData) } if (this.storageCache[this.storageCache.length - 1].date - this.storageCache[0].date >= 60 || this.storageCache.length >= 12) { this.sendTsData() } else this.tsDataTimer = setTimeout(() => { this.sendTsData() }, 60000); } private sendTsData() { let data = JSON.stringify(this.storageCache) if (data.length > 10240) { error('saveTsData:单次上传数据长度超过10Kb,请减少数据内容,或降低数据上传频率'); return } tip('sendTsData') this.mqttClient.publish(this.pubTopic, formatMess2StorageTs(this.config.deviceName, 'ts', data)) this.storageCache = [] } objectDataTimer saveObjectData(data: any) { if (this.config.broker != 'blinker') { warn('saveObjectData:仅可用于blinker broker') return } let dataCache; if (typeof data == 'string') { if (!isJson(data)) { error(`saveObjectData:数据不是对象`) return } else { dataCache = JSON.parse(data) } } else { dataCache = data } clearTimeout(this.objectDataTimer); this.objectDataTimer = setTimeout(() => { tip('saveObjectData') this.mqttClient.publish(this.pubTopic, formatMess2StorageOt(this.config.deviceName, 'ot', JSON.stringify(dataCache))) }, 5000); } textDataTimer saveTextData(data: string) { if (this.config.broker != 'blinker') { warn('saveTextData:仅可用于blinker broker'); return } if (data.length > 1024) { error('saveTextData:数据长度超过1024字节'); return } clearTimeout(this.textDataTimer); this.textDataTimer = setTimeout(() => { tip('saveTextData') this.mqttClient.publish(this.pubTopic, formatMess2StorageTt(this.config.deviceName, 'tt', data)) }, 5000); } addWidget(widget: Widget | any): Widget | any { widget.device = this; this.widgetKeyList.push(widget.key); this.widgetDict[widget.key] = widget; return widget } addVoiceAssistant(voiceAssistant: VoiceAssistant) { this.configReady.subscribe(state => { if (state) { let params = Object.assign({ token: this.config.iotToken }, voiceAssistant.vaType) axios.post(API.VOICE_ASSISTANT, params).then(resp => { // console.log(resp); voiceAssistant.device = this; voiceAssistant.listen(); }) } }) return voiceAssistant } vibrate(time = 500) { this.sendMessage(`{"vibrate":${time}}`) } sendSmsTimeout = true; sms(text: string) { if (!this.sendSmsTimeout) { warn('sendSms:too frequent requests') return } this.sendSmsTimeout = false; setTimeout(() => { this.sendSmsTimeout = true }, 60000); axios.post(API.SMS, { 'deviceName': this.config.deviceName, 'key': this.config.authKey, 'msg': text }).then(resp => { if (resp.data.message != 1000) error(resp.data); }) } wechat(title: string, state: string, text: string) { axios.post(API.WECHAT, { 'deviceName': this.config.deviceName, 'key': this.config.authKey, 'title': title, 'state': state, 'msg': text }).then(resp => { if (resp.data.message != 1000) error(resp.data); }) } push(text: string) { axios.post(API.PUSH, { 'deviceName': this.config.deviceName, 'key': this.config.authKey, 'msg': text }).then(resp => { if (resp.data.message != 1000) error(resp.data); }) } notice(message) { this.sendMessage(`{"notice":"${message}"}`) } // 定时功能 timingTasks = []; private setTimingData(data) { timerLog('set timing task') if (typeof this.tempData['timing'] == 'undefined') this.tempData['timing'] = [] this.tempData['timing'][data[0].task] = data[0] this.addTimingTask(data[0]) } private getTimingData() { if (typeof this.tempData['timing'] == 'undefined') return { timing: [] } else return { timing: this.tempData['timing'] } } private delTimingData(taskId) { this.delTimingTask(taskId) arrayRemove(this.tempData['timing'], taskId) for (let index = taskId; index < this.tempData['timing'].length; index++) this.tempData['timing'][index].task = index } private addTimingTask(taskData) { // console.log(taskData); if (taskData.ena == 0) { this.disableTimingTask(taskData.task) return } let hour = Math.floor(taskData.tim / 60); let minute = taskData.tim % 60 let dayOfWeek = [] for (let index = 0; index < taskData.day.length; index++) { if (taskData.day[index] == '1') dayOfWeek.push(index) } let config = { minute: minute, hour: hour } if (dayOfWeek.length == 1) { config['dayOfWeek'] = dayOfWeek[0] } else if (dayOfWeek.length > 1) { config['dayOfWeek'] = dayOfWeek } // console.log(config); this.timingTasks[taskData.task] = schedule.scheduleJob(config, () => { this.processData(taskData.act[0]) this.disableTimingTask(taskData.task) this.sendMessage(this.getTimingData()) timerLog('timer task done') }) saveJsonFile(this.tempDataPath, this.tempData) } private delTimingTask(taskId) { this.disableTimingTask(taskId); arrayRemove(this.timingTasks, taskId) saveJsonFile(this.tempDataPath, this.tempData) } private disableTimingTask(taskId) { this.tempData['timing'][taskId].ena = 0; this.timingTasks[taskId].cancel(); saveJsonFile(this.tempDataPath, this.tempData) } // 重启后,加载定时配置 private loadTimingTask() { if (typeof this.tempData['timing'] == 'undefined') return timerLog("load timing tasks") for (let index = 0; index < this.tempData['timing'].length; index++) { const task = this.tempData['timing'][index]; if (task.ena == 1) this.addTimingTask(task) } } // 倒计时功能 countdownTimer; countdownTimer2; setCountdownData(data) { if (data == 'dlt') { timerLog('countdown stop') this.tempData['countdown'] = false this.clearCountdownTimer() return } else if (JSON.stringify(data).indexOf(`{"run":1}`) > -1 || JSON.stringify(data).indexOf(`{"run":0}`) > -1) { this.tempData['countdown']['run'] = data.run if (this.tempData['countdown']['run'] == 0) { timerLog('countdown pause') this.countdownTimer.pause() this.countdownTimer2.pause() } else if (this.tempData['countdown']['run'] == 1) { timerLog('countdown resume') this.countdownTimer.resume() this.countdownTimer2.resume() } return } timerLog('countdown start') this.tempData['countdown'] = data; this.tempData['countdown']['rtim'] = 0 this.clearCountdownTimer(); this.countdownTimer = pauseable.setTimeout(() => { this.clearCountdownTimer(); timerLog('countdown done') this.processData(this.tempData['countdown'].act[0]); // 关闭倒计时 this.tempData['countdown'] = false this.sendMessage(this.getCountdownData()) }, data.ttim * 60 * 1000); this.countdownTimer2 = pauseable.setInterval(() => { this.tempData['countdown']['rtim']++; if (this.tempData['countdown']['rtim'] == this.tempData['countdown']['ttim']) clearInterval(this.countdownTimer2) }, 60 * 1000) } clearCountdownTimer() { if (typeof this.countdownTimer != 'undefined') this.countdownTimer.clear() if (typeof this.countdownTimer != 'undefined') this.countdownTimer2.clear() } getCountdownData() { if (typeof this.tempData['countdown'] == 'undefined') return { countdown: false } else return { countdown: this.tempData['countdown'] } } // 气象数据获取 getWeather(cityCode = null) { let params = { device: this.config.deviceName, key: this.config.iotToken } if (cityCode != null) { params['code'] = cityCode } return axios.get(API.WEATHER, { params: params }).then((resp) => { if (resp.data.message == 1000) return resp.data.detail else { error('getWeather 超出限制') return } }) } getWeatherForecast(cityCode = null) { let params = { device: this.config.deviceName, key: this.config.iotToken } if (cityCode != null) { params['code'] = cityCode } return axios.get(API.WEATHER_FORECAST, { params: params }).then((resp) => { if (resp.data.message == 1000) return resp.data.detail else { error('getWeatherForecast 超出限制') return } }) } getAir(cityCode = null) { let params = { device: this.config.deviceName, key: this.config.iotToken } if (cityCode != null) { params['code'] = cityCode } return axios.get(API.AIR, { params: params } ).then((resp) => { if (resp.data.message == 1000) return resp.data.detail else { error('getAir 超出限制') return } }) } log(logString) { return axios.post(API.LOG, { token: this.config.iotToken, data: [[(new Date()).getTime().toString().substr(0, 10), logString]] }).then((resp: any) => { if (resp.data.message == 1000) tip('log2Cloud') return resp.data }) } setPosition(lng, lat) { return axios.post(API.POSITION, { token: this.config.iotToken, data: [[(new Date()).getTime().toString().substr(0, 10), [lng, lat]]] }).then((resp: any) => { if (resp.data.message == 1000) tip('position2Cloud') return resp.data }) } // 实时数据传输功能 realtimeTasks = {} sendRtData(key: string, func: Function, time = 1000) { if (typeof this.realtimeTasks[key] != 'undefined') this.realtimeTasks[key].cancel() this.realtimeTasks[key] = schedule.scheduleJob( { end: Date.now() + 10000, rule: `*/${time / 1000} * * * * *` }, () => { let message = `{"${key}":{"val":${func()},"date":${Math.round(new Date().getTime() / 1000)}}}` this.sendMessage(message) }) } } // 内置开关 export class BuiltinSwitch { key = 'switch'; state = ''; change = new Subject<Message>(); setState(state) { this.state = state return this } update() { let message = {} message[this.key] = this.state this.device.sendMessage(message) } device: BlinkerDevice; } function formatMess2Device(deviceId, toDevice, data) { // 兼容阿里broker保留deviceType和fromDevice return `{"deviceType":"OwnApp","data":${data},"fromDevice":"${deviceId}","toDevice":"${toDevice}"}` } function formatMess2Grounp(deviceId, toGrounp, data) { return `{"data":${data},"fromDevice":"${deviceId}","toGrounp":"${toGrounp}"}` } function formatMess2StorageTs(deviceId, storageType, data) { return `{"data":${data},"fromDevice":"${deviceId}","toStorage":"${storageType}"}` } function formatMess2StorageTt(deviceId, storageType, data) { return `{"data":"${data}","fromDevice":"${deviceId}","toStorage":"${storageType}"}` } function formatMess2StorageOt(deviceId, storageType, data) { return `{"data":${data},"fromDevice":"${deviceId}","toStorage":"${storageType}"}` } function isJson(str: string) { if (isNumber(str)) { return false; } try { JSON.parse(str); return true; } catch (e) { return false; } } function isNumber(val: string) { var regPos = /^\d+(\.\d+)?$/; //非负浮点数 var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数 if (regPos.test(val) || regNeg.test(val)) { return true; } else { // console.log("不是数字"); return false; } } import * as fs from 'fs'; import { API, SERVER } from './server.config'; import { clearInterval } from 'timers'; import { u8aToString } from './fun'; function loadJsonFile(path) { if (fs.existsSync(path)) return JSON.parse(fs.readFileSync(path, 'utf8')); else return {} } function saveJsonFile(path, data) { fs.writeFileSync(path, JSON.stringify(data)); } function arrayRemove(array, index) { if (index <= (array.length - 1)) { for (var i = index; i < array.length; i++) { array[i] = array[i + 1]; } } else { // throw new Error('超出最大索引!'); } array.length = array.length - 1; return array; }
the_stack
import { TxData } from "../../types"; import * as promisify from "tiny-promisify"; import { classUtils } from "../../../utils/class_utils"; import { Web3Utils } from "../../../utils/web3_utils"; import { BigNumber } from "../../../utils/bignumber"; import { Collateralizer as ContractArtifacts } from "@dharmaprotocol/contracts"; import * as Web3 from "web3"; import { BaseContract, CONTRACT_WRAPPER_ERRORS } from "./base_contract_wrapper"; export class CollateralizerContract extends BaseContract { public debtKernelAddress = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as CollateralizerContract; const result = await promisify<string>( self.web3ContractInstance.debtKernelAddress.call, self.web3ContractInstance, )(); return result; }, }; public tokenTransferProxy = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as CollateralizerContract; const result = await promisify<string>( self.web3ContractInstance.tokenTransferProxy.call, self.web3ContractInstance, )(); return result; }, }; public debtRegistry = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as CollateralizerContract; const result = await promisify<string>( self.web3ContractInstance.debtRegistry.call, self.web3ContractInstance, )(); return result; }, }; public unpause = { async sendTransactionAsync(txData: TxData = {}): Promise<string> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.unpause.estimateGasAsync.bind(self), ); const txHash = await promisify<string>( self.web3ContractInstance.unpause, self.web3ContractInstance, )(txDataWithDefaults); return txHash; }, async estimateGasAsync(txData: TxData = {}): Promise<number> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.unpause.estimateGas, self.web3ContractInstance, )(txDataWithDefaults); return gas; }, getABIEncodedTransactionData(txData: TxData = {}): string { const self = this as CollateralizerContract; const abiEncodedTransactionData = self.web3ContractInstance.unpause.getData(); return abiEncodedTransactionData; }, }; public returnCollateral = { async sendTransactionAsync(agreementId: string, txData: TxData = {}): Promise<string> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.returnCollateral.estimateGasAsync.bind(self, agreementId), ); const txHash = await promisify<string>( self.web3ContractInstance.returnCollateral, self.web3ContractInstance, )(agreementId, txDataWithDefaults); return txHash; }, async estimateGasAsync(agreementId: string, txData: TxData = {}): Promise<number> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.returnCollateralAsync.estimateGas, self.web3ContractInstance, )(agreementId, txDataWithDefaults); return gas; }, getABIEncodedTransactionData(agreementId: string, txData: TxData = {}): string { const self = this as CollateralizerContract; const abiEncodedTransactionData = self.web3ContractInstance.returnCollateralAsync.getData(); return abiEncodedTransactionData; }, }; public timestampAdjustedForGracePeriod = { async callAsync( gracePeriodInDays: BigNumber, defaultBlock?: Web3.BlockParam, ): Promise<BigNumber> { const self = this as CollateralizerContract; const result = await promisify<BigNumber>( self.web3ContractInstance.timestampAdjustedForGracePeriod.call, self.web3ContractInstance, )(gracePeriodInDays); return result; }, }; public paused = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<boolean> { const self = this as CollateralizerContract; const result = await promisify<boolean>( self.web3ContractInstance.paused.call, self.web3ContractInstance, )(); return result; }, }; public SECONDS_IN_DAY = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as CollateralizerContract; const result = await promisify<BigNumber>( self.web3ContractInstance.SECONDS_IN_DAY.call, self.web3ContractInstance, )(); return result; }, }; public collateralize = { async sendTransactionAsync( agreementId: string, collateralizer: string, txData: TxData = {}, ): Promise<string> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.collateralize.estimateGasAsync.bind(self, agreementId, collateralizer), ); const txHash = await promisify<string>( self.web3ContractInstance.collateralize, self.web3ContractInstance, )(agreementId, collateralizer, txDataWithDefaults); return txHash; }, async estimateGasAsync( agreementId: string, collateralizer: string, txData: TxData = {}, ): Promise<number> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.collateralize.estimateGas, self.web3ContractInstance, )(agreementId, collateralizer, txDataWithDefaults); return gas; }, getABIEncodedTransactionData( agreementId: string, collateralizer: string, txData: TxData = {}, ): string { const self = this as CollateralizerContract; const abiEncodedTransactionData = self.web3ContractInstance.collateralize.getData(); return abiEncodedTransactionData; }, }; public pause = { async sendTransactionAsync(txData: TxData = {}): Promise<string> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.pause.estimateGasAsync.bind(self), ); const txHash = await promisify<string>( self.web3ContractInstance.pause, self.web3ContractInstance, )(txDataWithDefaults); return txHash; }, async estimateGasAsync(txData: TxData = {}): Promise<number> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.pause.estimateGas, self.web3ContractInstance, )(txDataWithDefaults); return gas; }, getABIEncodedTransactionData(txData: TxData = {}): string { const self = this as CollateralizerContract; const abiEncodedTransactionData = self.web3ContractInstance.pause.getData(); return abiEncodedTransactionData; }, }; public owner = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as CollateralizerContract; const result = await promisify<string>( self.web3ContractInstance.owner.call, self.web3ContractInstance, )(); return result; }, }; public revokeCollateralizeAuthorization = { async sendTransactionAsync(agent: string, txData: TxData = {}): Promise<string> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.revokeCollateralizeAuthorization.estimateGasAsync.bind(self, agent), ); const txHash = await promisify<string>( self.web3ContractInstance.revokeCollateralizeAuthorization, self.web3ContractInstance, )(agent, txDataWithDefaults); return txHash; }, async estimateGasAsync(agent: string, txData: TxData = {}): Promise<number> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.revokeCollateralizeAuthorization.estimateGas, self.web3ContractInstance, )(agent, txDataWithDefaults); return gas; }, getABIEncodedTransactionData(agent: string, txData: TxData = {}): string { const self = this as CollateralizerContract; const abiEncodedTransactionData = self.web3ContractInstance.revokeCollateralizeAuthorization.getData(); return abiEncodedTransactionData; }, }; public tokenRegistry = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as CollateralizerContract; const result = await promisify<string>( self.web3ContractInstance.tokenRegistry.call, self.web3ContractInstance, )(); return result; }, }; public addAuthorizedCollateralizeAgent = { async sendTransactionAsync(agent: string, txData: TxData = {}): Promise<string> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.addAuthorizedCollateralizeAgent.estimateGasAsync.bind(self, agent), ); const txHash = await promisify<string>( self.web3ContractInstance.addAuthorizedCollateralizeAgent, self.web3ContractInstance, )(agent, txDataWithDefaults); return txHash; }, async estimateGasAsync(agent: string, txData: TxData = {}): Promise<number> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.addAuthorizedCollateralizeAgent.estimateGas, self.web3ContractInstance, )(agent, txDataWithDefaults); return gas; }, getABIEncodedTransactionData(agent: string, txData: TxData = {}): string { const self = this as CollateralizerContract; const abiEncodedTransactionData = self.web3ContractInstance.addAuthorizedCollateralizeAgent.getData(); return abiEncodedTransactionData; }, }; public unpackCollateralParametersFromBytes = { async callAsync( parameters: string, defaultBlock?: Web3.BlockParam, ): Promise<[BigNumber, BigNumber, BigNumber]> { const self = this as CollateralizerContract; const result = await promisify<[BigNumber, BigNumber, BigNumber]>( self.web3ContractInstance.unpackCollateralParametersFromBytes.call, self.web3ContractInstance, )(parameters); return result; }, }; public agreementToCollateralizer = { async callAsync(index_0: string, defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as CollateralizerContract; const result = await promisify<string>( self.web3ContractInstance.agreementToCollateralizer.call, self.web3ContractInstance, )(index_0); return result; }, }; public seizeCollateral = { async sendTransactionAsync(agreementId: string, txData: TxData = {}): Promise<string> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.seizeCollateral.estimateGasAsync.bind(self, agreementId), ); const txHash = await promisify<string>( self.web3ContractInstance.seizeCollateral, self.web3ContractInstance, )(agreementId, txDataWithDefaults); return txHash; }, async estimateGasAsync(agreementId: string, txData: TxData = {}): Promise<number> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.seizeCollateralAsync.estimateGas, self.web3ContractInstance, )(agreementId, txDataWithDefaults); return gas; }, getABIEncodedTransactionData(agreementId: string, txData: TxData = {}): string { const self = this as CollateralizerContract; const abiEncodedTransactionData = self.web3ContractInstance.seizeCollateralAsync.getData(); return abiEncodedTransactionData; }, }; public transferOwnership = { async sendTransactionAsync(newOwner: string, txData: TxData = {}): Promise<string> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.transferOwnership.estimateGasAsync.bind(self, newOwner), ); const txHash = await promisify<string>( self.web3ContractInstance.transferOwnership, self.web3ContractInstance, )(newOwner, txDataWithDefaults); return txHash; }, async estimateGasAsync(newOwner: string, txData: TxData = {}): Promise<number> { const self = this as CollateralizerContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.transferOwnership.estimateGas, self.web3ContractInstance, )(newOwner, txDataWithDefaults); return gas; }, getABIEncodedTransactionData(newOwner: string, txData: TxData = {}): string { const self = this as CollateralizerContract; const abiEncodedTransactionData = self.web3ContractInstance.transferOwnership.getData(); return abiEncodedTransactionData; }, }; public getAuthorizedCollateralizeAgents = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string[]> { const self = this as CollateralizerContract; const result = await promisify<string[]>( self.web3ContractInstance.getAuthorizedCollateralizeAgents.call, self.web3ContractInstance, )(); return result; }, }; async deploy(...args: any[]): Promise<any> { const wrapper = this; const rejected = false; return new Promise((resolve, reject) => { wrapper.web3ContractInstance.new( wrapper.defaults, (err: string, contract: Web3.ContractInstance) => { if (err) { reject(err); } else if (contract.address) { wrapper.web3ContractInstance = wrapper.web3ContractInstance.at( contract.address, ); wrapper.address = contract.address; resolve(); } }, ); }); } constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) { super(web3ContractInstance, defaults); classUtils.bindAll(this, ["web3ContractInstance", "defaults"]); } static async deployed(web3: Web3, defaults: Partial<TxData>): Promise<CollateralizerContract> { const web3Utils = new Web3Utils(web3); const currentNetwork = await web3Utils.getNetworkIdAsync(); const { abi, networks }: { abi: any; networks: any } = ContractArtifacts; if (networks[currentNetwork]) { const { address: contractAddress } = networks[currentNetwork]; const contractExists = await web3Utils.doesContractExistAtAddressAsync(contractAddress); if (contractExists) { const web3ContractInstance = web3.eth.contract(abi).at(contractAddress); return new CollateralizerContract(web3ContractInstance, defaults); } else { throw new Error( CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK( "Collateralizer", currentNetwork, ), ); } } else { throw new Error( CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK( "Collateralizer", currentNetwork, ), ); } } static async at( address: string, web3: Web3, defaults: Partial<TxData>, ): Promise<CollateralizerContract> { const web3Utils = new Web3Utils(web3); const { abi }: { abi: any } = ContractArtifacts; const contractExists = await web3Utils.doesContractExistAtAddressAsync(address); const currentNetwork = await web3Utils.getNetworkIdAsync(); if (contractExists) { const web3ContractInstance = web3.eth.contract(abi).at(address); return new CollateralizerContract(web3ContractInstance, defaults); } else { throw new Error( CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK( "Collateralizer", currentNetwork, ), ); } } } // tslint:disable:max-file-line-count
the_stack
import { define } from 'elements-sk/define'; import { html } from 'lit-html'; import * as d3Scale from 'd3-scale'; import * as d3Array from 'd3-array'; import * as ResizeObserverPolyfill from 'resize-observer-polyfill'; // This import is needed because https://github.com/Microsoft/TypeScript/issues/28502 import ResizeObserver from 'resize-observer-polyfill'; import { ElementSk } from '../../../infra-sk/modules/ElementSk'; import { KDTree, KDPoint } from './kd'; import { ticks } from './ticks'; // Prefix for trace ids that are not real traces, such as special_zero. Special // traces never receive focus and can't be clicked on. const SPECIAL = 'special'; export const MISSING_DATA_SENTINEL = 1e32; const NUM_Y_TICKS = 4; const HOVER_COLOR = '#8887'; // Note the alpha value. const ZOOM_RECT_COLOR = '#0007'; // Note the alpha value. const SUMMARY_LINE_WIDTH = 1; // px const DETAIL_LINE_WIDTH = 1; // px const AXIS_LINE_WIDTH = 1; // px const MIN_MOUSE_MOVE_FOR_ZOOM = 5; // px // As backup use a Polyfill for ResizeObserver if it isn't supported. This can // go away when Safari supports ResizeObserver: // https://caniuse.com/#feat=resizeobserver const LocalResizeObserver = ResizeObserver || ResizeObserverPolyfill; /** * @constant {Array} - Colors used for traces. */ const COLORS = [ '#000000', '#1B9E77', '#D95F02', '#7570B3', '#E7298A', '#66A61E', '#E6AB02', '#A6761D', '#666666', ]; // Contains linear scales to convert from source coordinates into // device/destination coordinates. export interface Range { x: d3Scale.ScaleLinear<number, number>; y: d3Scale.ScaleLinear<number, number>; } // A trace is drawn as a set of lines overdrawn with dots at each measurement. interface TracePaths { linePath: Path2D | null; dotsPath: Path2D | null; } /** @class Builds the Path2D objects that describe the trace and the dots for a given * set of scales. */ class PathBuilder { // TODO(jcgregorio) Change to TracePaths. private linePath: Path2D; private dotsPath: Path2D; // TODO(jcgregorio) Change to Range. private xRange: d3Scale.ScaleLinear<number, number>; private yRange: d3Scale.ScaleLinear<number, number>; private radius: number; constructor( xRange: d3Scale.ScaleLinear<number, number>, yRange: d3Scale.ScaleLinear<number, number>, radius: number, ) { this.xRange = xRange; this.yRange = yRange; this.radius = radius; this.linePath = new Path2D(); this.dotsPath = new Path2D(); } /** * Add a point to plot to the path. * * @param {Number} x - X coordinate in source coordinates. * @param {Number} y - Y coordinate in source coordinates. */ add(x: number, y: number) { // Convert source coord into canvas coords. const cx = this.xRange(x); const cy = this.yRange(y); if (x === 0) { this.linePath.moveTo(cx, cy); } else { this.linePath.lineTo(cx, cy); } this.dotsPath.moveTo(cx + this.radius, cy); this.dotsPath.arc(cx, cy, this.radius, 0, 2 * Math.PI); } /** * Returns the Arrays of Path2D objects that represent all the traces. * * @returns {Object} */ paths(): TracePaths { return { linePath: this.linePath, dotsPath: this.dotsPath, }; } } interface Point { x: number; y: number; } const invalidPoint: Point = { x: Number.MIN_SAFE_INTEGER, y: Number.MIN_SAFE_INTEGER, }; const pointIsValid = (p: Point): boolean => p.x !== invalidPoint.x; interface Rect extends Point { width: number; height: number; } /** * Convert rect in domain units into canvas coordinates using the given range. * * Presumes the rect was previously gotten from rectFromRangeInvert, so we don't * need to flip top and bottom. */ export const rectFromRange = (range: Range, rect: Rect): Rect => { const cleft = range.x(rect.x); const ctop = range.y(rect.y); const cright = range.x(rect.x + rect.width); const cbottom = range.y(rect.y + rect.height); return { x: cleft, y: ctop, width: cright - cleft, height: cbottom - ctop, }; }; /** * Convert rect in canvas units into domain units given the given range. * * Presumes this comes from a dragged out mouse region, which could be backwards * and/or upside down, so corrections are done to the corners. */ export const rectFromRangeInvert = (range: Range, rect: Rect): Rect => { let left = rect.x; let top = rect.y; let right = rect.x + rect.width; let bottom = rect.y + rect.height; if (right < left) { [left, right] = [right, left]; } // We do this backwards since range.y then does a second direction reversal, // i.e. Canvas y-axis is in the opposite direction of the y-axis we use in // the data units. if (top < bottom) { [bottom, top] = [top, bottom]; } return { x: range.x.invert(left), y: range.y.invert(top), width: range.x.invert(right) - range.x.invert(left), height: range.y.invert(bottom) - range.y.invert(top), }; }; const defaultRect: Rect = { x: 0, y: 0, width: 0, height: 0, }; interface SearchPoint extends Point { // Source coordinates. sx: number; sy: number; name: string; } /** * @class Builds a kdTree for searcing for nearest points to the mouse. */ class SearchBuilder { // TODO(jcgregorio) Change to Range. private xRange: d3Scale.ScaleLinear<number, number>; private yRange: d3Scale.ScaleLinear<number, number>; private points: SearchPoint[]; constructor( xRange: d3Scale.ScaleLinear<number, number>, yRange: d3Scale.ScaleLinear<number, number>, ) { this.xRange = xRange; this.yRange = yRange; this.points = []; } /** * Add a point to the kdTree. * * Note that add() stores the x and y coords as 'sx' and 'sy' in the KDTree nodes, * and the canvas coords, which are computed from sx and sy are stored as 'x' * and 'y' in the KDTree nodes. * * @param {Number} x - X coordinate in source coordinates. * @param {Number} y - Y coordinate in source coordinates. * @param {String} name - The trace name. */ add(x: number, y: number, name: string) { if (name.startsWith(SPECIAL)) { return; } // Convert source coord into canvas coords. const cx = this.xRange(x); const cy = this.yRange(y); this.points.push({ x: cx, y: cy, sx: x, sy: y, name, }); } /** * Returns a kdTree that contains all the points being plotted. * * @returns {KDTree} */ kdTree() { const distance = (a: KDPoint, b: KDPoint) => { const dx = a.x - b.x; const dy = a.y - b.y; return dx * dx + dy * dy; }; return new KDTree(this.points, distance, ['x', 'y']); } } // Returns true if pt is in rect. function inRect(pt: Point, rect: Rect): boolean { return ( pt.x >= rect.x && pt.x < rect.x + rect.width && pt.y >= rect.y && pt.y < rect.y + rect.height ); } // Restricts pt to rect. function clampToRect(pt: Point, rect: Rect) { if (pt.x < rect.x) { pt.x = rect.x; } else if (pt.x > rect.x + rect.width) { pt.x = rect.x + rect.width; } if (pt.y < rect.y) { pt.y = rect.y; } else if (pt.y > rect.y + rect.height) { pt.y = rect.y + rect.height; } } // Clip the given Canvas2D context to the given rect. function clipToRect(ctx: CanvasRenderingContext2D, rect: Rect) { ctx.beginPath(); ctx.rect(rect.x, rect.y, rect.width, rect.height); ctx.clip(); } // All the data for a single trace. interface LineData { name: string; values: number[]; color: string; detail: TracePaths; summary: TracePaths; } interface MousePosition { clientX: number; clientY: number; } interface MouseMoveRaw extends MousePosition { // Is the shift key being pressed as the mouse moves. shiftKey: boolean; } interface HoverPoint extends Point { // The trace id. name: string; } interface Label extends Point { // The text value of the label. text: string; } interface CrosshairPoint extends Point { shift: boolean; } // Common information for both the Summary and Detail display areas. interface Area { rect: Rect; axis: { path: Path2D; labels: Label[]; }; range: Range; } type SummaryArea = Area interface DetailArea extends Area { yaxis: { path: Path2D; labels: Label[]; }; } // Describes the zoom in terms of x-axis source values. type ZoomRange = [number, number] | null; // Used for both the trace_selected and trace_focused events. export interface PlotSimpleSkTraceEventDetails { x: number; y: number; // The trace id. name: string; } export interface PlotSimpleSkZoomEventDetails { xBegin: Date; xEnd: Date; } /** * The type of zoom being done, or 'no-zoom' if no zoom is currently being done. */ export type ZoomDragType = 'no-zoom' | 'details' | 'summary' export class PlotSimpleSk extends ElementSk { /** The location of the XBar. See the xbar property. */ private _xbar: number = -1; /** If true then draw dots on the traces. */ private _dots: boolean = true; /** The locations of the background bands. See bands property. */ private _bands: number[] = []; /** A map of trace names to 'true' of traces that are highlighted. */ private highlighted: { [key: string]: boolean } = {}; /** * The data we are plotting. * An array of objects of this form: * * { * name: key, * values: [1.0, 1.1, 0.9, ...], * detail: { * linePath: Path2D, * dotsPath: Path2D, * }, * summary: { * linePath: Path2D, * dotsPath: Path2D, * }, * } */ private lineData: LineData[] = []; /** An array of Date()'s the same length as the values in lineData. */ private labels: Date[] = []; /** * The current zoom, either null or an array of two values in source x * coordinates, e.g. [1, 12]. */ private _zoom: ZoomRange = null; /** The source coordinate where a zoom started. */ private zoomBegin: number = 0; /** The zoom rectangle on the details region. Stored in destination units. */ private zoomRect: Rect = defaultRect; /** * detailsZoomRangesStack and inactiveZoomRangesStack work together to manage * a stack of zoom levels. As new zoom ranges are dragged out they are pushed * onto detailsZoomRangesStack, and as the mouse wheel is turned we push/pop * zoom ranges between detailsZoomRangesStack and inactiveZoomRangesStack. * Scroll up means to zoom in, so we pop a rect off the inactive stack and * push it on the active stack. Scrolling down means to zoom out, so we do the * reverse, pop of the active stack and push it onto the inactive stack. * * When plotting we only look at the top of the active stack, i.e. the end of * detailsZoomRangesStack. * * detailsZoomRangesStack is a stack of zoom ranges, each zoom range in the * stack represents a smaller area than the zoom range below it on the stack. * Zoom ranges are stored in domain units. */ private detailsZoomRangesStack: Rect[] = []; /** * As we use the mouse wheel to move through zooms we store the ones we've * popped off of detailsZoomRangesStack here. * * Zoom ranges are stored in domain units. */ private inactiveDetailsZoomRangesStack: Rect[] = []; /** * True if we are currently drag zooming, i.e. the mouse is pressed and moving * over the summary. */ private inZoomDrag: ZoomDragType = 'no-zoom'; /** The Canvas 2D context of the traces canvas. */ private ctx: CanvasRenderingContext2D | null = null; /** The Canvas 2D context of the overlay canvas. */ private overlayCtx: CanvasRenderingContext2D | null = null; /** The window.devicePixelRatio. */ private scale: number = 1.0; /** * A copy of the clientX, clientY, and shiftKey values of mousemove events, * or null if a mousemove event hasn't occurred since the last time it was * processed. */ private mouseMoveRaw: MouseMoveRaw | null = null; /** * A kdTree for all the points being displayed, in source coordinates. Is * null if no traces are being displayed. */ private pointSearch: KDTree<SearchPoint> | null = null; /** * The closest trace point to the mouse. May be {} if no traces are * displayed or the mouse hasn't moved over the canvas yet. Has the form: * { * x: x, * y: y, * name: String, // name of trace * } */ private hoverPt: HoverPoint = { x: -1, y: -1, name: '', }; /** * The location of the crosshair in canvas coordinates. Of the form: * { * x: x, * y: y, * shift: Boolean, * } * * The value of shift is true of the shift key is being pressed while the * mouse moves. * } */ private crosshair: CrosshairPoint = { x: -1, y: -1, shift: false, }; /** All the info we need about the summary area. */ private summaryArea: SummaryArea = { rect: { x: 0, y: 0, width: 0, height: 0, }, axis: { path: new Path2D(), // Path2D. labels: [], // The labels and locations to draw them. {x, y, text}. }, range: { x: d3Scale.scaleLinear(), y: d3Scale.scaleLinear(), }, }; /** All the info we need about the details area. */ private detailArea: DetailArea = { rect: { x: 0, y: 0, width: 0, height: 0, }, axis: { path: new Path2D(), // Path2D. labels: [], // The labels and locations to draw them. {x, y, text}. }, yaxis: { path: new Path2D(), labels: [], // The labels and locations to draw them. {x, y, text}. }, range: { x: d3Scale.scaleLinear(), y: d3Scale.scaleLinear(), }, }; /** * A task to rebuild the k-d search tree used for finding the closest point * to the mouse. The actual value is a window.setTimer timerId or zero if no * task is scheduled. * * See https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/ * for details on tasks vs microtasks. */ private recalcSearchTask: number = 0; /** * A task to do the actual re-draw work of a zoom. The actual value is a * window.setTimer timerId or zero if no task is scheduled. * * See https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/ * for details on tasks vs microtasks. */ private zoomTask: number = 0; /** * A formatter that prints numbers nicely, such as adding commas. Used when * display the hover text. */ private numberFormatter: Intl.NumberFormat = new Intl.NumberFormat(); private SUMMARY_HEIGHT!: number; // px private SUMMARY_BAR_WIDTH!: number; // px private DETAIL_BAR_WIDTH!: number; // px private SUMMARY_HIGHLIGHT_LINE_WIDTH!: number; // px private DETAIL_RADIUS!: number; // px private SUMMARY_RADIUS!: number; // The radius of points in the summary area. (px) private MARGIN!: number; // The margin around the details and summary areas. (px) private LEFT_MARGIN!: number; // px private Y_AXIS_TICK_LENGTH!: number; // px private LABEL_FONT_SIZE!: number; // px private LABEL_MARGIN!: number; // px private LABEL_FONT!: string; // CSS font string. private ZOOM_BAR_LINE_WIDTH!: number; // px private HOVER_LINE_WIDTH!: number; // px private LABEL_COLOR!: string; // CSS color. private LABEL_BACKGROUND!: string; // CSS color. private CROSSHAIR_COLOR!: string; // CSS color. private BAND_COLOR!: string; // CSS color. constructor() { super(PlotSimpleSk.template); this._upgradeProperty('width'); this._upgradeProperty('height'); this._upgradeProperty('bands'); this._upgradeProperty('xbar'); this._upgradeProperty('hightlight'); this._upgradeProperty('zoom'); this.updateScaledMeasurements(); } // Note that in both of the canvas elements we are setting a CSS transform that // takes into account window.devicePixelRatio, that is, we are drawing to a // scale that matches the displays native resolution and then scaling that back // to fit on the page. Also see updateScaledMeasurements for how the device // pixel ratio affects all of our pixel calculations. private static template = (ele: PlotSimpleSk) => html` <canvas class="traces" width=${ele.width * window.devicePixelRatio} height=${ele.height * window.devicePixelRatio} style="transform-origin: 0 0; transform: scale(${1 / window.devicePixelRatio});" ></canvas> <canvas class="overlay" width=${ele.width * window.devicePixelRatio} height=${ele.height * window.devicePixelRatio} style="transform-origin: 0 0; transform: scale(${1 / window.devicePixelRatio});" ></canvas> `; connectedCallback(): void { super.connectedCallback(); this.render(); // We need to dynamically resize the canvas elements since they don't do // that themselves. const resizeObserver = new LocalResizeObserver((entries: ResizeObserverEntry[]) => { entries.forEach((entry) => { this.width = entry.contentRect.width; }); }); resizeObserver.observe(this); this.addEventListener('mousemove', (e) => { // Do as little as possible here. The raf() function will periodically // check if the mouse has moved and trigger the appropriate redraws. this.mouseMoveRaw = { clientX: e.clientX, clientY: e.clientY, shiftKey: e.shiftKey, }; }); this.addEventListener('mousedown', (e) => { const pt = this.eventToCanvasPt(e); // If you click in the summary area then begin zooming via drag. if (inRect(pt, this.summaryArea.rect!)) { const zx = this.summaryArea.range.x.invert(pt.x); this.inZoomDrag = 'summary'; this.zoomBegin = zx; this.zoom = [zx, zx + 0.01]; // Add a smidge to the second zx to avoid a degenerate detail plot. // Zooming via the summary area clears all details area zooms. this.detailsZoomRangesStack = []; this.inactiveDetailsZoomRangesStack = []; } if (inRect(pt, this.detailArea.rect!)) { this.inZoomDrag = 'details'; this.zoomRect = { x: pt.x, y: pt.y, width: 0, height: 0, }; } }); this.addEventListener('mouseup', () => { if (this.inZoomDrag !== 'no-zoom') { this.dispatchZoomEvent(); } if (this.inZoomDrag === 'details') { this.doDetailsZoom(); } this.inZoomDrag = 'no-zoom'; }); this.addEventListener('mouseleave', () => { if (this.inZoomDrag !== 'no-zoom') { this.dispatchZoomEvent(); } if (this.inZoomDrag === 'details') { this.doDetailsZoom(); } this.inZoomDrag = 'no-zoom'; }); this.addEventListener('wheel', (e: WheelEvent) => { e.stopPropagation(); e.preventDefault(); // If the wheel is spun while we are zoomed then move through the stack of // zoom ranges. if (this.detailsZoomRangesStack) { // Scrolling up on the scroll wheel gives e.deltaY a negative value. Up // means to scroll in, which means we want to take a rect from // inactiveDetailsZoomRangesStack and make it active by pushing it on // detailsZoomRangesStack. Down reverses the push/pop direction. if (e.deltaY < 0) { if (this.inactiveDetailsZoomRangesStack.length === 0) { return; } this.detailsZoomRangesStack.push(this.inactiveDetailsZoomRangesStack.pop()!); } else { if (this.detailsZoomRangesStack.length === 0) { return; } this.inactiveDetailsZoomRangesStack.push(this.detailsZoomRangesStack.pop()!); } this._zoomImpl(); } }); this.addEventListener('click', (e) => { const pt = this.eventToCanvasPt(e); if (!inRect(pt, this.detailArea.rect)) { return; } if (!this.pointSearch) { return; } const closest = this.pointSearch.nearest(pt); const detail = { x: closest.sx, y: closest.sy, name: closest.name, }; this.dispatchEvent( new CustomEvent<PlotSimpleSkTraceEventDetails>('trace_selected', { detail, bubbles: true, }), ); }); // If the user toggles the theme to/from darkmode then redraw. document.addEventListener('theme-chooser-toggle', () => { this.render(); }); window.requestAnimationFrame(this.raf.bind(this)); } attributeChangedCallback(_: string, oldValue: string, newValue: string): void { if (oldValue !== newValue) { this.render(); } } // Call this when the width or height attrs have changed. render(): void { this._render(); const canvas = this.querySelector<HTMLCanvasElement>('canvas.traces')!; const overlayCanvas = this.querySelector<HTMLCanvasElement>( 'canvas.overlay', )!; if (canvas) { this.ctx = canvas.getContext('2d'); this.overlayCtx = overlayCanvas.getContext('2d'); this.scale = window.devicePixelRatio; this.updateScaledMeasurements(); this.updateScaleRanges(); this.recalcDetailPaths(); this.recalcSummaryPaths(); this.drawTracesCanvas(); } } /** * Adds lines to be displayed. * * Any line id that begins with 'special' will be treated specially, * i.e. it will be presented as a dashed black line that doesn't * generate events. This may be useful for adding a line at y=0, * or a reference trace. * * @param {Object} lines - A map from trace id to arrays of y values. * @param {Array} labels - An array of Date objects the same length as the values. * */ addLines(lines: { [key: string]: number[] | null }, labels: Date[]): void { const keys = Object.keys(lines); if (keys.length === 0) { return; } const startedEmpty = this._zoom === null && this.lineData.length === 0; if (labels) { this.labels = labels; } // Convert into the format we will eventually expect. keys.forEach((key) => { // You can't encode NaN in JSON, so convert sentinel values to NaN here so // that dsArray functions will operate correctly. lines[key]!.forEach((x, i) => { if (x === MISSING_DATA_SENTINEL) { lines[key]![i] = NaN; } }); const values = lines[key]!; this.lineData.push({ name: key, values, color: 'black', detail: { linePath: null, dotsPath: null, }, summary: { linePath: null, dotsPath: null, }, }); }); // Set the zoom if we just added data for the first time. if (startedEmpty && this.lineData.length > 0) { this._zoom = [0, this.lineData[0].values.length - 1]; } this.updateScaleDomains(); this.recalcSummaryPaths(); this.recalcDetailPaths(); this.drawTracesCanvas(); } /** * Delete all the lines whose ids are in 'ids' from being plotted. * * @param {Array<string>} ids - The trace ids to remove. */ deleteLines(ids: string[]): void { this.lineData = this.lineData.filter( (line) => ids.indexOf(line.name) === -1, ); const onlySpecialLinesRemaining = this.lineData.every((line) => line.name.startsWith(SPECIAL)); if (onlySpecialLinesRemaining) { this.removeAll(); } else { this.updateScaleDomains(); this.recalcSummaryPaths(); this.recalcDetailPaths(); this.drawTracesCanvas(); } } /** * Remove all lines from plot. */ removeAll(): void { this.lineData = []; this.labels = []; this.hoverPt = { x: -1, y: -1, name: '', }; this.pointSearch = null; this.crosshair = { x: -1, y: -1, shift: false, }; this.mouseMoveRaw = null; this.highlighted = {}; this._xbar = -1; this._zoom = null; this.inZoomDrag = 'no-zoom'; this.detailsZoomRangesStack = []; this.inactiveDetailsZoomRangesStack = []; this.drawTracesCanvas(); } /** * Return the names of all the lines being plotted, not including SPECIAL * names. * */ getLineNames(): string[] { const ret: string[] = []; this.lineData.forEach((line) => { if (line.name.startsWith(SPECIAL)) { return; } ret.push(line.name); }); return ret; } /** * Update all the things that look like constants, but are really dependent on * window.devicePixelRatio or the current CSS styling. */ private updateScaledMeasurements() { // The height of the summary area. if (this.summary) { this.SUMMARY_HEIGHT = 50 * this.scale; // px } else { this.SUMMARY_HEIGHT = 0; } this.SUMMARY_BAR_WIDTH = 2 * this.scale; // px this.DETAIL_BAR_WIDTH = 3 * this.scale; // px this.SUMMARY_HIGHLIGHT_LINE_WIDTH = 3 * this.scale; // The radius of points in the details area. this.DETAIL_RADIUS = 3 * this.scale; // px // The radius of points in the summary area. this.SUMMARY_RADIUS = 2 * this.scale; // px // The margin around the details and summary areas. this.MARGIN = 32 * this.scale; // px this.LEFT_MARGIN = 2 * this.MARGIN; // px this.Y_AXIS_TICK_LENGTH = this.MARGIN / 4; // px this.LABEL_FONT_SIZE = 14 * this.scale; // px this.LABEL_MARGIN = 6 * this.scale; // px this.LABEL_FONT = `${this.LABEL_FONT_SIZE}px Roboto,Helvetica,Arial,Bitstream Vera Sans,sans-serif`; this.ZOOM_BAR_LINE_WIDTH = 3 * this.scale; // px this.HOVER_LINE_WIDTH = 1 * this.scale; // px this.CROSSHAIR_COLOR = '#f00'; this.BAND_COLOR = '#888'; // Pull out the computed colors. const style = getComputedStyle(this); // Start by using the computed colors. this.LABEL_COLOR = style.color; this.LABEL_BACKGROUND = style.backgroundColor; // Now override with CSS variables if they are present. const onBackground = style.getPropertyValue('--on-backgroud'); if (onBackground !== '') { this.LABEL_COLOR = onBackground; } const background = style.getPropertyValue('--backgroud'); if (background !== '') { this.LABEL_BACKGROUND = background; } const errorColor = style.getPropertyValue('--error'); if (errorColor !== '') { this.CROSSHAIR_COLOR = errorColor; } const secondaryColor = style.getPropertyValue('--secondary'); if (secondaryColor !== '') { this.BAND_COLOR = secondaryColor; } } private dispatchZoomEvent() { if (!this._zoom) { return; } let beginIndex = Math.floor(this._zoom[0] - 0.1); if (beginIndex < 0) { beginIndex = 0; } let endIndex = Math.ceil(this._zoom[1] + 0.1); if (endIndex > this.labels.length - 1) { endIndex = this.labels.length - 1; } const detail = { xBegin: this.labels[beginIndex], xEnd: this.labels[endIndex], }; this.dispatchEvent( new CustomEvent<PlotSimpleSkZoomEventDetails>('zoom', { detail, bubbles: true, }), ); } /** * Convert mouse event coordinates to a canvas point. * * @param {Object} e - A mouse event or an object that has the coords stored * in clientX and clientY. */ private eventToCanvasPt(e: MouseMoveRaw) { const clientRect = this.ctx!.canvas.getBoundingClientRect(); return { x: (e.clientX - clientRect.left) * this.scale, y: (e.clientY - clientRect.top) * this.scale, }; } // Handles requestAnimationFrame callbacks. private raf() { // Always queue up our next raf first. window.requestAnimationFrame(() => this.raf()); // Bail out early if the mouse hasn't moved. if (this.mouseMoveRaw === null) { return; } if (this.inZoomDrag === 'no-zoom') { const pt = this.eventToCanvasPt(this.mouseMoveRaw); // Update _hoverPt if needed. if (this.pointSearch) { const closest = this.pointSearch.nearest(pt); const detail = { x: closest.sx, y: closest.sy, name: closest.name, }; if (detail.x !== this.hoverPt.x || detail.y !== this.hoverPt.y) { this.hoverPt = detail; this.dispatchEvent( new CustomEvent<PlotSimpleSkTraceEventDetails>('trace_focused', { detail, bubbles: true, }), ); } } // Update crosshair. if (this.mouseMoveRaw.shiftKey && this.pointSearch) { this.crosshair = { x: pt.x, y: pt.y, shift: false, }; clampToRect(this.crosshair, this.detailArea.rect); } else { this.crosshair = { x: this.detailArea.range.x(this.hoverPt.x), y: this.detailArea.range.y(this.hoverPt.y), shift: true, }; } this.drawOverlayCanvas(); } else { // We are zooming. const pt = this.eventToCanvasPt(this.mouseMoveRaw); if (this.inZoomDrag === 'summary') { clampToRect(pt, this.summaryArea.rect); // x in source coordinates. const sx = this.summaryArea.range.x.invert(pt.x); // Set zoom, always making sure we go from lowest to highest. let zoom: ZoomRange = [this.zoomBegin, sx]; if (this.zoomBegin > sx) { zoom = [sx, this.zoomBegin]; } this.zoom = zoom; } else if (this.inZoomDrag === 'details') { clampToRect(pt, this.detailArea.rect); this.zoomRect.width = pt.x - this.zoomRect.x; this.zoomRect.height = pt.y - this.zoomRect.y; this.drawOverlayCanvas(); } this.mouseMoveRaw = null; } } /** * This is a super simple hash (h = h * 31 + x_i) currently used * for things like assigning colors to graphs based on trace ids. It * shouldn't be used for anything more serious than that. * * @param {String} s - A string to hash. * @return {Number} A 32 bit hash for the given string. */ private hashString(s: string) { let hash = 0; for (let i = s.length - 1; i >= 0; i--) { // eslint-disable-next-line no-bitwise hash = (hash << 5) - hash + s.charCodeAt(i); // eslint-disable-next-line no-bitwise hash |= 0; } return Math.abs(hash); } // Rebuilds our cache of Path2D objects we use for quick rendering. private recalcSummaryPaths() { this.lineData.forEach((line) => { // Need to pass in the x and y ranges, and the dot radius. if (line.name.startsWith(SPECIAL)) { line.color = this.LABEL_COLOR; } else { line.color = COLORS[(this.hashString(line.name) % 8) + 1]; } const summaryBuilder = new PathBuilder( this.summaryArea.range.x, this.summaryArea.range.y, this.SUMMARY_RADIUS, ); line.values.forEach((y, x) => { if (Number.isNaN(y)) { return; } summaryBuilder.add(x, y); }); line.summary = summaryBuilder.paths(); }); // Build summary x-axis. this.recalcXAxis(this.summaryArea, this.labels, 0); } // Rebuilds our cache of Path2D objects we use for quick rendering. private recalcDetailPaths() { const domain = this.detailArea.range.x.domain(); domain[0] = Math.floor(domain[0] - 0.1); domain[1] = Math.ceil(domain[1] + 0.1); this.lineData.forEach((line) => { // Need to pass in the x and y ranges, and the dot radius. if (line.name.startsWith(SPECIAL)) { line.color = this.LABEL_COLOR; } else { line.color = COLORS[(this.hashString(line.name) % 8) + 1]; } const detailBuilder = new PathBuilder( this.detailArea.range.x, this.detailArea.range.y, this.DETAIL_RADIUS, ); let previousPoint: Point = invalidPoint; let addedPointFromBeforeTheDomain = false; let addedPointFromAfterTheDomain = false; line.values.forEach((y, x) => { if (Number.isNaN(y)) { return; } // Always add in one point after the domain so we draw all visible line // segments. if (x > domain[1] && !addedPointFromAfterTheDomain) { detailBuilder.add(x, y); addedPointFromAfterTheDomain = true; return; } if (x < domain[0] || x > domain[1]) { previousPoint = { x: x, y: y }; return; } // Always add in one point before the domain so we draw all visible line // segments. if (!addedPointFromBeforeTheDomain) { if (pointIsValid(previousPoint)) { detailBuilder.add(previousPoint.x, previousPoint.y); } addedPointFromBeforeTheDomain = true; } detailBuilder.add(x, y); }); line.detail = detailBuilder.paths(); }); // Build detail x-axis. const detailDomain = this.detailArea.range.x.domain(); const labelOffset = Math.ceil(detailDomain[0]); const detailLabels = this.labels.slice( Math.ceil(detailDomain[0]), Math.floor(detailDomain[1] + 1), ); this.recalcXAxis(this.detailArea, detailLabels, labelOffset); // Build detail y-axis. this.recalcYAxis(this.detailArea); this.recalcSearch(); } // Recalculates the y-axis info. private recalcYAxis(area: DetailArea) { const yAxisPath = new Path2D(); const thinX = Math.floor(this.detailArea.rect.x) + 0.5; // Make sure we get a thin line. https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors#A_lineWidth_example yAxisPath.moveTo(thinX, this.detailArea.rect.y); yAxisPath.lineTo(thinX, this.detailArea.rect.y + this.detailArea.rect.height); area.yaxis.labels = []; area.range.y.ticks(NUM_Y_TICKS).forEach((t) => { const label = { x: 0, y: Math.floor(area.range.y(t)) + 0.5, text: `${this.numberFormatter.format(t)}`, }; area.yaxis.labels.push(label); yAxisPath.moveTo(thinX, label.y); yAxisPath.lineTo(thinX - this.Y_AXIS_TICK_LENGTH, label.y); }); area.yaxis.path = yAxisPath; } // Recalculates the x-axis info. private recalcXAxis(area: Area, labels: Date[], labelOffset: number) { const xAxisPath = new Path2D(); const thinY = Math.floor(area.rect.y) + 0.5; // Make sure we get a thin line. xAxisPath.moveTo(area.rect.x + 0.5, thinY); xAxisPath.lineTo(area.rect.x + 0.5 + area.rect.width, thinY); area.axis.labels = []; ticks(labels).forEach((tick) => { const label = { x: Math.floor(area.range.x(tick.x + labelOffset)) + 0.5, y: area.rect.y - this.MARGIN / 2, text: tick.text, }; area.axis.labels.push(label); xAxisPath.moveTo(label.x, area.rect.y); xAxisPath.lineTo(label.x, area.rect.y - this.MARGIN / 2); }); area.axis.path = xAxisPath; } // Rebuilds the kdTree we use to look up closest points. private recalcSearch() { if (this.recalcSearchTask) { return; } this.recalcSearchTask = window.setTimeout(() => this.recalcSearchImpl()); } private recalcSearchImpl() { if (this.zoomTask) { // If there is a pending zoom task then let that complete first since zooming // invalidates the search tree and it needs to be built again. this.recalcSearchTask = window.setTimeout(() => this.recalcSearchImpl()); return; } const domain = this.detailArea.range.x.domain(); domain[0] = Math.floor(domain[0] - 0.1); domain[1] = Math.ceil(domain[1] + 0.1); const searchBuilder = new SearchBuilder( this.detailArea.range.x, this.detailArea.range.y, ); this.lineData.forEach((line) => { line.values.forEach((y, x) => { if (Number.isNaN(y)) { return; } if (x < domain[0] || x > domain[1]) { return; } searchBuilder.add(x, y, line.name); }); }); this.pointSearch = searchBuilder.kdTree(); this.recalcSearchTask = 0; } // Updates all of our d3Scale domains. private updateScaleDomains() { let domainEnd = 1; if (this.lineData && this.lineData.length) { domainEnd = this.lineData[0].values.length - 1; } if (this._zoom) { this.detailArea.range.x = this.detailArea.range.x.domain(this._zoom); } else { this.detailArea.range.x = this.detailArea.range.x.domain([0, domainEnd]); } this.summaryArea.range.x = this.summaryArea.range.x.domain([0, domainEnd]); const domain = [ d3Array.min(this.lineData, (line) => d3Array.min(line.values))!, d3Array.max(this.lineData, (line) => d3Array.max(line.values))!, ]; this.detailArea.range.y = this.detailArea.range.y.domain(domain).nice(); this.summaryArea.range.y = this.summaryArea.range.y.domain(domain); // If detailsZoomRangeStacks is not empty then it overrides the detail // range. if (this.detailsZoomRangesStack.length > 0) { const zoom = this.detailsZoomRangesStack[this.detailsZoomRangesStack.length - 1]; this.detailArea.range.x = this.detailArea.range.x.domain([zoom.x, zoom.x + zoom.width]); this.detailArea.range.y = this.detailArea.range.y.domain([zoom.y, zoom.y + zoom.height]); } } // Updates all of our d3Scale ranges. Also updates detail and summary rects. private updateScaleRanges() { const width = this.ctx!.canvas.width; const height = this.ctx!.canvas.height; this.summaryArea.range.x = this.summaryArea.range.x.range([ this.LEFT_MARGIN, width - this.MARGIN, ]); this.summaryArea.range.y = this.summaryArea.range.y.range([ this.SUMMARY_HEIGHT + this.MARGIN, this.MARGIN, ]); this.detailArea.range.x = this.detailArea.range.x.range([ this.LEFT_MARGIN, width - this.MARGIN, ]); this.detailArea.range.y = this.detailArea.range.y.range([ height - this.MARGIN, this.SUMMARY_HEIGHT + 2 * this.MARGIN, ]); this.summaryArea.rect = { x: this.LEFT_MARGIN, y: this.MARGIN, width: width - this.MARGIN - this.LEFT_MARGIN, height: this.SUMMARY_HEIGHT, }; this.detailArea.rect = { x: this.LEFT_MARGIN, y: this.SUMMARY_HEIGHT + 2 * this.MARGIN, width: width - this.MARGIN - this.LEFT_MARGIN, height: height - this.SUMMARY_HEIGHT - 3 * this.MARGIN, }; } private doDetailsZoom() { // Don't actually do the zoom if the box isn't big enough. if ( Math.abs(this.zoomRect.width) < MIN_MOUSE_MOVE_FOR_ZOOM || Math.abs(this.zoomRect.height) < MIN_MOUSE_MOVE_FOR_ZOOM ) { return; } this.detailsZoomRangesStack.push( rectFromRangeInvert(this.detailArea.range, this.zoomRect), ); // We added a new zoom range, which means all the inactive zoom ranges are // no longer valid. this.inactiveDetailsZoomRangesStack = []; this.inZoomDrag = 'no-zoom'; this._zoomImpl(); } // Draw the contents of the overlay canvas. private drawOverlayCanvas() { // Always start by clearing the overlay. const width = this.overlayCtx!.canvas.width; const height = this.overlayCtx!.canvas.height; const ctx = this.overlayCtx!; ctx.clearRect(0, 0, width, height); if (this.summary) { // First clip to the summary region. ctx.save(); { // Block to scope save/restore. clipToRect(ctx, this.summaryArea.rect); // Draw the xbar. this.drawXBar(ctx, this.summaryArea, this.SUMMARY_BAR_WIDTH); // Draw the bands. this.drawBands(ctx, this.summaryArea, this.SUMMARY_BAR_WIDTH); // If detailsZoomRangeStacks is not empty then draw a box to indicate // the zoomed region. if (this.detailsZoomRangesStack.length > 0) { const zoom = this.detailsZoomRangesStack[this.detailsZoomRangesStack.length - 1]; this.drawZoomRect(ctx, rectFromRange(this.summaryArea.range, zoom)); } // Draw the zoom on the summary. if (this._zoom !== null) { ctx.lineWidth = this.ZOOM_BAR_LINE_WIDTH; ctx.strokeStyle = this.LABEL_COLOR; // Draw left bar. const leftx = this.summaryArea.range.x(this._zoom[0]); ctx.beginPath(); ctx.moveTo(leftx, this.summaryArea.rect.y); ctx.lineTo(leftx, this.summaryArea.rect.y + this.summaryArea.rect.height); // Draw right bar. const rightx = this.summaryArea.range.x(this._zoom[1]); ctx.moveTo(rightx, this.summaryArea.rect.y); ctx.lineTo(rightx, this.summaryArea.rect.y + this.summaryArea.rect.height); ctx.stroke(); // Draw gray boxes. ctx.fillStyle = ZOOM_RECT_COLOR; ctx.rect( this.summaryArea.rect.x, this.summaryArea.rect.y, leftx - this.summaryArea.rect.x, this.summaryArea.rect.height, ); ctx.rect( rightx, this.summaryArea.rect.y, this.summaryArea.rect.x + this.summaryArea.rect.width - rightx, this.summaryArea.rect.height, ); ctx.fill(); } } ctx.restore(); } // Now clip to the detail region. ctx.save(); { // Block to scope save/restore. clipToRect(ctx, this.detailArea.rect); // Draw the xbar. this.drawXBar(ctx, this.detailArea, this.DETAIL_BAR_WIDTH); // Draw the bands. this.drawBands(ctx, this.detailArea, this.DETAIL_BAR_WIDTH); // Draw highlighted lines. this.lineData.forEach((highlightedLine) => { if (!(highlightedLine.name in this.highlighted)) { return; } ctx.strokeStyle = highlightedLine.color; ctx.fillStyle = this.LABEL_BACKGROUND; ctx.lineWidth = this.SUMMARY_HIGHLIGHT_LINE_WIDTH; ctx.stroke(highlightedLine.detail.linePath!); if (this.dots) { ctx.fill(highlightedLine.detail.dotsPath!); ctx.stroke(highlightedLine.detail.dotsPath!); } }); // Find the line currently hovered over. let line = null; for (let i = 0; i < this.lineData.length; i++) { if (this.lineData[i].name === this.hoverPt.name) { line = this.lineData[i]; break; } } if (line !== null) { // Draw the hovered line and dots in a different color. ctx.strokeStyle = HOVER_COLOR; ctx.fillStyle = HOVER_COLOR; ctx.lineWidth = this.HOVER_LINE_WIDTH; // Just draw the dots, not the line. if (this.dots) { ctx.fill(line.detail.dotsPath!); ctx.stroke(line.detail.dotsPath!); } } if (this.inZoomDrag === 'details') { this.drawZoomRect(ctx, this.zoomRect); } else if (this.inZoomDrag === 'no-zoom') { // Draw the crosshairs. ctx.strokeStyle = this.CROSSHAIR_COLOR; ctx.lineWidth = AXIS_LINE_WIDTH; ctx.beginPath(); const thinX = Math.floor(this.crosshair.x) + 0.5; // Make sure we get a thin line. const thinY = Math.floor(this.crosshair.y) + 0.5; // Make sure we get a thin line. ctx.moveTo(this.detailArea.rect.x, thinY); ctx.lineTo(this.detailArea.rect.x + this.detailArea.rect.width, thinY); ctx.moveTo(thinX, this.detailArea.rect.y); ctx.lineTo(thinX, this.detailArea.rect.y + this.detailArea.rect.height); ctx.stroke(); // Y label at crosshair if shift is pressed. if (this.crosshair.shift) { // Draw the label offset from the crosshair. ctx.font = this.LABEL_FONT; ctx.textBaseline = 'bottom'; const label = this.numberFormatter.format(this.hoverPt.y); let x = this.crosshair.x + this.MARGIN; let y = this.crosshair.y - this.MARGIN; // First draw a white backdrop. ctx.fillStyle = this.LABEL_BACKGROUND; const meas = ctx.measureText(label); const labelHeight = this.LABEL_FONT_SIZE + 2 * this.LABEL_MARGIN; const labelWidth = meas.width + this.LABEL_MARGIN * 2; // Bump the text to different quadrants so it is always visible. if (y < this.detailArea.rect.y + this.detailArea.rect.height / 2) { y = this.crosshair.y + this.MARGIN; } if (x > this.detailArea.rect.x + this.detailArea.rect.width / 2) { x = x - labelWidth - 2 * this.MARGIN; } ctx.beginPath(); ctx.rect( x - this.LABEL_MARGIN, y + this.LABEL_MARGIN, labelWidth, -labelHeight, ); ctx.fill(); ctx.strokeStyle = this.LABEL_COLOR; ctx.beginPath(); ctx.rect( x - this.LABEL_MARGIN, y + this.LABEL_MARGIN, labelWidth, -labelHeight, ); ctx.stroke(); // Now draw text on top. ctx.fillStyle = this.LABEL_COLOR; ctx.fillText(label, x, y); } } } ctx.restore(); } // Draw a dashed rectangle for the details zoom. private drawZoomRect(ctx: CanvasRenderingContext2D, rect: Rect) { ctx.strokeStyle = this.LABEL_COLOR; ctx.lineWidth = 1; ctx.setLineDash([2, 2]); ctx.strokeRect(rect.x, rect.y, rect.width, rect.height); ctx.setLineDash([]); } // Draw the xbar in the given area with the given width. private drawXBar(ctx: CanvasRenderingContext2D, area: Area, width: number) { if (this.xbar === -1) { return; } ctx.lineWidth = width; ctx.strokeStyle = this.CROSSHAIR_COLOR; const bx = area.range.x(this._xbar); ctx.beginPath(); ctx.moveTo(bx, area.rect.y); ctx.lineTo(bx, area.rect.y + area.rect.height); ctx.stroke(); } // Draw the bands in the given area with the given width. private drawBands(ctx: CanvasRenderingContext2D, area: Area, width: number) { ctx.lineWidth = width; ctx.strokeStyle = this.BAND_COLOR; ctx.setLineDash([width, width]); ctx.beginPath(); this._bands.forEach((band) => { const bx = area.range.x(band); ctx.moveTo(bx, area.rect.y); ctx.lineTo(bx, area.rect.y + area.rect.height); }); ctx.stroke(); ctx.setLineDash([]); } // Draw everything on the trace canvas. // // Well, not quite everything, if we are drag zooming then we only redraw the // details and not the summary. private drawTracesCanvas() { const width = this.ctx!.canvas.width; const height = this.ctx!.canvas.height; const ctx = this.ctx!; if (this.inZoomDrag !== 'no-zoom') { ctx.clearRect( this.detailArea.rect.x - this.MARGIN, this.detailArea.rect.y - this.MARGIN, this.detailArea.rect.width + 2 * this.MARGIN, this.detailArea.rect.height + 2 * this.MARGIN, ); } else { ctx.clearRect(0, 0, width, height); } ctx.fillStyle = this.LABEL_BACKGROUND; // Draw the detail. ctx.save(); { // Block to scope save/restore. clipToRect(ctx, this.detailArea.rect); this.drawXAxis(ctx, this.detailArea); ctx.fillStyle = this.LABEL_BACKGROUND; this.lineData.forEach((line) => { ctx.strokeStyle = line.color; ctx.lineWidth = DETAIL_LINE_WIDTH; ctx.stroke(line.detail.linePath!); if (this.dots) { ctx.fill(line.detail.dotsPath!); ctx.stroke(line.detail.dotsPath!); } }); } ctx.restore(); this.drawXAxis(ctx, this.detailArea); if (this.inZoomDrag === 'no-zoom' && this.summary) { // Draw the summary. ctx.save(); { // Block to scope save/restore. clipToRect(ctx, this.summaryArea.rect); this.lineData.forEach((line) => { ctx.fillStyle = this.LABEL_BACKGROUND; ctx.strokeStyle = line.color; ctx.lineWidth = SUMMARY_LINE_WIDTH; ctx.stroke(line.summary.linePath!); if (this.dots) { ctx.fill(line.summary.dotsPath!); ctx.stroke(line.summary.dotsPath!); } }); } ctx.restore(); this.drawXAxis(ctx, this.summaryArea); } // Draw y-Axes. this.drawYAxis(ctx, this.detailArea); this.drawOverlayCanvas(); } // Draw a y-axis using the given context in the given area. private drawYAxis(ctx: CanvasRenderingContext2D, area: DetailArea) { ctx.strokeStyle = this.LABEL_COLOR; ctx.fillStyle = this.LABEL_COLOR; ctx.font = this.LABEL_FONT; ctx.textBaseline = 'middle'; ctx.lineWidth = AXIS_LINE_WIDTH; ctx.textAlign = 'right'; ctx.stroke(area.yaxis.path); const labelWidth = (3 * this.LEFT_MARGIN) / 4; area.yaxis.labels.forEach((label) => { ctx.fillText(label.text, label.x + labelWidth, label.y, labelWidth); }); } // Draw a x-axis using the given context in the given area. private drawXAxis(ctx: CanvasRenderingContext2D, area: Area) { ctx.strokeStyle = this.LABEL_COLOR; ctx.fillStyle = this.LABEL_COLOR; ctx.font = this.LABEL_FONT; ctx.textBaseline = 'middle'; ctx.lineWidth = AXIS_LINE_WIDTH; ctx.stroke(area.axis.path); area.axis.labels.forEach((label) => { ctx.fillText(label.text, label.x - 2, label.y); }); } /** * An array of trace ids to highlight. Set to [] to remove all highlighting. */ get highlight(): string[] { return Object.keys(this.highlighted); } set highlight(ids: string[]) { this.highlighted = {}; ids.forEach((name) => { this.highlighted[name] = true; }); this.drawOverlayCanvas(); } /** * Location to put a vertical marking bar on the graph. Can be set to -1 to * not display any bar. */ get xbar(): number { return this._xbar; } set xbar(value: number) { this._xbar = value; this.drawOverlayCanvas(); } /** * A list of x source offsets to place vertical markers. into labels. Can be * set to [] to remove all bands. */ get bands(): number[] { return this._bands; } set bands(bands: number[]) { if (!bands) { this._bands = []; } else { this._bands = bands; } this.drawOverlayCanvas(); } /** The zoom range, an array of two values in source x units. Can be set to * null to have no zoom. */ get zoom(): ZoomRange { return this._zoom; } set zoom(range: ZoomRange) { this._zoom = range; if (this.zoomTask) { return; } this.zoomTask = window.setTimeout(() => this._zoomImpl()); } private _zoomImpl() { this.updateScaleDomains(); this.recalcDetailPaths(); this.drawTracesCanvas(); this.zoomTask = 0; } static get observedAttributes(): string[] { return ['width', 'height', 'summary']; } /** Mirrors the width attribute. */ get width(): number { return +(this.getAttribute('width') || '0'); } set width(val: number) { this.setAttribute('width', val.toString()); } /** Mirrors the height attribute. */ get height(): number { return +(this.getAttribute('height') || '0'); } set height(val: number) { this.setAttribute('height', val.toString()); } /** @prop summary {string} Mirrors the summary attribute. */ get summary(): boolean { return this.hasAttribute('summary'); } set summary(val: boolean) { if (val) { this.setAttribute('summary', val.toString()); } else { this.removeAttribute('summary'); } } /** @prop nodots {boolean} Mirrors the nodots attribute. */ get dots(): boolean { return this._dots; } set dots(val: boolean) { this._dots = val; this.drawTracesCanvas(); } } define('plot-simple-sk', PlotSimpleSk);
the_stack
module android.graphics.drawable { import Resources = android.content.res.Resources; import Canvas = android.graphics.Canvas; import PixelFormat = android.graphics.PixelFormat; import Rect = android.graphics.Rect; import View = android.view.View; import System = java.lang.System; import Runnable = java.lang.Runnable; import Drawable = android.graphics.drawable.Drawable; import TypedArray = android.content.res.TypedArray; /** * A Drawable that manages an array of other Drawables. These are drawn in array * order, so the element with the largest index will be drawn on top. * <p> * It can be defined in an XML file with the <code>&lt;layer-list></code> element. * Each Drawable in the layer is defined in a nested <code>&lt;item></code>. For more * information, see the guide to <a * href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.</p> * * @attr ref android.R.styleable#LayerDrawableItem_left * @attr ref android.R.styleable#LayerDrawableItem_top * @attr ref android.R.styleable#LayerDrawableItem_right * @attr ref android.R.styleable#LayerDrawableItem_bottom * @attr ref android.R.styleable#LayerDrawableItem_drawable * @attr ref android.R.styleable#LayerDrawableItem_id */ export class LayerDrawable extends Drawable implements Drawable.Callback { mLayerState:LayerDrawable.LayerState; private mOpacityOverride:number = PixelFormat.UNKNOWN; private mPaddingL:number[]; private mPaddingT:number[]; private mPaddingR:number[]; private mPaddingB:number[]; private mTmpRect:Rect = new Rect(); private mMutated:boolean; /** * Create a new layer drawable with the specified list of layers and the specified * constant state. * * @param layers The list of layers to add to this drawable. * @param state The constant drawable state. */ constructor(layers:Drawable[], state:LayerDrawable.LayerState = null) { super(); let _as:LayerDrawable.LayerState = this.createConstantState(state); this.mLayerState = _as; if (_as.mNum > 0) { this.ensurePadding(); } if (layers != null) { let length:number = layers.length; let r:LayerDrawable.ChildDrawable[] = new Array<LayerDrawable.ChildDrawable>(length); for (let i:number = 0; i < length; i++) { r[i] = new LayerDrawable.ChildDrawable(); r[i].mDrawable = layers[i]; layers[i].setCallback(this); //this.mLayerState.mChildrenChangingConfigurations |= layers[i].getChangingConfigurations(); } this.mLayerState.mNum = length; this.mLayerState.mChildren = r; this.ensurePadding(); } } createConstantState(state:LayerDrawable.LayerState):LayerDrawable.LayerState { return new LayerDrawable.LayerState(state, this); } inflate(r:Resources, parser:HTMLElement):void { super.inflate(r, parser); let a:TypedArray = r.obtainAttributes(parser); this.mOpacityOverride = a.getInt("android:opacity", PixelFormat.UNKNOWN); this.setAutoMirrored(a.getBoolean("android:autoMirrored", false)); a.recycle(); //parse children for(let child of Array.from(parser.children)) { let item = <HTMLElement>child; if (item.tagName.toLowerCase() !== 'item') { continue; } a = r.obtainAttributes(item); let left:number = a.getDimensionPixelOffset("android:left", 0); let top:number = a.getDimensionPixelOffset("android:top", 0); let right:number = a.getDimensionPixelOffset("android:right", 0); let bottom:number = a.getDimensionPixelOffset("android:bottom", 0); let dr:Drawable = a.getDrawable("android:drawable"); let id:string = a.getString("android:id"); a.recycle(); if(!dr && item.children[0] instanceof HTMLElement){ dr = Drawable.createFromXml(r, <HTMLElement>item.children[0]); } if (!dr) { throw Error(`new XmlPullParserException(<item> tag requires a 'drawable' attribute or child tag defining a drawable)`); } this.addLayer(dr, id, left, top, right, bottom); } this.ensurePadding(); this.onStateChange(this.getState()); } /** * Add a new layer to this drawable. The new layer is identified by an id. * * @param layer The drawable to add as a layer. * @param id The id of the new layer. * @param left The left padding of the new layer. * @param top The top padding of the new layer. * @param right The right padding of the new layer. * @param bottom The bottom padding of the new layer. */ private addLayer(layer:Drawable, id:string, left = 0, top = 0, right = 0, bottom = 0):void { const st:LayerDrawable.LayerState = this.mLayerState; let N:number = st.mChildren != null ? st.mChildren.length : 0; let i:number = st.mNum; if (i >= N) { let nu:LayerDrawable.ChildDrawable[] = new Array<LayerDrawable.ChildDrawable>(N + 10); if (i > 0) { System.arraycopy(st.mChildren, 0, nu, 0, i); } st.mChildren = nu; } //this.mLayerState.mChildrenChangingConfigurations |= layer.getChangingConfigurations(); let childDrawable:LayerDrawable.ChildDrawable = new LayerDrawable.ChildDrawable(); st.mChildren[i] = childDrawable; childDrawable.mId = id; childDrawable.mDrawable = layer; childDrawable.mDrawable.setAutoMirrored(this.isAutoMirrored()); childDrawable.mInsetL = left; childDrawable.mInsetT = top; childDrawable.mInsetR = right; childDrawable.mInsetB = bottom; st.mNum++; layer.setCallback(this); } /** * Look for a layer with the given id, and returns its {@link Drawable}. * * @param id The layer ID to search for. * @return The {@link Drawable} of the layer that has the given id in the hierarchy or null. */ findDrawableByLayerId(id:string):Drawable { const layers:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; for (let i:number = this.mLayerState.mNum - 1; i >= 0; i--) { if (layers[i].mId == id) { return layers[i].mDrawable; } } return null; } /** * Sets the ID of a layer. * * @param index The index of the layer which will received the ID. * @param id The ID to assign to the layer. */ setId(index:number, id:string):void { this.mLayerState.mChildren[index].mId = id; } /** * Returns the number of layers contained within this. * @return The number of layers. */ getNumberOfLayers():number { return this.mLayerState.mNum; } /** * Returns the drawable at the specified layer index. * * @param index The layer index of the drawable to retrieve. * * @return The {@link android.graphics.drawable.Drawable} at the specified layer index. */ getDrawable(index:number):Drawable { return this.mLayerState.mChildren[index].mDrawable; } /** * Returns the id of the specified layer. * * @param index The index of the layer. * * @return The id of the layer or {@link android.view.View#NO_ID} if the layer has no id. */ getId(index:number):string { return this.mLayerState.mChildren[index].mId; } /** * Sets (or replaces) the {@link Drawable} for the layer with the given id. * * @param id The layer ID to search for. * @param drawable The replacement {@link Drawable}. * @return Whether the {@link Drawable} was replaced (could return false if * the id was not found). */ setDrawableByLayerId(id:string, drawable:Drawable):boolean { const layers:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; for (let i:number = this.mLayerState.mNum - 1; i >= 0; i--) { if (layers[i].mId == id) { if (layers[i].mDrawable != null) { if (drawable != null) { let bounds:Rect = layers[i].mDrawable.getBounds(); drawable.setBounds(bounds); } layers[i].mDrawable.setCallback(null); } if (drawable != null) { drawable.setCallback(this); } layers[i].mDrawable = drawable; return true; } } return false; } /** Specify modifiers to the bounds for the drawable[index]. left += l top += t; right -= r; bottom -= b; */ setLayerInset(index:number, l:number, t:number, r:number, b:number):void { let childDrawable:LayerDrawable.ChildDrawable = this.mLayerState.mChildren[index]; childDrawable.mInsetL = l; childDrawable.mInsetT = t; childDrawable.mInsetR = r; childDrawable.mInsetB = b; } drawableSizeChange(who:android.graphics.drawable.Drawable):void { let callback = this.getCallback(); if (callback != null && callback.drawableSizeChange) { callback.drawableSizeChange(this); } } // overrides from Drawable.Callback invalidateDrawable(who:Drawable):void { const callback:Drawable.Callback = this.getCallback(); if (callback != null) { callback.invalidateDrawable(this); } } scheduleDrawable(who:Drawable, what:Runnable, when:number):void { const callback:Drawable.Callback = this.getCallback(); if (callback != null) { callback.scheduleDrawable(this, what, when); } } unscheduleDrawable(who:Drawable, what:Runnable):void { const callback:Drawable.Callback = this.getCallback(); if (callback != null) { callback.unscheduleDrawable(this, what); } } // overrides from Drawable draw(canvas:Canvas):void { const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; const N:number = this.mLayerState.mNum; for (let i:number = 0; i < N; i++) { array[i].mDrawable.draw(canvas); } } //getChangingConfigurations():number { // return super.getChangingConfigurations() | this.mLayerState.mChangingConfigurations | this.mLayerState.mChildrenChangingConfigurations; //} getPadding(padding:Rect):boolean { // Arbitrarily get the padding from the first image. // Technically we should maybe do something more intelligent, // like take the max padding of all the images. padding.left = 0; padding.top = 0; padding.right = 0; padding.bottom = 0; const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; const N:number = this.mLayerState.mNum; for (let i:number = 0; i < N; i++) { this.reapplyPadding(i, array[i]); padding.left += this.mPaddingL[i]; padding.top += this.mPaddingT[i]; padding.right += this.mPaddingR[i]; padding.bottom += this.mPaddingB[i]; } return true; } setVisible(visible:boolean, restart:boolean):boolean { let changed:boolean = super.setVisible(visible, restart); const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; const N:number = this.mLayerState.mNum; for (let i:number = 0; i < N; i++) { array[i].mDrawable.setVisible(visible, restart); } return changed; } setDither(dither:boolean):void { const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; const N:number = this.mLayerState.mNum; for (let i:number = 0; i < N; i++) { array[i].mDrawable.setDither(dither); } } setAlpha(alpha:number):void { const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; const N:number = this.mLayerState.mNum; for (let i:number = 0; i < N; i++) { array[i].mDrawable.setAlpha(alpha); } } getAlpha():number { const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; if (this.mLayerState.mNum > 0) { // All layers should have the same alpha set on them - just return the first one return array[0].mDrawable.getAlpha(); } else { return super.getAlpha(); } } //setColorFilter(cf:ColorFilter):void { // const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; // const N:number = this.mLayerState.mNum; // for (let i:number = 0; i < N; i++) { // array[i].mDrawable.setColorFilter(cf); // } //} /** * Sets the opacity of this drawable directly, instead of collecting the states from * the layers * * @param opacity The opacity to use, or {@link PixelFormat#UNKNOWN PixelFormat.UNKNOWN} * for the default behavior * * @see PixelFormat#UNKNOWN * @see PixelFormat#TRANSLUCENT * @see PixelFormat#TRANSPARENT * @see PixelFormat#OPAQUE */ setOpacity(opacity:number):void { this.mOpacityOverride = opacity; } getOpacity():number { if (this.mOpacityOverride != PixelFormat.UNKNOWN) { return this.mOpacityOverride; } return this.mLayerState.getOpacity(); } setAutoMirrored(mirrored:boolean):void { this.mLayerState.mAutoMirrored = mirrored; const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; const N:number = this.mLayerState.mNum; for (let i:number = 0; i < N; i++) { array[i].mDrawable.setAutoMirrored(mirrored); } } isAutoMirrored():boolean { return this.mLayerState.mAutoMirrored; } isStateful():boolean { return this.mLayerState.isStateful(); } protected onStateChange(state:number[]):boolean { const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; const N:number = this.mLayerState.mNum; let paddingChanged:boolean = false; let changed:boolean = false; for (let i:number = 0; i < N; i++) { const r:LayerDrawable.ChildDrawable = array[i]; if (r.mDrawable.setState(state)) { changed = true; } if (this.reapplyPadding(i, r)) { paddingChanged = true; } } if (paddingChanged) { this.onBoundsChange(this.getBounds()); } return changed; } protected onLevelChange(level:number):boolean { const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; const N:number = this.mLayerState.mNum; let paddingChanged:boolean = false; let changed:boolean = false; for (let i:number = 0; i < N; i++) { const r:LayerDrawable.ChildDrawable = array[i]; if (r.mDrawable.setLevel(level)) { changed = true; } if (this.reapplyPadding(i, r)) { paddingChanged = true; } } if (paddingChanged) { this.onBoundsChange(this.getBounds()); } return changed; } protected onBoundsChange(bounds:Rect):void { const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; const N:number = this.mLayerState.mNum; let padL:number = 0, padT:number = 0, padR:number = 0, padB:number = 0; for (let i:number = 0; i < N; i++) { const r:LayerDrawable.ChildDrawable = array[i]; r.mDrawable.setBounds(bounds.left + r.mInsetL + padL, bounds.top + r.mInsetT + padT, bounds.right - r.mInsetR - padR, bounds.bottom - r.mInsetB - padB); padL += this.mPaddingL[i]; padR += this.mPaddingR[i]; padT += this.mPaddingT[i]; padB += this.mPaddingB[i]; } } getIntrinsicWidth():number { let width:number = -1; const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; const N:number = this.mLayerState.mNum; let padL:number = 0, padR:number = 0; for (let i:number = 0; i < N; i++) { const r:LayerDrawable.ChildDrawable = array[i]; let w:number = r.mDrawable.getIntrinsicWidth() + r.mInsetL + r.mInsetR + padL + padR; if (w > width) { width = w; } padL += this.mPaddingL[i]; padR += this.mPaddingR[i]; } return width; } getIntrinsicHeight():number { let height:number = -1; const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; const N:number = this.mLayerState.mNum; let padT:number = 0, padB:number = 0; for (let i:number = 0; i < N; i++) { const r:LayerDrawable.ChildDrawable = array[i]; let h:number = r.mDrawable.getIntrinsicHeight() + r.mInsetT + r.mInsetB + padT + padB; if (h > height) { height = h; } padT += this.mPaddingT[i]; padB += this.mPaddingB[i]; } return height; } private reapplyPadding(i:number, r:LayerDrawable.ChildDrawable):boolean { const rect:Rect = this.mTmpRect; r.mDrawable.getPadding(rect); if (rect.left != this.mPaddingL[i] || rect.top != this.mPaddingT[i] || rect.right != this.mPaddingR[i] || rect.bottom != this.mPaddingB[i]) { this.mPaddingL[i] = rect.left; this.mPaddingT[i] = rect.top; this.mPaddingR[i] = rect.right; this.mPaddingB[i] = rect.bottom; return true; } return false; } private ensurePadding():void { const N:number = this.mLayerState.mNum; if (this.mPaddingL != null && this.mPaddingL.length >= N) { return; } this.mPaddingL = androidui.util.ArrayCreator.newNumberArray(N); this.mPaddingT = androidui.util.ArrayCreator.newNumberArray(N); this.mPaddingR = androidui.util.ArrayCreator.newNumberArray(N); this.mPaddingB = androidui.util.ArrayCreator.newNumberArray(N); //androidui: fill 0 to new array (like java) for (var i = 0; i < N; i++) { this.mPaddingL[i] = 0; this.mPaddingT[i] = 0; this.mPaddingR[i] = 0; this.mPaddingB[i] = 0; } } getConstantState():Drawable.ConstantState { if (this.mLayerState.canConstantState()) { //this.mLayerState.mChangingConfigurations = this.getChangingConfigurations(); return this.mLayerState; } return null; } mutate():Drawable { if (!this.mMutated && super.mutate() == this) { this.mLayerState = this.createConstantState(this.mLayerState); const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; const N:number = this.mLayerState.mNum; for (let i:number = 0; i < N; i++) { array[i].mDrawable.mutate(); } this.mMutated = true; } return this; } ///** @hide */ //setLayoutDirection(layoutDirection:number):void { // const array:LayerDrawable.ChildDrawable[] = this.mLayerState.mChildren; // const N:number = this.mLayerState.mNum; // for (let i:number = 0; i < N; i++) { // array[i].mDrawable.setLayoutDirection(layoutDirection); // } // super.setLayoutDirection(layoutDirection); //} } export module LayerDrawable { export class ChildDrawable { mDrawable:Drawable; mInsetL:number = 0; mInsetT:number = 0; mInsetR:number = 0; mInsetB:number = 0; mId:string; } export class LayerState implements Drawable.ConstantState { mNum:number = 0; mChildren:LayerDrawable.ChildDrawable[]; //mChangingConfigurations:number = 0; //mChildrenChangingConfigurations:number = 0; private mHaveOpacity:boolean = false; private mOpacity:number = 0; private mHaveStateful:boolean = false; private mStateful:boolean; private mCheckedConstantState:boolean; private mCanConstantState:boolean; private mAutoMirrored:boolean; constructor(orig:LayerState, owner:LayerDrawable) { if (orig != null) { const origChildDrawable:LayerDrawable.ChildDrawable[] = orig.mChildren; const N:number = orig.mNum; this.mNum = N; this.mChildren = new Array<LayerDrawable.ChildDrawable>(N); //this.mChangingConfigurations = orig.mChangingConfigurations; //this.mChildrenChangingConfigurations = orig.mChildrenChangingConfigurations; for (let i:number = 0; i < N; i++) { const r:LayerDrawable.ChildDrawable = this.mChildren[i] = new LayerDrawable.ChildDrawable(); const or:LayerDrawable.ChildDrawable = origChildDrawable[i]; //if (res != null) { // r.mDrawable = or.mDrawable.getConstantState().newDrawable(res); //} else { r.mDrawable = or.mDrawable.getConstantState().newDrawable(); //} r.mDrawable.setCallback(owner); //r.mDrawable.setLayoutDirection(or.mDrawable.getLayoutDirection()); r.mInsetL = or.mInsetL; r.mInsetT = or.mInsetT; r.mInsetR = or.mInsetR; r.mInsetB = or.mInsetB; r.mId = or.mId; } this.mHaveOpacity = orig.mHaveOpacity; this.mOpacity = orig.mOpacity; this.mHaveStateful = orig.mHaveStateful; this.mStateful = orig.mStateful; this.mCheckedConstantState = this.mCanConstantState = true; this.mAutoMirrored = orig.mAutoMirrored; } else { this.mNum = 0; this.mChildren = null; } } newDrawable():Drawable { return new LayerDrawable(null, this); } //getChangingConfigurations():number { // return this.mChangingConfigurations; //} getOpacity():number { if (this.mHaveOpacity) { return this.mOpacity; } const N:number = this.mNum; let op:number = N > 0 ? this.mChildren[0].mDrawable.getOpacity() : PixelFormat.TRANSPARENT; for (let i:number = 1; i < N; i++) { op = Drawable.resolveOpacity(op, this.mChildren[i].mDrawable.getOpacity()); } this.mOpacity = op; this.mHaveOpacity = true; return op; } isStateful():boolean { if (this.mHaveStateful) { return this.mStateful; } let stateful:boolean = false; const N:number = this.mNum; for (let i:number = 0; i < N; i++) { if (this.mChildren[i].mDrawable.isStateful()) { stateful = true; break; } } this.mStateful = stateful; this.mHaveStateful = true; return stateful; } canConstantState():boolean { if (!this.mCheckedConstantState && this.mChildren != null) { this.mCanConstantState = true; const N:number = this.mNum; for (let i:number = 0; i < N; i++) { if (this.mChildren[i].mDrawable.getConstantState() == null) { this.mCanConstantState = false; break; } } this.mCheckedConstantState = true; } return this.mCanConstantState; } } } }
the_stack
import { GLCapabilityType, IPlatformRenderTarget, Logger, RenderBufferDepthFormat, RenderColorTexture, RenderDepthTexture, RenderTarget, TextureCubeFace } from "@oasis-engine/core"; import { GLRenderColorTexture } from "./GLRenderColorTexture"; import { GLRenderDepthTexture } from "./GLRenderDepthTexture"; import { GLTexture } from "./GLTexture"; import { WebGLRenderer } from "./WebGLRenderer"; /** * The render target in WebGL platform is used for off-screen rendering. */ export class GLRenderTarget implements IPlatformRenderTarget { private _gl: WebGLRenderingContext & WebGL2RenderingContext; private _isWebGL2: boolean; private _target: RenderTarget; private _frameBuffer: WebGLFramebuffer; private _MSAAFrameBuffer: WebGLFramebuffer | null; private _depthRenderBuffer: WebGLRenderbuffer | null; private _MSAAColorRenderBuffers: WebGLRenderbuffer[] = []; private _MSAADepthRenderBuffer: WebGLRenderbuffer | null; private _oriDrawBuffers: GLenum[]; private _blitDrawBuffers: GLenum[] | null; private _curMipLevel: number = 0; /** * Create render target in WebGL platform. */ constructor(rhi: WebGLRenderer, target: RenderTarget) { this._gl = rhi.gl as WebGLRenderingContext & WebGL2RenderingContext; this._isWebGL2 = rhi.isWebGL2; this._target = target; /** @ts-ignore */ const { _colorTextures, _depth, width, height } = target; /** todo * MRT + Cube + [,MSAA] * MRT + MSAA */ if (!(_depth instanceof RenderDepthTexture) && !GLTexture._supportRenderBufferDepthFormat(_depth, rhi, false)) { throw new Error(`RenderBufferDepthFormat is not supported:${RenderBufferDepthFormat[_depth]}`); } if (_colorTextures.length > 1 && !rhi.canIUse(GLCapabilityType.drawBuffers)) { throw new Error("MRT is not supported"); } if (_colorTextures.some((v: RenderColorTexture) => v.width !== width || v.height !== height)) { throw new Error("RenderColorTexture's size must as same as RenderTarget"); } if (_depth instanceof RenderDepthTexture && (_depth.width !== width || _depth.height !== height)) { throw new Error("RenderDepthTexture's size must as same as RenderTarget"); } // todo: necessary to support MRT + Cube + [,MSAA] ? if (_colorTextures.length > 1 && _colorTextures.some((v: RenderColorTexture) => v.isCube)) { throw new Error("MRT+Cube+[,MSAA] is not supported"); } const maxAntiAliasing = rhi.capability.maxAntiAliasing; if (target.antiAliasing > maxAntiAliasing) { Logger.warn(`MSAA antiAliasing exceeds the limit and is automatically downgraded to:${maxAntiAliasing}`); /** @ts-ignore */ target._antiAliasing = maxAntiAliasing; } this._frameBuffer = this._gl.createFramebuffer(); // bind main FBO this._bindMainFBO(); // bind MSAA FBO if (target.antiAliasing > 1) { this._MSAAFrameBuffer = this._gl.createFramebuffer(); this._bindMSAAFBO(); } } /** * Set which face and mipLevel of the cube texture to render to. * @param faceIndex - Cube texture face * @param mipLevel - Set mip level the data want to write */ setRenderTargetInfo(faceIndex: TextureCubeFace, mipLevel: number): void { const { _gl: gl, _target: target } = this; const { depthTexture } = target; const colorTexture = target.getColorTexture(0); const mipChanged = mipLevel !== this._curMipLevel; gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer); if (colorTexture) { const isCube = colorTexture.isCube; if (mipChanged || isCube) { gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, isCube ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D, /** @ts-ignore */ (colorTexture._platformTexture as GLRenderColorTexture)._glTexture, mipLevel ); } } if (depthTexture) { const isCube = depthTexture.isCube; if (mipChanged || isCube) { /** @ts-ignore */ const { _platformTexture: platformTexture } = depthTexture; gl.framebufferTexture2D( gl.FRAMEBUFFER, platformTexture._formatDetail.attachment, isCube ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D, platformTexture._glTexture, mipLevel ); } } else { if (mipChanged) { // @ts-ignore const { internalFormat } = GLTexture._getRenderBufferDepthFormatDetail(target._depth, gl, this._isWebGL2); gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthRenderBuffer); gl.renderbufferStorage(gl.RENDERBUFFER, internalFormat, target.width >> mipLevel, target.height >> mipLevel); } } this._curMipLevel = mipLevel; // revert current activated render target this._activeRenderTarget(); } /** * Blit FBO. */ blitRenderTarget(): void { if (!this._MSAAFrameBuffer) return; const gl = this._gl; const mask = gl.COLOR_BUFFER_BIT | (this._target.depthTexture ? gl.DEPTH_BUFFER_BIT : 0); const { colorTextureCount, width, height } = this._target; gl.bindFramebuffer(gl.READ_FRAMEBUFFER, this._MSAAFrameBuffer); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, this._frameBuffer); for (let textureIndex = 0; textureIndex < colorTextureCount; textureIndex++) { const attachment = gl.COLOR_ATTACHMENT0 + textureIndex; this._blitDrawBuffers[textureIndex] = attachment; gl.readBuffer(attachment); gl.drawBuffers(this._blitDrawBuffers); gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST); this._blitDrawBuffers[textureIndex] = gl.NONE; } gl.bindFramebuffer(gl.FRAMEBUFFER, null); } /** * Destroy render target. */ destroy(): void { const gl = this._gl; this._frameBuffer && gl.deleteFramebuffer(this._frameBuffer); this._depthRenderBuffer && gl.deleteRenderbuffer(this._depthRenderBuffer); this._MSAAFrameBuffer && gl.deleteFramebuffer(this._MSAAFrameBuffer); this._MSAADepthRenderBuffer && gl.deleteRenderbuffer(this._MSAADepthRenderBuffer); for (let i = 0; i < this._MSAAColorRenderBuffers.length; i++) { gl.deleteRenderbuffer(this._MSAAColorRenderBuffers[i]); } this._frameBuffer = null; this._depthRenderBuffer = null; this._MSAAFrameBuffer = null; this._MSAAColorRenderBuffers.length = 0; this._MSAADepthRenderBuffer = null; } /** * Activate this RenderTarget. * @internal * @remarks * If MSAA is turned on, MSAA FBO is activated, and then this._blitRenderTarget() is performed to exchange FBO. * If MSAA is not turned on, activate the main FBO. */ _activeRenderTarget(): void { const gl = this._gl; if (this._MSAAFrameBuffer) { gl.bindFramebuffer(gl.FRAMEBUFFER, this._MSAAFrameBuffer); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer); } } private _bindMainFBO(): void { const gl = this._gl; const isWebGL2: boolean = this._isWebGL2; /** @ts-ignore */ const { _depth, colorTextureCount, width, height } = this._target; const drawBuffers = new Array(colorTextureCount); gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer); /** color render buffer */ for (let i = 0; i < colorTextureCount; i++) { const colorTexture = this._target.getColorTexture(i); const attachment = gl.COLOR_ATTACHMENT0 + i; drawBuffers[i] = attachment; if (!colorTexture.isCube) { gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, /** @ts-ignore */ (colorTexture._platformTexture as GLRenderColorTexture)._glTexture, 0 ); } } if (colorTextureCount > 1) { gl.drawBuffers(drawBuffers); } this._oriDrawBuffers = drawBuffers; /** depth render buffer */ if (_depth !== null) { if (_depth instanceof RenderDepthTexture) { if (!_depth.isCube) { gl.framebufferTexture2D( gl.FRAMEBUFFER, /** @ts-ignore */ (_depth._platformTexture as GLRenderDepthTexture)._formatDetail.attachment, gl.TEXTURE_2D, /** @ts-ignore */ (_depth._platformTexture as GLRenderDepthTexture)._glTexture, 0 ); } } else if (this._target.antiAliasing <= 1) { const { internalFormat, attachment } = GLTexture._getRenderBufferDepthFormatDetail(_depth, gl, isWebGL2); const depthRenderBuffer = gl.createRenderbuffer(); this._depthRenderBuffer = depthRenderBuffer; gl.bindRenderbuffer(gl.RENDERBUFFER, depthRenderBuffer); gl.renderbufferStorage(gl.RENDERBUFFER, internalFormat, width, height); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, depthRenderBuffer); } } gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.bindRenderbuffer(gl.RENDERBUFFER, null); } private _bindMSAAFBO(): void { const gl = this._gl; const isWebGL2 = this._isWebGL2; const MSAADepthRenderBuffer = gl.createRenderbuffer(); /** @ts-ignore */ const { _depth, colorTextureCount, antiAliasing, width, height } = this._target; this._blitDrawBuffers = new Array(colorTextureCount); this._MSAADepthRenderBuffer = MSAADepthRenderBuffer; gl.bindFramebuffer(gl.FRAMEBUFFER, this._MSAAFrameBuffer); // prepare MRT+MSAA color RBOs for (let i = 0; i < colorTextureCount; i++) { const MSAAColorRenderBuffer = gl.createRenderbuffer(); this._MSAAColorRenderBuffers[i] = MSAAColorRenderBuffer; this._blitDrawBuffers[i] = gl.NONE; gl.bindRenderbuffer(gl.RENDERBUFFER, MSAAColorRenderBuffer); gl.renderbufferStorageMultisample( gl.RENDERBUFFER, antiAliasing, /** @ts-ignore */ (this._target.getColorTexture(i)._platformTexture as GLRenderColorTexture)._formatDetail.internalFormat, width, height ); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, MSAAColorRenderBuffer); } gl.drawBuffers(this._oriDrawBuffers); // prepare MSAA depth RBO if (_depth !== null) { const { internalFormat, attachment } = _depth instanceof RenderDepthTexture ? /** @ts-ignore */ (_depth._platformTexture as GLRenderDepthTexture)._formatDetail : GLTexture._getRenderBufferDepthFormatDetail(_depth, gl, isWebGL2); gl.bindRenderbuffer(gl.RENDERBUFFER, MSAADepthRenderBuffer); gl.renderbufferStorageMultisample(gl.RENDERBUFFER, antiAliasing, internalFormat, width, height); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, MSAADepthRenderBuffer); } this._checkFrameBuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.bindRenderbuffer(gl.RENDERBUFFER, null); } private _checkFrameBuffer(): void { const gl = this._gl; const isWebGL2 = this._isWebGL2; const e = gl.checkFramebufferStatus(gl.FRAMEBUFFER); switch (e) { case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: throw new Error( "The attachment types are mismatched or not all framebuffer attachment points are framebuffer attachment complete" ); case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: throw new Error("There is no attachment"); case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: throw new Error(" Height and width of the attachment are not the same."); case gl.FRAMEBUFFER_UNSUPPORTED: throw new Error( "The format of the attachment is not supported or if depth and stencil attachments are not the same renderbuffer" ); } if (isWebGL2 && e === gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE) { throw new Error( "The values of gl.RENDERBUFFER_SAMPLES are different among attached renderbuffers, or are non-zero if the attached images are a mix of renderbuffers and textures." ); } } }
the_stack
import React, { useContext, useState } from "react"; import { useActor } from "@xstate/react"; import Modal from "react-bootstrap/Modal"; import close from "assets/icons/close.png"; import sunflowerRock from "assets/nfts/sunflower_rock.png"; import sunflowerTombstone from "assets/nfts/sunflower_tombstone.png"; import sunflowerStatue from "assets/nfts/sunflower_statue.png"; import potatoStatue from "assets/nfts/potato_statue.png"; import christmasTree from "assets/nfts/christmas_tree.png"; import dog from "assets/nfts/farm_dog.gif"; import cat from "assets/nfts/farm_cat.gif"; import gnome from "assets/nfts/gnome.gif"; import nancy from "assets/nfts/nancy.png"; import scarecrow from "assets/nfts/scarecrow.png"; import kuebiko from "assets/nfts/kuebiko.gif"; import goblinKing from "assets/nfts/goblin_king.png"; import fountain from "assets/nfts/fountain.gif"; import nyonStatue from "assets/nfts/nyon_statue.png"; import homelessTent from "assets/nfts/homeless_tent.png"; import farmerBath from "assets/nfts/farmer_bath.png"; import swimmer from "assets/npcs/swimmer.gif"; import beaver from "assets/nfts/beaver.gif"; import apprentice from "assets/nfts/apprentice_beaver.gif"; import foreman from "assets/nfts/construction_beaver.gif"; import easterBunny from "assets/nfts/easter/easter_bunny_eggs.gif"; import { GRID_WIDTH_PX } from "../lib/constants"; import { Context } from "../GameProvider"; import { Section } from "lib/utils/hooks/useScrollIntoView"; import { Flags } from "./Flags"; import { Inventory } from "../types/game"; import { Panel } from "components/ui/Panel"; import { fountainAudio } from "lib/utils/sfx"; import { Sign } from "./Sign"; // Only show 1 scarecrow at a time export const Scarecrows: React.FC<{ inventory: Inventory }> = ({ inventory, }) => { if (inventory.Kuebiko) { return ( <img style={{ width: `${GRID_WIDTH_PX * 2}px`, }} src={kuebiko} alt="Scarecrow" /> ); } if (inventory.Scarecrow) { return ( <img style={{ width: `${GRID_WIDTH_PX * 1.3}px`, }} src={scarecrow} alt="Scarecrow" /> ); } if (inventory.Nancy) { return ( <img style={{ width: `${GRID_WIDTH_PX * 1.2}px`, }} src={nancy} alt="Scarecrow" /> ); } return null; }; export const Beavers: React.FC<{ inventory: Inventory }> = ({ inventory }) => { if (inventory["Foreman Beaver"]) { return ( <img style={{ width: `${GRID_WIDTH_PX * 1.2}px`, }} src={foreman} alt="Foreman Beaver" /> ); } if (inventory["Apprentice Beaver"]) { return ( <img style={{ width: `${GRID_WIDTH_PX * 1.2}px`, }} src={apprentice} alt="Apprentice Beaver" /> ); } if (inventory["Woody the Beaver"]) { return ( <img style={{ width: `${GRID_WIDTH_PX * 1.2}px`, }} src={beaver} alt="Woddy the Beaver" /> ); } return null; }; // Only show 1 Nyon statue at a time export const NyonStatue: React.FC = () => { const [showNyonLore, setShowNyonLore] = useState(false); return ( <> <img style={{ width: `${GRID_WIDTH_PX * 1.8}px`, }} className="hover:img-highlight cursor-pointer" src={nyonStatue} alt="Nyon Statue" onClick={() => setShowNyonLore(true)} /> <Modal centered show={showNyonLore} onHide={() => setShowNyonLore(false)}> <Panel> <img src={close} className="h-6 top-4 right-4 absolute cursor-pointer" onClick={() => setShowNyonLore(false)} /> <div className="flex flex-col items-cetner justify-content-between"> <div className="flex justify-content m-2"> <img style={{ width: `${GRID_WIDTH_PX * 1.5}px`, }} className="img-highlight mr-2" src={nyonStatue} alt="Nyon Statue" /> <div className="ml-2 mt-3"> <span className="text-shadow text-xs block">In memory of</span> <span className="text-shadow block">Nyon Lann</span> </div> </div> <div className="flex-1 ml-2 mr-2"> <span className="text-shadow block mb-2 text-xs"> The legendary knight responsible for clearing the goblins from the mines. Shortly after his victory he died by poisoning from a Goblin conspirator. The Sunflower Citizens erected this statue with his armor to commemorate his conquests. </span> </div> </div> </Panel> </Modal> </> ); }; export const Decorations: React.FC = () => { const { gameService } = useContext(Context); const [ { context: { state }, }, ] = useActor(gameService); return ( <> <Flags /> {state.inventory["Sunflower Rock"] && ( <img style={{ width: `${GRID_WIDTH_PX * 4}px`, right: `${GRID_WIDTH_PX * 11.5}px`, top: `${GRID_WIDTH_PX * 22}px`, }} id={Section["Sunflower Rock"]} className="absolute" src={sunflowerRock} alt="Sunflower rock" /> )} {state.inventory["Christmas Tree"] && ( <img style={{ width: `${GRID_WIDTH_PX * 2}px`, right: `${GRID_WIDTH_PX * 16}px`, top: `${GRID_WIDTH_PX * 1}px`, }} id={Section["Christmas Tree"]} className="absolute" src={christmasTree} alt="Christmas Tree" /> )} {state.inventory["Sunflower Statue"] && ( <img style={{ width: `${GRID_WIDTH_PX * 2}px`, left: `${GRID_WIDTH_PX * 45.5}px`, top: `${GRID_WIDTH_PX * 32}px`, }} id={Section["Sunflower Statue"]} className="absolute" src={sunflowerStatue} alt="Sunflower Statue" /> )} {state.inventory["Potato Statue"] && ( <img style={{ width: `${GRID_WIDTH_PX * 1.5}px`, left: `${GRID_WIDTH_PX * 52}px`, top: `${GRID_WIDTH_PX * 39}px`, }} id={Section["Potato Statue"]} className="absolute" src={potatoStatue} alt="Potato Statue" /> )} {state.inventory["Sunflower Tombstone"] && ( <img style={{ width: `${GRID_WIDTH_PX * 1}px`, left: `${GRID_WIDTH_PX * 30}px`, top: `${GRID_WIDTH_PX * 36.8}px`, }} id={Section["Sunflower Tombstone"]} className="absolute" src={sunflowerTombstone} alt="Sunflower tombstone" /> )} {state.inventory["Farm Cat"] && ( <img style={{ width: `${GRID_WIDTH_PX * 1.5}px`, right: `${GRID_WIDTH_PX * 39.55}px`, top: `${GRID_WIDTH_PX * 28.2}px`, }} id={Section["Farm Cat"]} className="absolute z-10" src={cat} alt="Farm cat" /> )} {state.inventory["Farm Dog"] && ( <img style={{ width: `${GRID_WIDTH_PX * 1}px`, right: `${GRID_WIDTH_PX * 37.8}px`, top: `${GRID_WIDTH_PX * 32}px`, }} id={Section["Farm Dog"]} className="absolute" src={dog} alt="Farm dog" /> )} {state.inventory["Gnome"] && ( <img style={{ width: `${GRID_WIDTH_PX * 1}px`, right: "481px", top: "441px", }} id={Section.Gnome} className="absolute" src={gnome} alt="Gnome" /> )} {/* Scarecrows */} <div className="flex justify-center absolute" style={{ width: `${GRID_WIDTH_PX * 3}px`, left: `${GRID_WIDTH_PX * 38}px`, top: `${GRID_WIDTH_PX * 34}px`, }} id={Section.Scarecrow} > <Scarecrows inventory={state.inventory} /> </div> {state.inventory["Nyon Statue"] && ( <div className="flex justify-center absolute" style={{ width: `${GRID_WIDTH_PX * 3}px`, left: `${GRID_WIDTH_PX * 42.5}px`, top: `${GRID_WIDTH_PX * 41}px`, }} id={Section["Nyon Statue"]} > <NyonStatue /> </div> )} {state.inventory["Fountain"] && ( <img style={{ width: `${GRID_WIDTH_PX * 2.5}px`, left: `${GRID_WIDTH_PX * 35}px`, top: `${GRID_WIDTH_PX * 28}px`, }} id={Section.Fountain} onClick={() => fountainAudio.play()} className="absolute hover:img-highlight cursor-pointer" src={fountain} alt="Fountain" /> )} {state.inventory["Goblin Crown"] && ( <img style={{ width: `${GRID_WIDTH_PX * 3}px`, right: `${GRID_WIDTH_PX * 27.5}px`, bottom: `${GRID_WIDTH_PX * 5.5}px`, }} id={Section["Goblin Crown"]} className="absolute" src={goblinKing} alt="GoblinKing" /> )} {/* Beavers */} <div className="flex justify-center absolute" style={{ width: `${GRID_WIDTH_PX * 2}px`, right: `${GRID_WIDTH_PX * 24}px`, top: `${GRID_WIDTH_PX * 49}px`, }} id={Section.Beaver} > <Beavers inventory={state.inventory} /> </div> {state.inventory["Homeless Tent"] && ( <img style={{ width: `${GRID_WIDTH_PX * 2}px`, right: `${GRID_WIDTH_PX * 34.5}px`, top: `${GRID_WIDTH_PX * 31}px`, }} id={Section.Tent} className="absolute" src={homelessTent} alt="Homeless Tent" /> )} <Sign id={state.id as number} inventory={state.inventory} /> {state.inventory["Farmer Bath"] && ( <div className="flex justify-center absolute" style={{ width: `${GRID_WIDTH_PX * 2}px`, left: `${GRID_WIDTH_PX * 48.8}px`, top: `${GRID_WIDTH_PX * 39}px`, }} id={Section.Bath} > <img src={farmerBath} className="w-full" /> <img src={swimmer} style={{ position: "absolute", width: `${GRID_WIDTH_PX * 0.85}px`, top: `${GRID_WIDTH_PX * 0.5}px`, left: `${GRID_WIDTH_PX * 0.5}px`, }} /> </div> )} {state.inventory["Easter Bunny"] && ( <img style={{ width: `${GRID_WIDTH_PX * 2.5}px`, right: `${GRID_WIDTH_PX * 49}px`, top: `${GRID_WIDTH_PX * 24}px`, }} id={Section["Easter Bunny"]} className="absolute" src={easterBunny} alt="Easter Bunny" /> )} </> ); };
the_stack
import DagGraph from '../src/DagGraph' import * as DagHistory from '../src/DagHistory' import Configuration from '../src/Configuration' const config = new Configuration<BasicState>({ actionName: (state: any, id: string) => id, branchName: (oldBranch: any, newBranch: any, actionName: string) => actionName, }) const INITIAL_BRANCH = '1' interface BasicState { x: number y?: number } describe('The DagHistory Module', () => { describe('createHistory', () => { it('can create a new history object', () => { const history = DagHistory.createHistory() expect(history).toBeDefined() expect(history.current).toMatchObject({}) const graph = new DagGraph(history.graph) expect(graph.currentStateId).toBeDefined() // 'expected current branch to be initial', expect(graph.currentBranch).toEqual(INITIAL_BRANCH) // 'expected latest on branch to equal current state', expect(graph.latestOn(INITIAL_BRANCH)).toEqual(graph.currentStateId) // 'expected committed on branch to equal current state', expect(graph.committedOn(INITIAL_BRANCH)).toEqual(graph.currentStateId) }) it('can create a new history object with an initial state', () => { const history = DagHistory.createHistory<BasicState>({ x: 1, y: 2 }) expect(history).toBeDefined() expect(history.current).toMatchObject({ x: 1, y: 2 }) expect(history.graph).toBeDefined() }) }) describe('insert', () => { it('will insert a new state into the history', () => { const historyA = DagHistory.createHistory<BasicState>() const historyB = DagHistory.insert({ x: 1 }, historyA, config) const graphA = new DagGraph(historyA.graph) const graphB = new DagGraph(historyB.graph) expect(graphA.currentStateId).not.toEqual(graphB.currentStateId) expect(graphB.childrenOf(graphA.currentStateId)).toMatchObject([ graphB.currentStateId, ]) expect(graphB.latestOn(INITIAL_BRANCH)).toEqual(graphB.currentStateId) expect(graphB.committedOn(INITIAL_BRANCH)).toEqual(graphB.currentStateId) }) it('will not cull children of the parent state that are associated with branches', () => { const historyA = DagHistory.createHistory<BasicState>() const graphA = new DagGraph(historyA.graph) const historyB = DagHistory.insert({ x: 1 }, historyA, config) const graphB = new DagGraph(historyB.graph) const historyC = DagHistory.jumpToState(graphA.currentStateId, historyB) const historyD = DagHistory.insert({ x: 2 }, historyC, config) const graphD = new DagGraph(historyD.graph) expect(graphD.getState(graphB.currentStateId)).toBeDefined() }) it('will cull children of the parent state that are not associated with branches', () => { let history = DagHistory.createHistory<BasicState>() let graph = new DagGraph(history.graph) let currentBranch = graph.currentBranch const insert = () => { history = DagHistory.insert({ x: 1 }, history, config) graph = new DagGraph(history.graph) currentBranch = graph.currentBranch return graph.currentStateId } // Set up an initial state // (init) A* const stateA = graph.currentStateId // Insert a new state into the graph: // (init) A -> B* const stateB = insert() // Undo State B // (init) A* -> B history = DagHistory.undo(history) graph = new DagGraph(history.graph) // 'C -> latest should be state B', expect(graph.latestOn(INITIAL_BRANCH)).toEqual(stateB) // 'D -> committed should be state A', expect(graph.committedOn(INITIAL_BRANCH)).toEqual(stateA) // Insert a new state // (init) A -> B // (init-1) -> C* const stateC = insert() // 'implicit branch should be created (1)', expect(currentBranch).not.toEqual(INITIAL_BRANCH) /// graphD Contains all the states expect(graph.getState(stateA)).toBeDefined() expect(graph.getState(stateB)).toBeDefined() expect(graph.getState(stateC)).toBeDefined() // Init Branch contains A and B // 'D -> latest on init is B', expect(graph.latestOn(INITIAL_BRANCH)).toEqual(stateB) // 'D -> committed on init is A', expect(graph.committedOn(INITIAL_BRANCH)).toEqual(stateA) // Current Branch contains C // 'D -> latest on current is C', expect(graph.latestOn(currentBranch)).toEqual(stateC) // 'D -> committed on current is C', expect(graph.committedOn(currentBranch)).toEqual(stateC) // 'D ->*p first on current is C', expect(graph.firstOn(currentBranch)).toEqual(stateC) expect(graph.commitPath(stateC)).toMatchObject(['1', '3']) // Check branch depths // 'start depth should be 1', expect(graph.branchStartDepth(currentBranch)).toEqual(1) // 'end depth should be 1', expect(graph.branchEndDepth(currentBranch)).toEqual(1) // 'max depth should be 1' expect(graph.maxDepth).toEqual(1) // Insert a new state // (init) A -> B // (init-1) -> C -> D insert() // 'implicit branch should be created (2)', expect(currentBranch).not.toEqual(INITIAL_BRANCH) // 'start depth should be 1', expect(graph.branchStartDepth(currentBranch)).toEqual(1) // 'end depth should be 2', expect(graph.branchEndDepth(currentBranch)).toEqual(2) // 'max depth should be 2' expect(graph.maxDepth).toEqual(2) }) }) describe('undo/redo', () => { it('undo will move the committed state back, leaving latest in place', () => { const historyA = DagHistory.createHistory<BasicState>() const graphA = new DagGraph(historyA.graph) const historyB = DagHistory.insert({ x: 1 }, historyA, config) const graphB = new DagGraph(historyB.graph) const historyC = DagHistory.undo(historyB) const graphC = new DagGraph(historyC.graph) expect(graphC.latestOn(INITIAL_BRANCH)).toEqual(graphB.currentStateId) expect(graphC.committedOn(INITIAL_BRANCH)).toEqual(graphA.currentStateId) }) it('redo will move the committed state forward', () => { const historyA = DagHistory.createHistory<BasicState>() const historyB = DagHistory.insert({ x: 1 }, historyA, config) const graphB = new DagGraph(historyB.graph) const historyC = DagHistory.undo(historyB) const historyD = DagHistory.redo(historyC) const graphD = new DagGraph(historyD.graph) expect(graphD.latestOn(INITIAL_BRANCH)).toEqual(graphB.currentStateId) expect(graphD.committedOn(INITIAL_BRANCH)).toEqual(graphB.currentStateId) }) }) describe('create branch', () => { it('will create a new branch on the current active with a common ancestor', () => { const historyA = DagHistory.createHistory<BasicState>() const graphA = new DagGraph(historyA.graph) const historyB = DagHistory.insert({ x: 1 }, historyA, config) const graphB = new DagGraph(historyB.graph) const historyC = DagHistory.jumpToState(graphA.currentStateId, historyB) const historyD = DagHistory.createBranch('derp', historyC) const graphD = new DagGraph(historyD.graph) const historyE = DagHistory.insert({ x: 2 }, historyD, config) const graphE = new DagGraph(historyE.graph) // a -> b <master> // -> e <derp> const currentBranch = graphD.currentBranch expect(graphD.getBranchName(currentBranch)).toEqual('derp') expect(graphD.latestOn(currentBranch)).toEqual(graphD.currentStateId) expect(graphD.committedOn(currentBranch)).toEqual(graphD.currentStateId) expect(graphE.commitPath(graphE.currentStateId)).toMatchObject([ graphA.currentStateId, graphE.currentStateId, ]) expect(graphE.commitPath(graphB.currentStateId)).toMatchObject([ graphA.currentStateId, graphB.currentStateId, ]) }) it('will create a new branch on the current active node', () => { const historyA = DagHistory.createHistory<BasicState>() const graphA = new DagGraph(historyA.graph) const historyB = DagHistory.insert({ x: 1 }, historyA, config) const graphB = new DagGraph(historyB.graph) const historyD = DagHistory.createBranch('derp', historyB) const graphD = new DagGraph(historyD.graph) const historyE = DagHistory.insert({ x: 2 }, historyD, config) const graphE = new DagGraph(historyE.graph) // a -> b <master> // -> e <derp> const currentBranch = graphD.currentBranch expect(graphD.getBranchName(currentBranch)).toEqual('derp') expect(graphD.latestOn(currentBranch)).toEqual(graphD.currentStateId) expect(graphD.committedOn(currentBranch)).toEqual(graphD.currentStateId) expect(graphE.commitPath(graphE.currentStateId)).toMatchObject([ graphA.currentStateId, graphB.currentStateId, graphE.currentStateId, ]) expect(graphE.commitPath(graphB.currentStateId)).toMatchObject([ graphA.currentStateId, graphB.currentStateId, ]) }) }) describe('clear', () => { it('can clear the history', () => { const historyA = DagHistory.createHistory<BasicState>() const historyB = DagHistory.insert({ x: 1 }, historyA, config) const historyC = DagHistory.clear(historyB) expect(Object.keys(historyC.graph.get('states').toJS()).length).toEqual(1) }) }) describe('squash', () => { it('will collapse parent states that have a single ancestor', () => { let history = DagHistory.createHistory<BasicState>({ x: 0 }) // Create a Branch and a Commired // (init) I // (A) -> A0* history = DagHistory.createBranch('A', history) history = DagHistory.insert<BasicState>({ x: 1 }, history, config) // Pop back to the Initial Branch // (init) I* // (A) -> A0 history = DagHistory.jumpToBranch(INITIAL_BRANCH, history) // Create a new branch with Two Additional Commits // (init) I // (A) -> A0 // (B) -> B0 -> B1 -> B2* history = DagHistory.createBranch('B', history) history = DagHistory.insert<BasicState>({ x: 2 }, history, config) history = DagHistory.insert<BasicState>({ x: 3 }, history, config) // Squash Branch B // (init) I // (A) -> A0 // (B) -> B0* (squashed) // // NOTE: Commit 1 and Commit 2 from Branch B should be squashed history = DagHistory.squash(history) // 'There should be 4 states after the squash', expect(Object.keys(history.graph.get('states').toJS()).length).toEqual(3) }) it('will collapse a linear chain into a single root', () => { let history = DagHistory.createHistory<BasicState>({ x: 0 }) history = DagHistory.insert<BasicState>({ x: 1 }, history, config) history = DagHistory.insert<BasicState>({ x: 2 }, history, config) history = DagHistory.insert<BasicState>({ x: 3 }, history, config) // Set up a flat linear chain // (init) I -> A -> B -> C* // A squash should flatten this totally // (init) I* (squashed) history = DagHistory.squash(history) expect(Object.keys(history.graph.get('states').toJS()).length).toEqual(1) }) }) })
the_stack
import test from 'ava'; import {JsonGetter} from '../src/decorators/JsonGetter'; import {JsonSetter} from '../src/decorators/JsonSetter'; import {JsonClassType} from '../src/decorators/JsonClassType'; import {ObjectMapper} from '../src/databind/ObjectMapper'; import {JsonIgnoreProperties} from '../src/decorators/JsonIgnoreProperties'; import {JsonProperty} from '../src/decorators/JsonProperty'; test('@JsonIgnoreProperties', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } } @JsonIgnoreProperties({ value: ['owner'] }) class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [String]}) category: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string, category: string, @JsonClassType({type: () => [User]}) owner: User) { this.id = id; this.name = name; this.category = category; this.owner = owner; } } const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const item1 = new Item(1, 'Game Of Thrones', 'Book', user); const item2 = new Item(2, 'NVIDIA', 'Graphic Card', user); user.items.push(...[item1, item2]); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"items":[{"id":1,"name":"Game Of Thrones","category":"Book"},{"id":2,"name":"NVIDIA","category":"Graphic Card"}],"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}')); const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.email, 'john.alfa@gmail.com'); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.is(userParsed.items.length, 2); t.is(userParsed.items[0].id, 1); t.is(userParsed.items[0].name, 'Game Of Thrones'); t.is(userParsed.items[0].category, 'Book'); t.is(userParsed.items[0].owner, null); t.is(userParsed.items[1].id, 2); t.is(userParsed.items[1].name, 'NVIDIA'); t.is(userParsed.items[1].category, 'Graphic Card'); t.is(userParsed.items[1].owner, null); }); test('@JsonIgnoreProperties at property level', t => { @JsonIgnoreProperties({ value: ['firstname'] }) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonIgnoreProperties({ value: ['owner'] }) @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } } class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [String]}) category: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string, category: string, @JsonClassType({type: () => [User]}) owner: User) { this.id = id; this.name = name; this.category = category; this.owner = owner; } } const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const item1 = new Item(1, 'Game Of Thrones', 'Book', user); const item2 = new Item(2, 'NVIDIA', 'Graphic Card', user); user.items.push(...[item1, item2]); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"email":"john.alfa@gmail.com","lastname":"Alfa","items":[{"id":1,"name":"Game Of Thrones","category":"Book"},{"id":2,"name":"NVIDIA","category":"Graphic Card"}]}')); // eslint-disable-next-line max-len const userParsed = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa","items":[{"id":1,"name":"Game Of Thrones","category":"Book","owner":{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}},{"id":2,"name":"NVIDIA","category":"Graphic Card","owner":{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}}]}', {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.email, 'john.alfa@gmail.com'); t.is(userParsed.firstname, null); t.is(userParsed.lastname, 'Alfa'); t.is(userParsed.items.length, 2); t.is(userParsed.items[0].id, 1); t.is(userParsed.items[0].name, 'Game Of Thrones'); t.is(userParsed.items[0].category, 'Book'); t.is(userParsed.items[0].owner, null); t.is(userParsed.items[1].id, 2); t.is(userParsed.items[1].name, 'NVIDIA'); t.is(userParsed.items[1].category, 'Graphic Card'); t.is(userParsed.items[1].owner, null); }); test('@JsonIgnoreProperties at method level', t => { @JsonIgnoreProperties({ value: ['firstname'] }) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } @JsonGetter() @JsonClassType({type: () => [Array, [Item]]}) @JsonIgnoreProperties({ value: ['owner'] }) getItems(): Item[] { return this.items; } @JsonSetter() @JsonIgnoreProperties({ value: ['owner'] }) setItems(@JsonClassType({type: () => [Array, [Item]]}) items: Item[]) { this.items = items; } } class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [String]}) category: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string, category: string, @JsonClassType({type: () => [User]}) owner: User) { this.id = id; this.name = name; this.category = category; this.owner = owner; } } const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const item1 = new Item(1, 'Game Of Thrones', 'Book', user); const item2 = new Item(2, 'NVIDIA', 'Graphic Card', user); user.items.push(...[item1, item2]); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"email":"john.alfa@gmail.com","lastname":"Alfa","items":[{"id":1,"name":"Game Of Thrones","category":"Book"},{"id":2,"name":"NVIDIA","category":"Graphic Card"}]}')); // eslint-disable-next-line max-len const userParsed = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa","items":[{"id":1,"name":"Game Of Thrones","category":"Book","owner":{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}},{"id":2,"name":"NVIDIA","category":"Graphic Card","owner":{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}}]}', {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.email, 'john.alfa@gmail.com'); t.is(userParsed.firstname, null); t.is(userParsed.lastname, 'Alfa'); t.is(userParsed.items.length, 2); t.is(userParsed.items[0].id, 1); t.is(userParsed.items[0].name, 'Game Of Thrones'); t.is(userParsed.items[0].category, 'Book'); t.is(userParsed.items[0].owner, null); t.is(userParsed.items[1].id, 2); t.is(userParsed.items[1].name, 'NVIDIA'); t.is(userParsed.items[1].category, 'Graphic Card'); t.is(userParsed.items[1].owner, null); }); test('@JsonIgnoreProperties at parameter level', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string, @JsonIgnoreProperties({value: ['owner']}) @JsonClassType({type: () => [Array, [Item]]}) items: Item[]) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; this.items = items; } } class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [String]}) category: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string, category: string, @JsonClassType({type: () => [User]}) owner: User) { this.id = id; this.name = name; this.category = category; this.owner = owner; } } const item1 = new Item(1, 'Game Of Thrones', 'Book', null); const item2 = new Item(2, 'NVIDIA', 'Graphic Card', null); const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa', [item1, item2]); item1.owner = user; item2.owner = user; const objectMapper = new ObjectMapper(); // eslint-disable-next-line max-len const userParsed = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa","items":[{"id":1,"name":"Game Of Thrones","category":"Book","owner":{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}},{"id":2,"name":"NVIDIA","category":"Graphic Card","owner":{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}}]}', {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.email, 'john.alfa@gmail.com'); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.is(userParsed.items.length, 2); t.is(userParsed.items[0].id, 1); t.is(userParsed.items[0].name, 'Game Of Thrones'); t.is(userParsed.items[0].category, 'Book'); t.is(userParsed.items[0].owner, null); t.is(userParsed.items[1].id, 2); t.is(userParsed.items[1].name, 'NVIDIA'); t.is(userParsed.items[1].category, 'Graphic Card'); t.is(userParsed.items[1].owner, null); }); test('@JsonIgnoreProperties at parameter level (inside @JsonClass)', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string, @JsonClassType({type: () => [Array, [ () => ({ target: Item, decorators: [ { name: 'JsonIgnoreProperties', options: { value: ['owner'] } } ] })]]}) items: Item[]) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; this.items = items; } } class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [String]}) category: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string, category: string, @JsonClassType({type: () => [User]}) owner: User) { this.id = id; this.name = name; this.category = category; this.owner = owner; } } const item1 = new Item(1, 'Game Of Thrones', 'Book', null); const item2 = new Item(2, 'NVIDIA', 'Graphic Card', null); const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa', [item1, item2]); item1.owner = user; item2.owner = user; const objectMapper = new ObjectMapper(); // eslint-disable-next-line max-len const userParsed = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa","items":[{"id":1,"name":"Game Of Thrones","category":"Book","owner":{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}},{"id":2,"name":"NVIDIA","category":"Graphic Card","owner":{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}}]}', {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.email, 'john.alfa@gmail.com'); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.is(userParsed.items.length, 2); t.is(userParsed.items[0].id, 1); t.is(userParsed.items[0].name, 'Game Of Thrones'); t.is(userParsed.items[0].category, 'Book'); t.is(userParsed.items[0].owner, null); t.is(userParsed.items[1].id, 2); t.is(userParsed.items[1].name, 'NVIDIA'); t.is(userParsed.items[1].category, 'Graphic Card'); t.is(userParsed.items[1].owner, null); }); test('@JsonIgnoreProperties with @JsonGetter and @JsonSetter', t => { @JsonIgnoreProperties({value: ['fullname']}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [String]]}) fullname: string[]; constructor(id: number, firstname: string, lastname: string) { this.id = id; this.firstname = firstname; this.lastname = lastname; } @JsonGetter({value: 'fullname'}) @JsonClassType({type: () => [String]}) getFullname(): string { return this.firstname + ' ' + this.lastname; } @JsonSetter({value: 'fullname'}) setFullname(fullname: string) { this.fullname = fullname.split(' '); } } const user = new User(1, 'John', 'Alfa'); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"firstname":"John","lastname":"Alfa"}')); const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.is(userParsed.fullname, undefined); }); test('@JsonIgnoreProperties with allowGetters "true"', t => { @JsonIgnoreProperties({value: ['fullname', 'firstname'], allowGetters: true}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [String]]}) fullname: string[]; constructor(id: number, firstname: string, lastname: string) { this.id = id; this.firstname = firstname; this.lastname = lastname; } @JsonGetter({value: 'fullname'}) @JsonClassType({type: () => [String]}) getFullname(): string { return this.firstname + ' ' + this.lastname; } @JsonSetter({value: 'fullname'}) setFullname(fullname: string) { this.fullname = fullname.split(' '); } } const user = new User(1, 'John', 'Alfa'); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"lastname":"Alfa","fullname":"John Alfa"}')); const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, null); t.is(userParsed.lastname, 'Alfa'); t.is(userParsed.fullname, undefined); }); test('@JsonIgnoreProperties with allowSetters "true"', t => { @JsonIgnoreProperties({value: ['fullname', 'firstname'], allowGetters: true, allowSetters: true}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [String]]}) fullname: string[]; constructor(id: number, firstname: string, lastname: string) { this.id = id; this.firstname = firstname; this.lastname = lastname; } @JsonGetter({value: 'fullname'}) @JsonClassType({type: () => [String]}) getFullname(): string { return this.firstname + ' ' + this.lastname; } @JsonSetter({value: 'fullname'}) setFullname(fullname: string) { this.fullname = fullname.split(' '); } } const user = new User(1, 'John', 'Alfa'); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"lastname":"Alfa","fullname":"John Alfa"}')); const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, null); t.is(userParsed.lastname, 'Alfa'); t.deepEqual(userParsed.fullname, ['John', 'Alfa']); }); test('@JsonIgnoreProperties with @JsonProperty as getters and setters', t => { @JsonIgnoreProperties({value: ['fullname', 'firstname']}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [String]]}) fullname: string[]; constructor(id: number) { this.id = id; } @JsonProperty() @JsonClassType({type: () => [String]}) getFullname(): string { return this.firstname + ' ' + this.lastname; } @JsonProperty() setFullname(fullname: string) { const fullnameSplitted = fullname.split(' '); this.firstname = fullnameSplitted[0]; this.lastname = fullnameSplitted[1]; this.fullname = fullnameSplitted; } } const user = new User(1); user.firstname = 'John'; user.lastname = 'Alfa'; const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"lastname":"Alfa"}')); const userParsed = objectMapper.parse<User>( '{"id":1,"firstname":"John","lastname":"Alfa","fullname":"John Alfa"}', {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, undefined); t.is(userParsed.lastname, 'Alfa'); t.is(userParsed.fullname, undefined); }); test('@JsonIgnoreProperties with allowGetters and @JsonProperty as getters and setters', t => { @JsonIgnoreProperties({value: ['fullname', 'firstname'], allowGetters: true}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [String]]}) fullname: string[]; constructor(id: number) { this.id = id; } @JsonProperty() @JsonClassType({type: () => [String]}) getFullname(): string { return this.firstname + ' ' + this.lastname; } @JsonProperty() setFullname(fullname: string) { const fullnameSplitted = fullname.split(' '); this.firstname = fullnameSplitted[0]; this.lastname = fullnameSplitted[1]; this.fullname = fullnameSplitted; } } const user = new User(1); user.firstname = 'John'; user.lastname = 'Alfa'; const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"lastname":"Alfa","fullname":"John Alfa"}')); const userParsed = objectMapper.parse<User>( '{"id":1,"firstname":"John","lastname":"Alfa","fullname":"John Alfa"}', {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, undefined); t.is(userParsed.lastname, 'Alfa'); t.is(userParsed.fullname, undefined); }); test('@JsonIgnoreProperties with allowSetters and @JsonProperty as getters and setters', t => { @JsonIgnoreProperties({value: ['fullname', 'firstname'], allowGetters: true, allowSetters: true}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [String]]}) fullname: string[]; constructor(id: number) { this.id = id; } @JsonProperty() @JsonClassType({type: () => [String]}) getFullname(): string { return this.firstname + ' ' + this.lastname; } @JsonProperty() setFullname(fullname: string) { const fullnameSplitted = fullname.split(' '); this.firstname = fullnameSplitted[0]; this.lastname = fullnameSplitted[1]; this.fullname = fullnameSplitted; } } const user = new User(1); user.firstname = 'John'; user.lastname = 'Alfa'; const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"lastname":"Alfa","fullname":"John Alfa"}')); const userParsed = objectMapper.parse<User>('{"id":1,"fullname":"John Alfa"}', {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.deepEqual(userParsed.fullname, ['John', 'Alfa']); }); test('@JsonIgnoreProperties with ignoreUnknown "true"', t => { @JsonIgnoreProperties({value: ['firstname'], ignoreUnknown: true}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; constructor(id: number, firstname: string, lastname: string) { this.id = id; this.firstname = firstname; this.lastname = lastname; } } const objectMapper = new ObjectMapper(); const jsonData = '{"id":1,"firstname":"John","lastname":"Alfa","email":"john.alfa@gmail.com"}'; const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, null); t.is(userParsed.lastname, 'Alfa'); t.assert(!Object.hasOwnProperty.call(userParsed, 'email')); });
the_stack
import { User } from "@microsoft/microsoft-graph-types"; import { AadHttpClient, AadHttpClientConfiguration, HttpClientResponse, IAadHttpClientConfiguration, IAadHttpClientConfigurations, IAadHttpClientOptions } from "@microsoft/sp-http"; import { IODataUser } from "@microsoft/sp-odata-types"; import { SPPermission } from "@microsoft/sp-page-context"; //import * as MicrosoftGraph from "@microsoft/microsoft-graph-types" import { sp } from "@pnp/sp"; import { SiteGroup } from "@pnp/sp/src/sitegroups"; import { filter, find, includes, indexOf, lowerCase } from "lodash"; export interface ISPSecurableObject { id: number; roleAssignments: SPRoleAssignment[]; } export class SPBasePermissions { public low: number; public high: number; public constructor(high: any, low: any) { this.high = parseInt(high, 10); this.low = parseInt(low, 10); } } export enum securableType { List } export class ADGroupId { public ADId: string; // the goid id in azure public SPId: number; // the numeric id in the sharepoint users list } export class ADGroup { public id: ADGroupId; public members: Array<User>; } export class SPSiteGroup { public id: number; public title: string; public isHiddenInUI: boolean; public isShareByEmailGuestUse: boolean; public isSiteAdmin: boolean; public userIds: number[];// to switch to ad groups need to make this a string[] with the UPN public adGroupIds: ADGroupId[]; public constructor(id: number, title: string) { this.id = id; this.title = title; this.userIds = []; this.adGroupIds = []; } } export class SPSiteUser { public name: string; public id?: number; public userId?: SPExternalUser; public upn: string; public isSelected: boolean; //should user be shown in UI public principalType: number; //4=Security group, 1 = user, 2=DL, 8=SP Group, IN HERE A -1 MEANS AD USER public adId: string;//id if the user in AD } export class SPRoleDefinition { public id: number; public basePermissions: SPBasePermissions; public description: string; public hidden: boolean; public name: string; public constructor(id: number, basePermissions: SPBasePermissions, description: string, hidden: boolean, name: string) { this.id = id; this.basePermissions = basePermissions; this.description = description; this.hidden = hidden; this.name = name; } } export class SPSecurityInfo { public siteUsers: SPSiteUser[]; public siteGroups: SPSiteGroup[]; public roleDefinitions: SPRoleDefinition[]; public adGroups: ADGroup[]; public lists: (SPList | SPListItem)[]; public constructor() { this.siteUsers = new Array<SPSiteUser>(); this.siteGroups = new Array<SPSiteGroup>(); this.roleDefinitions = new Array<SPRoleDefinition>(); this.siteUsers = new Array<SPSiteUser>(); this.lists = new Array<SPList>(); this.adGroups = new Array<ADGroup>(); } } export class SPList { public title: string; public id: string; public hidden: boolean; // this specifies if the list is a sharepoint hidden list public serverRelativeUrl: string; public type: securableType; public itemCount: number; public roleAssignments: SPRoleAssignment[]; public isExpanded: boolean; public hasBeenRetrieved: boolean; public isSelected: boolean; //Shoud list be shown in the UI } export class SPListItem { public id: string; public parentId: string; public listTitle: string; public type: string; public itemCount: number; public title: string; public serverRelativeUrl: string; public roleAssignments: SPRoleAssignment[]; public isExpanded: boolean; public hasBeenRetrieved: boolean; public level: number; } // export class ADGroup { // public id: string; // public parentId: string; // public listTitle: string; // public type: string; // public itemCount: number; // public title: string; // public serverRelativeUrl: string; // public roleAssignments: SPRoleAssignment[]; // public isExpanded: boolean; // public hasBeenRetrieved: boolean; // public level: number; // } export class SPExternalUser { public nameId: string; public nameIdIssuer: string; } export class SPRoleAssignment { public roleDefinitionIds: number[] = []; public principalId: number; } export class Helpers { public static doesUserHaveAnyPermission(securableObjects: any[], user, requestedpermissions: SPPermission[], roles, siteGroups, adGroups: ADGroup[]): boolean { for (var securableObject of securableObjects) { for (var requestedpermission of requestedpermissions) { if (Helpers.doesUserHavePermission(securableObject, user, requestedpermission, roles, siteGroups, adGroups)) { return true; } } } return false; } public static doesUserHavePermission(securableObject, user, requestedpermission: SPPermission, roles, siteGroups, adGroups: ADGroup[]) { const permissions: SPBasePermissions[] = Helpers.getUserPermissionsForObject(securableObject, user, roles, siteGroups, adGroups); for (const permission of permissions) { if ( ((permission.low & requestedpermission.value.Low) === (requestedpermission.value.Low)) && ((permission.high & requestedpermission.value.High) === (requestedpermission.value.High)) ) { return true; } } return false; } public static getBasePermissionsForRoleDefinitiuonIds(selectedRoleDefinitionIds: number[], roleDefinitions: SPRoleDefinition[]): Array<SPBasePermissions> { let basePermissions = []; for (const selectedRoleDefinitionId of selectedRoleDefinitionIds) { for (const roleDefinition of roleDefinitions) { if (roleDefinition.id === selectedRoleDefinitionId) { basePermissions.push(roleDefinition.basePermissions); } } } // for (var rdx = 0; rdx < roleDefs.length; rdx++) { // for (var rdi = 0; rdi < roleDefinitionIds.length; rdi++) {basePermission // if (roleDefs[rdx].Id === roleDefinitionIds[rdi]) { // basePermissions.push(roleDefs[rdx].BasePermissions); // } // } // } return basePermissions; } public static getUserPermissionsForObject(securableObject, user, roles: SPRoleDefinition[], siteGroups: SPSiteGroup[], adGroups: ADGroup[]) { const userRoleAssignments: SPRoleAssignment[] = Helpers.GetRoleAssignmentsForUser(securableObject, user, siteGroups, adGroups); let roleDefinitionIds: number[] = []; for (const roleAssignment of userRoleAssignments) { for (const roleDefinitionID of roleAssignment.roleDefinitionIds) { roleDefinitionIds.push(roleDefinitionID); } } var userPermissions = Helpers.getBasePermissionsForRoleDefinitiuonIds(roleDefinitionIds, roles); return userPermissions; } public static findGroup(groupId: number, groups: SPSiteGroup[]): SPSiteGroup { return find(groups, (g) => { return g.id === groupId; }); } public static userIsInGroup(userId: number, groupId: number, groups: SPSiteGroup[]): boolean { let group: SPSiteGroup = this.findGroup(groupId, groups); return includes(group.userIds, userId); } public static userIsInGroupsNestAdGroups(userAdId: String, groupId: number, groups: SPSiteGroup[], adGroups: ADGroup[]): boolean { let group: SPSiteGroup = this.findGroup(groupId, groups); debugger; for (var adGrouId of group.adGroupIds) { var adGroup = find(adGroups, (adg) => { return adg.id === adGrouId; }); if (adGroup) { if (find(adGroup.members, (aduser) => { return aduser.id === userAdId; })) { return true; } } else { debugger; alert(`adGroup ${ADGroupId} was not in the collection of ad groups.`); } } } public static GetRoleAssignmentsForUser(securableObject: ISPSecurableObject, user: SPSiteUser, groups: SPSiteGroup[], adGroups: ADGroup[]): SPRoleAssignment[] { try { let selectedRoleAssignments: SPRoleAssignment[] = []; // for each role assignment, if the user is in the group, or its for this user, add it to his roleassignments for (const roleAssignment of securableObject.roleAssignments) { let group: SPSiteGroup = find(groups, (g) => { return g.id === roleAssignment.principalId; }); if (group) { if (this.userIsInGroup(user.id, group.id, groups)) { // this tests if a user is directly in the SP GROUP selectedRoleAssignments.push(roleAssignment); } if (this.userIsInGroupsNestAdGroups(user.adId, group.id, groups, adGroups)) { // this tests if a user is in an ad group thats in the SP GROUP selectedRoleAssignments.push(roleAssignment); } } else { // it must be a user if (user.id === roleAssignment.principalId) { selectedRoleAssignments.push(roleAssignment); } } } debugger; if (user.adId) { // if user is referenced in any groups, we stored his ad id in his user record for (var adgroup of adGroups) {// for all adGroups if (find(adgroup.members, (member) => { return member.id === user.adId; }) != -1) { // if user is in the adgroup // for each role assignment, if the adGroup is in the group, or its for this adgroup, add it to his roleassignments for (const roleAssignment of securableObject.roleAssignments) { if (adgroup.id.SPId === roleAssignment.principalId) { selectedRoleAssignments.push(roleAssignment); } // debugger; // let group: SPSiteGroup = find(groups, (g) => { return g.id === roleAssignment.principalId; }); // if (group) { // if (this.userIsInGroup(user.id, group.id, groups)) { // selectedRoleAssignments.push(roleAssignment); // } // } // else { // // it must be a user // if (user.id === roleAssignment.principalId) { // selectedRoleAssignments.push(roleAssignment); // } // } } } } } return selectedRoleAssignments; } catch (exception) { //debugger; console.error(exception); } } } export default class SPSecurityService { public siteUrl: string; public constructor(siteUrl: string) { this.siteUrl = siteUrl; } public loadFolderRoleAssigmentsDefinitionsMembers(listTitle, folderServerRelativeUrl, parentId: string, level: number, forceReload: boolean): Promise<SPListItem[]> { // pnp.sp.web.lists.getByTitle("Config3").getItemsByCAMLQuery(caml, "RoleAssignments").then(show); let caml: any = { ViewXml: "<View Scope='RecursiveAll'>" + " <Query>" + "<Where>" + " <Eq>" + " <FieldRef Name='FileDirRef'/>" + " <Value Type='Lookup'>" + folderServerRelativeUrl + " </Value>" + " </Eq>" + " </Where>" + " </Query>" + // " <QueryOptions>"+ // "<ViewAttributes Scope='RecursiveAll' />" + // "<OptimizeFor>FolderUrls</OptimizeFor>"+ // "</QueryOptions>"+ " </View>" }; return sp.web.lists.getByTitle(listTitle).getItemsByCAMLQuery(caml, "ContentType", "Folder", "Folder/ParentFolder", "File", "File/ParentFolder", "RoleAssignments", "RoleAssignments/RoleDefinitionBindings", "RoleAssignments/Member", "RoleAssignments/Member/Users", "RoleAssignments/Member/Groups") .then((response) => { let itemsToAdd: SPListItem[] = []; for (let listItem of response) { let itemToAdd: SPListItem = new SPListItem(); itemToAdd.id = listItem.GUID; itemToAdd.parentId = parentId; itemToAdd.level = level; itemToAdd.listTitle = listTitle; itemToAdd.type = listItem.ContentType.Name; itemToAdd.isExpanded = false; itemToAdd.hasBeenRetrieved = false; itemToAdd.roleAssignments = []; if (listItem.ContentType.Name === "Folder") { // its a folder itemToAdd.title = listItem.Folder.Name; itemToAdd.serverRelativeUrl = listItem.Folder.ServerRelativeUrl; itemToAdd.itemCount = listItem.Folder.ItemCount; } else { if (listItem.File) {// its a file itemToAdd.title = listItem.File.Name; itemToAdd.serverRelativeUrl = listItem.File.ServerRelativeUrl; } else { // its a listitem itemToAdd.title = listItem.Title; } } for (let roleAssignmentObject of listItem.RoleAssignments) { let roleAssignment: SPRoleAssignment = { roleDefinitionIds: roleAssignmentObject.RoleDefinitionBindings.map((rdb) => { return rdb.Id; }), principalId: roleAssignmentObject.PrincipalId }; // if (roleAssignmentObject.Member.UserId) { // roleAssignment.userId = new SPExternalUser(); // roleAssignment.userId.nameId = roleAssignmentObject.Member.UserId.NameId; // roleAssignment.userId.nameIdIssuer = roleAssignmentObject.Member.UserId.NameIdIssuer; // // roleAssignment.userId = roleAssignmentObject.Member.UserId; // } // if (roleAssignmentObject.Member.Users) { // for (let roleAssignmentMemberUser of roleAssignmentObject.Member.Users) { // roleAssignment.users.push(roleAssignmentMemberUser.Id); // } // } // if (roleAssignmentObject.Member.Groups) { // for (let roleAssignmentMemberGroup of roleAssignmentObject.Member.Groups) { // roleAssignment.groups.push(roleAssignmentMemberGroup.Id); // } // } // for (let roleDefinitionBinding of roleAssignmentObject.RoleDefinitionBindings) { // roleAssignment.roleDefinitionIds.push(roleDefinitionBinding.Id); // } itemToAdd.roleAssignments.push(roleAssignment); } itemsToAdd.push(itemToAdd); } return itemsToAdd; }); } // public async getMembersOfAdGroup(aadHttpClient: AadHttpClient, groupName: string): Promise<any> { // return aadHttpClient.get("v1.0/groups?$filter=displayName eq '" + groupName + "'&$expand=members", // AadHttpClient.configurations.v1).then((response) => { // response.json().then((data) => { // debugger; // }); // }).catch((err) => { // console.log(err); // }); // } /// Loads data for intial display public loadData(showHiddenLists: boolean, showCatalogs: boolean, aadHttpClient: AadHttpClient, forceReload: boolean): Promise<SPSecurityInfo> { let securityInfo: SPSecurityInfo = new SPSecurityInfo(); let batch: any = sp.createBatch(); let errors: Array<string> = []; debugger; sp.web.siteUsers.inBatch(batch).get() .then((response) => { securityInfo.siteUsers = response.map((u) => { var upn: string = u.LoginName.split('|')[2]; let user: SPSiteUser = new SPSiteUser(); user.isSelected = true; user.id = u.Id; user.name = u.Title; user.principalType = u.PrincipalType; user.upn = upn ? upn.toLocaleLowerCase() : u.Title;// switching key in react from id to upn. ensure upn is not undefined if (u.UserId) { user.userId = new SPExternalUser(); user.userId.nameId = u.UserId.NameId; user.userId.nameIdIssuer = u.UserId.NameIdIssuer; } return user; }); // securityInfo.siteUsers = securityInfo.siteUsers.filter((su) => { su.upn }); return securityInfo.siteUsers;// dont really need to return this// already set it on securityinfo }).catch((error) => { debugger; errors.push(`There was an error feting site users -- ${error.message}`); throw error; }); sp.web.siteGroups.filter(`Title ne 'Limited Access System Group'`).expand("Users").select("Title", "Id", "IsHiddenInUI", "IsShareByEmailGuestUse", "IsSiteAdmin", "IsSiteAdmin") .inBatch(batch).get() .then(async (response) => { // if group contains an ad group(PrincipalType=4) expand it securityInfo.siteGroups = response.map((grp) => { // //IMPORTANT: //For groups created with 'Anyone in the organization with the link' //LoginName: "SharingLinks.cf28991a-7f40-49c8-a68e-f4fa143a094f.OrganizationEdit.2671b36d-1681-4e39-82dc-a9f11166517d", // //For groups create with SPecific People //LoginName: "SharingLinks.3d634d86-7136-4d59-8acf-c87d9a2c7d98.Flexible.9368eb69-6ca4-4b55-85e5-148c3e48e520", // //need to check for other options. Seems funny that the one labeled 'Flexible' is for specific people. // //So we wil need to add code one day to decipher all thes sharing groups! let siteGroup: SPSiteGroup = new SPSiteGroup(grp.Id, grp.Title); for (let user of grp.Users) { if (user.PrincipalType === 4) { //4=Security group, 1 = user, 2=DL, 8=SP Group var adgroupid = new ADGroupId(); adgroupid.ADId = user.LoginName.split('|')[2];//Loginname s c:0t,c|tenant|grpid for ad groups adgroupid.SPId = user.Id; siteGroup.adGroupIds.push(adgroupid); } else { siteGroup.userIds.push(user.Id); } } return siteGroup; }); return securityInfo.siteGroups;// don't really need to return this// already set it on securityinfo }).catch((error) => { //error fetching groups errors.push(`There was an error feting site Groups -- ${error.message}`); //debugger; throw error; }); sp.web.roleDefinitions.expand("BasePermissions").inBatch(batch).get() .then((response) => { securityInfo.roleDefinitions = response.map((rd) => { const bp: SPBasePermissions = new SPBasePermissions(rd.BasePermissions.High, rd.BasePermissions.Low); const roleDefinition: SPRoleDefinition = new SPRoleDefinition( parseInt(rd.Id, 10), bp, rd.Description, rd.Hidden, rd.Name); return roleDefinition; }); return securityInfo.roleDefinitions; }).catch((error) => { //debugger; //error fetching role definitions errors.push(`There was an error fetching role Definitions -- ${error.message}`); throw error; }); let filters: string[] = []; if (!showHiddenLists) { filters.push("Hidden eq false"); } if (!showCatalogs) { filters.push("IsCatalog eq false"); } let subFilter: string = filters.join(" and "); sp.web.lists .expand("RootFolder", "RoleAssignments", "RoleAssignments/RoleDefinitionBindings", "RoleAssignments/Member", "RoleAssignments/Member/Users", "RoleAssignments/Member/Groups", "RoleAssignments/Member/UserId") .filter(subFilter).inBatch(batch).get() .then((response) => { securityInfo.lists = response.map((listObject) => { let mylist: SPList = new SPList(); mylist.isSelected = true;// Should be shown in the UI, user can de-select it in the ui mylist.title = listObject.Title; mylist.id = listObject.Id; mylist.hidden = listObject.Hidden; mylist.serverRelativeUrl = listObject.RootFolder.ServerRelativeUrl; mylist.type = securableType.List;// to differentiate folders from lists mylist.itemCount = listObject.ItemCount; mylist.isExpanded = false; mylist.hasBeenRetrieved = false; mylist.roleAssignments = listObject.RoleAssignments.map((roleAssignmentObject) => { let roleAssignment: SPRoleAssignment = { roleDefinitionIds: roleAssignmentObject.RoleDefinitionBindings.map((rdb) => { return rdb.Id; }), principalId: roleAssignmentObject.PrincipalId }; return roleAssignment; }); return mylist; }); }).catch((error) => { //debugger; errors.push(`There was an error fetching lists -- ${error.message} `); //error fetching lists throw error; }); // execute the batch to get sp stuff return batch.execute().then(async () => { // then get the ad stuff var requests = []; var adPromises: Array<Promise<void>> = []; for (let sitegroup of securityInfo.siteGroups) { for (let adGroupId of sitegroup.adGroupIds) { // need to do this in batch var adPromise = this.fetchAdGroup(aadHttpClient, adGroupId) .then((adGroup) => { securityInfo.adGroups.push(adGroup); for (var adUser of adGroup.members) { var siteUser = find(securityInfo.siteUsers, (su, key) => { return su.upn === adUser.userPrincipalName.toLowerCase(); }); if (siteUser) { siteUser.adId = adUser.id; } else { let user: SPSiteUser = new SPSiteUser(); user.adId = adUser.id; user.name = adUser.displayName + "*"; user.upn = adUser.userPrincipalName ? adUser.userPrincipalName : adUser.displayName; user.isSelected = true; user.principalType = -1; securityInfo.siteUsers.push(user); } } } ) .catch((err) => { debugger; }); adPromises.push(adPromise); } } await Promise.all(adPromises); console.table(securityInfo.siteUsers); debugger; return securityInfo; }).catch((error) => { debugger; // error in batch throw errors; }); } private fetchAdGroup(aadHttpClient: AadHttpClient, adGrouId: ADGroupId): Promise<ADGroup> { var aadHttpClientConfiguration: AadHttpClientConfiguration = new AadHttpClientConfiguration({}, {}); // note im not loading nested groups here. Will need to load them on the fly? or maybe here?nvrmind return aadHttpClient.get(`https://graph.microsoft.com/v1.0/groups/${adGrouId.ADId}/transitiveMembers`, aadHttpClientConfiguration) .then((adResponse) => { return adResponse.json() .then((data) => { let adGroup: ADGroup = new ADGroup(); adGroup.id = adGrouId; adGroup.members = data.value; return adGroup; }).catch((err) => { debugger; alert(`error converting to json`); return null; }); }).catch((err) => { debugger; //if 403 show message to grant security alert(`grant app SharePoint Online Client Extensibility Web Application Principal graph permissions Group.Read.All & GroupMembers.Read.All`); return null; }); } }
the_stack
import { reactive, shallowReactive } from "../reactive" import { isProxy, isReactive, markRaw, toRaw } from "../utils" import { computed, isRef, ref } from "../ref" import { createEffect } from "../effect" describe("reactive", () => { it("should create a deep proxy", () => { let subject, expected subject = reactive({ count: { value: 0 } }) expected = true expect(isProxy(subject)).toBe(expected) expect(isProxy(subject.count)).toBe(expected) }) it("should set a plain value", () => { let subject, expected subject = reactive({ value: {} }) expected = { count: 2 } subject.value = expected expect(subject.value).not.toBe(expected) expect(toRaw(subject).value).toBe(expected) expect(subject.value).toBe(subject.value) expect(subject.value).toEqual(expected) }) it("should unwrap and create a two-way binding with refs", () => { let value, subject, expected value = ref(0) subject = reactive({ value }) expected = 2 subject.value = expected expect(subject.value).toBe(expected) expect(value.value).toBe(expected) expected = 10 value.value = expected expect(subject.value).toBe(expected) expect(value.value).toBe(expected) }) it("should create a shallow proxy", () => { let subject, expected subject = shallowReactive({ count: { value: 0 } }) expected = true expect(isProxy(subject)).toBe(expected) expect(isProxy(subject.count)).not.toBe(expected) }) it("should return the raw value", () => { let subject, expected expected = { count: { value: 0 } } subject = reactive(expected) expect(toRaw(subject)).toBe(expected) expect(toRaw(subject.count)).toBe(expected.count) expect(toRaw(expected)).toBe(expected) }) test("Object", () => { const original = { foo: 1 } const observed = reactive(original) expect(observed).not.toBe(original) expect(isReactive(observed)).toBe(true) expect(isReactive(original)).toBe(false) // get expect(observed.foo).toBe(1) // has expect("foo" in observed).toBe(true) // ownKeys expect(Object.keys(observed)).toEqual(["foo"]) }) test("proto", () => { const obj = {} const reactiveObj = reactive(obj) expect(isReactive(reactiveObj)).toBe(true) // read prop of reactiveObject will cause reactiveObj[prop] to be reactive // @ts-ignore const prototype = reactiveObj["__proto__"] const otherObj = { data: ["a"] } expect(isReactive(otherObj)).toBe(false) const reactiveOther = reactive(otherObj) expect(isReactive(reactiveOther)).toBe(true) expect(reactiveOther.data[0]).toBe("a") }) test("nested reactives", () => { const original = { nested: { foo: 1, }, array: [{ bar: 2 }], } const observed = reactive(original) expect(isReactive(observed.nested)).toBe(true) expect(isReactive(observed.array)).toBe(true) expect(isReactive(observed.array[0])).toBe(true) }) test("observed value should proxy mutations to original (Object)", () => { const original: any = { foo: 1 } const observed = reactive(original) // set observed.bar = 1 expect(observed.bar).toBe(1) expect(original.bar).toBe(1) // delete delete observed.foo expect("foo" in observed).toBe(false) expect("foo" in original).toBe(false) }) test("setting a property with an unobserved value should wrap with reactive", () => { const observed = reactive<{ foo?: object }>({}) const raw = {} observed.foo = raw expect(observed.foo).not.toBe(raw) expect(isReactive(observed.foo)).toBe(true) }) test("observing already observed value should return same Proxy", () => { const original = { foo: 1 } const observed = reactive(original) const observed2 = reactive(observed) expect(observed2).toBe(observed) }) test("observing the same value multiple times should return same Proxy", () => { const original = { foo: 1 } const observed = reactive(original) const observed2 = reactive(original) expect(observed2).toBe(observed) }) test("should not pollute original object with Proxies", () => { const original: any = { foo: 1 } const original2 = { bar: 2 } const observed = reactive(original) const observed2 = reactive(original2) observed.bar = observed2 expect(observed.bar).toBe(observed2) expect(original.bar).toBe(original2) }) test("unwrap", () => { const original = { foo: 1 } const observed = reactive(original) expect(toRaw(observed)).toBe(original) expect(toRaw(original)).toBe(original) }) test("should not unwrap Ref<T>", () => { const observedNumberRef = reactive(ref(1)) const observedObjectRef = reactive(ref({ foo: 1 })) expect(isRef(observedNumberRef)).toBe(true) expect(isRef(observedObjectRef)).toBe(true) }) test("should unwrap computed refs", () => { // readonly const a = computed(() => 1) // writable const b = computed({ get: () => 1, set: () => {}, }) const obj = reactive({ a, b }) // check type obj.a + 1 obj.b + 1 expect(typeof obj.a).toBe(`number`) expect(typeof obj.b).toBe(`number`) }) test("non-observable values", () => { // const assertValue = (value: any) => { // reactive(value) // expect( // `value cannot be made reactive: ${String(value)}` // ).toHaveBeenWarnedLast() // } // // // number // assertValue(1) // // string // assertValue('foo') // // boolean // assertValue(false) // // null // assertValue(null) // // undefined // assertValue(undefined) // // symbol // const s = Symbol() // assertValue(s) // built-ins should work and return same value const p = Promise.resolve() expect(reactive(p)).toBe(p) const r = new RegExp("") expect(reactive(r)).toBe(r) const d = new Date() expect(reactive(d)).toBe(d) }) test("markRaw", () => { const obj = reactive({ foo: { a: 1 }, bar: markRaw({ b: 2 }), }) expect(isReactive(obj.foo)).toBe(true) expect(isReactive(obj.bar)).toBe(false) }) test("should not observe frozen objects", () => { const obj = reactive({ foo: Object.freeze({ a: 1 }), }) expect(isReactive(obj.foo)).toBe(false) }) describe("shallowReactive", () => { test("should not make non-reactive properties reactive", () => { const props = shallowReactive({ n: { foo: 1 } }) expect(isReactive(props.n)).toBe(false) }) test("should keep reactive properties reactive", () => { const props: any = shallowReactive({ n: reactive({ foo: 1 }) }) props.n = reactive({ foo: 2 }) expect(isReactive(props.n)).toBe(true) }) test("should not observe when iterating", () => { const shallowSet = shallowReactive(new Set()) const a = {} shallowSet.add(a) const spreadA = [...shallowSet][0] expect(isReactive(spreadA)).toBe(false) }) test("should not get reactive entry", () => { const shallowMap = shallowReactive(new Map()) const a = {} const key = "a" shallowMap.set(key, a) expect(isReactive(shallowMap.get(key))).toBe(false) }) test("should not get reactive on foreach", () => { const shallowSet = shallowReactive(new Set()) const a = {} shallowSet.add(a) shallowSet.forEach((x) => expect(isReactive(x)).toBe(false)) }) }) }) describe("reactive array", () => { test("should make Array reactive", () => { const original = [{ foo: 1 }] const observed = reactive(original) expect(observed).not.toBe(original) expect(isProxy(observed)).toBe(true) expect(isProxy(original)).toBe(false) expect(isProxy(observed[0])).toBe(true) // get expect(observed[0].foo).toBe(1) // has expect(0 in observed).toBe(true) // ownKeys expect(Object.keys(observed)).toEqual(["0"]) }) test("cloned reactive Array should point to observed values", () => { const original = [{ foo: 1 }] const observed = reactive(original) const clone = observed.slice() expect(isProxy(clone[0])).toBe(true) expect(clone[0]).not.toBe(original[0]) expect(clone[0]).toBe(observed[0]) }) test("observed value should proxy mutations to original (Array)", () => { const original: any[] = [{ foo: 1 }, { bar: 2 }] const observed = reactive(original) // set const value = { baz: 3 } const reactiveValue = reactive(value) observed[0] = value expect(observed[0]).toBe(reactiveValue) expect(original[0]).toBe(value) // delete delete observed[0] expect(observed[0]).toBeUndefined() expect(original[0]).toBeUndefined() // mutating methods observed.push(value) expect(observed[2]).toBe(reactiveValue) expect(original[2]).toBe(value) }) test("Array identity methods should work with raw values", () => { const raw = {} const arr = reactive([{}, {}]) arr.push(raw) expect(arr.indexOf(raw)).toBe(2) expect(arr.indexOf(raw, 3)).toBe(-1) expect(arr.includes(raw)).toBe(true) expect(arr.includes(raw, 3)).toBe(false) expect(arr.lastIndexOf(raw)).toBe(2) expect(arr.lastIndexOf(raw, 1)).toBe(-1) // should work also for the observed version const observed = arr[2] expect(arr.indexOf(observed)).toBe(2) expect(arr.indexOf(observed, 3)).toBe(-1) expect(arr.includes(observed)).toBe(true) expect(arr.includes(observed, 3)).toBe(false) expect(arr.lastIndexOf(observed)).toBe(2) expect(arr.lastIndexOf(observed, 1)).toBe(-1) }) test("Array identity methods should work if raw value contains reactive objects", () => { const raw = [] const obj = reactive({}) raw.push(obj) const arr = reactive(raw) expect(arr.includes(obj)).toBe(true) }) test("Array identity methods should be reactive", () => { const obj = {} const arr = reactive([obj, {}]) let index: number = -1 createEffect(() => { index = arr.indexOf(obj) }) expect(index).toBe(0) arr.reverse() expect(index).toBe(1) }) test("delete on Array should not trigger length dependency", () => { const arr = reactive([1, 2, 3]) const fn = jest.fn() createEffect(() => { fn(arr.length) }) expect(fn).toHaveBeenCalledTimes(1) delete arr[1] expect(fn).toHaveBeenCalledTimes(1) }) describe("Array methods w/ refs", () => { let original: any[] beforeEach(() => { original = reactive([1, ref(2)]) }) // read + copy test("read only copy methods", () => { const res = original.concat([3, ref(4)]) const raw = toRaw(res) expect(isRef(raw[1])).toBe(true) expect(isRef(raw[3])).toBe(true) }) // read + write test("read + write mutating methods", () => { const res = original.copyWithin(0, 1, 2) const raw = toRaw(res) expect(isRef(raw[0])).toBe(true) expect(isRef(raw[1])).toBe(true) }) test("read + identity", () => { const ref = original[1] expect(ref).toBe(toRaw(original)[1]) expect(original.indexOf(ref)).toBe(1) }) }) })
the_stack
import expandTilde = require('expand-tilde'); import { RevealOutputChannelOn as RevealOutputChannelOnEnum } from 'vscode-languageclient'; import { ConfigurationParameter } from '../../ConfigurationParameter'; import { FileSystem } from '../file_system/FileSystem'; import { Rustup } from './Rustup'; import { RustSource } from './RustSource'; /** * This class provides functionality related to RLS configuration */ export class RlsConfiguration { private _useRustfmtConfigurationParameter: ConfigurationParameters.UseRustfmt; private _rustup: Rustup | undefined; private _rustSource: RustSource; private _executableUserPath: string | undefined; private _userArgs: string[]; private _userEnv: object; private _revealOutputChannelOn: RevealOutputChannelOnEnum; private _useRustfmt: boolean | undefined; /** * Creates a new instance of the class * @param rustup The rustup object * @param rustSource The rust's source object */ public static async create(rustup: Rustup | undefined, rustSource: RustSource): Promise<RlsConfiguration> { const rlsExecutableConfigurationParameter = new ConfigurationParameters.Executable(); const executableUserPath = await rlsExecutableConfigurationParameter.getCheckedExecutable(); return new RlsConfiguration(rustup, rustSource, executableUserPath); } /** * Returns if there is some executable path specified by the user */ public isExecutableUserPathSet(): boolean { return this._executableUserPath !== undefined; } /** * Returns a path to RLS executable */ public getExecutablePath(): string | undefined { if (this._executableUserPath) { return this._executableUserPath; } if (this._rustup && this._rustup.isRlsInstalled()) { return 'rustup'; } return undefined; } /** * Returns arguments for RLS */ public getArgs(): string[] { // When the user specifies some executable path, the user expects the extension not to add // some arguments if (this._executableUserPath === undefined && this._rustup && this._rustup.isRlsInstalled()) { const userToolchain = this._rustup.getUserNightlyToolchain(); if (!userToolchain) { // It is actually impossible because `isRlsInstalled` uses `getUserNightlyToolchain` return this._userArgs; } return ['run', userToolchain.toString(true, false), 'rls'].concat(this._userArgs); } else { return this._userArgs; } } /** * Returns environment to run RLS in */ public getEnv(): object { const env: any = Object.assign({}, this._userEnv); if (!env.RUST_SRC_PATH) { const rustSourcePath = this._rustSource.getPath(); if (rustSourcePath) { env.RUST_SRC_PATH = rustSourcePath; } } return env; } /** * Returns how the output channel of RLS should behave when receiving messages */ public getRevealOutputChannelOn(): RevealOutputChannelOnEnum { return this._revealOutputChannelOn; } /** * Returns whether rustfmt should be used for formatting */ public getUseRustfmt(): boolean | undefined { return this._useRustfmt; } /** * Updates the property "useRustfmt" in the user configuration * @param value The new value */ public setUseRustfmt(value: boolean | undefined): void { if (this._useRustfmt === value) { return; } this._useRustfmt = value; this._useRustfmtConfigurationParameter.setUseRustfmt(value); } private constructor(rustup: Rustup | undefined, rustSource: RustSource, executableUserPath: string | undefined) { this._useRustfmtConfigurationParameter = new ConfigurationParameters.UseRustfmt(); this._rustup = rustup; this._rustSource = rustSource; this._executableUserPath = executableUserPath; this._userArgs = new ConfigurationParameters.Args().getArgs(); this._userEnv = new ConfigurationParameters.Env().getEnv(); this._revealOutputChannelOn = new ConfigurationParameters.RevealOutputChannelOn().getRevealOutputChannelOn(); this._useRustfmt = this._useRustfmtConfigurationParameter.getUseRustfmt(); } } namespace ConfigurationParameters { const RLS_CONFIGURATION_PARAMETER_SECTION = 'rust.rls'; /** * The wrapper around the configuration parameter of the RLS executable */ export class Executable { /** * The configuration parameter of the RLS executable */ private _parameter: ConfigurationParameter; public constructor() { this._parameter = new ConfigurationParameter(RLS_CONFIGURATION_PARAMETER_SECTION, 'executable'); } /** * Gets the executable from the configuration, checks if it exists and returns it * @return The existing executable from the configuration */ public async getCheckedExecutable(): Promise<string | undefined> { const executable = this._parameter.getValue(); // It is either string or `null`, but VSCode doens't prevent us from putting a number // here if (!(typeof executable === 'string')) { return undefined; } // If we passed the previous check, then it is a string, but it may be an empty string. In // that case we return `undefined` because an empty string is not valid path if (!executable) { return undefined; } // The user may input `~/.cargo/bin/rls` and expect it to work const tildeExpandedExecutable = expandTilde(executable); // We have to check if the path exists because otherwise the language server wouldn't start const foundExecutable = await FileSystem.findExecutablePath(tildeExpandedExecutable); return foundExecutable; } } /** * The wrapper around the configuration parameter of the RLS arguments */ export class Args { /** * The configuration parameter of the RLS arguments */ private _parameter: ConfigurationParameter; public constructor() { this._parameter = new ConfigurationParameter(RLS_CONFIGURATION_PARAMETER_SECTION, 'args'); } /** * Gets the arguments from the configuration and returns them * @return The arguments */ public getArgs(): string[] { const args = this._parameter.getValue(); // It is either array or `null`, but VSCode doens't prevent us from putting a number // here if (!(args instanceof Array)) { return []; } return args; } } /** * The wrapper around the configuration parameter of the RLS environment */ export class Env { /** * The configuration parameter of the RLS environment */ private _parameter: ConfigurationParameter; public constructor() { this._parameter = new ConfigurationParameter(RLS_CONFIGURATION_PARAMETER_SECTION, 'env'); } /** * Gets the environment from the configuration and returns it * @return The environment */ public getEnv(): object { const env = this._parameter.getValue(); // It is either object or `null`, but VSCode doens't prevent us from putting a number // here if (!(typeof env === 'object')) { return {}; } return env; } } /** * The wrapper around the configuration parameter specifying on what kind of message the output * channel is revealed */ export class RevealOutputChannelOn { /** * The configuration parameter specifying on what kind of message the output channel is * revealed */ private _parameter: ConfigurationParameter; public constructor() { this._parameter = new ConfigurationParameter(RLS_CONFIGURATION_PARAMETER_SECTION, 'revealOutputChannelOn'); } /** * Gets the value specifying on what kind of message the output channel is revealed from * the configuration and returns it * @return The environment */ public getRevealOutputChannelOn(): RevealOutputChannelOnEnum { const revealOutputChannelOn = this._parameter.getValue(); switch (revealOutputChannelOn) { case 'info': return RevealOutputChannelOnEnum.Info; case 'warn': return RevealOutputChannelOnEnum.Warn; case 'error': return RevealOutputChannelOnEnum.Error; case 'never': return RevealOutputChannelOnEnum.Never; default: return RevealOutputChannelOnEnum.Error; } } } /** * The wrapper around the configuration parameter specifying if rustfmt is used to format code */ export class UseRustfmt { /** * The configuration parameter specifying if rustfmt is used to format code */ private _parameter: ConfigurationParameter; public constructor() { this._parameter = new ConfigurationParameter(RLS_CONFIGURATION_PARAMETER_SECTION, 'useRustfmt'); } /** * Gets the flag specifying if rustfmt is used to format code from the configuration and returns it * @return The environment */ public getUseRustfmt(): boolean | undefined { const useRustfmt = this._parameter.getValue(); // It is either booleans or `null`, but VSCode doens't prevent us from putting a number // here if (!(typeof useRustfmt === 'boolean')) { return undefined; } return useRustfmt; } /** * Sets the value to the configuration * @param useRustfmt The new value */ public setUseRustfmt(useRustfmt: boolean | undefined): void { this._parameter.setValue(useRustfmt, true); } } }
the_stack
import { SerializableHash } from "@stablelib/hash"; import { readUint32LE, writeUint32LE } from "@stablelib/binary"; import { wipe } from "@stablelib/wipe"; export const BLOCK_SIZE = 64; export const DIGEST_LENGTH = 32; export const KEY_LENGTH = 32; export const PERSONALIZATION_LENGTH = 8; export const SALT_LENGTH = 8; export const MAX_LEAF_SIZE = Math.pow(2, 32) - 1; export const MAX_NODE_OFFSET = Math.pow(2, 48) - 1; export const MAX_FANOUT = 255; export const MAX_MAX_DEPTH = 255; // not a typo /** * Configuration for hash function. */ export type Config = { key?: Uint8Array; salt?: Uint8Array; personalization?: Uint8Array; tree?: Tree; }; /** * Tree hashing parameters. */ export type Tree = { fanout: number; // fanout maxDepth: number; // maximal depth leafSize: number; // leaf maximal byte length (0 for unlimited) nodeOffset: number; // node offset (0 for first, leftmost or leaf), max 2⁴⁸-1 nodeDepth: number; // node depth (0 for leaves) innerDigestLength: number; // inner digest length lastNode: boolean; // indicates processing of the last node of layer }; const IV = new Uint32Array([ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]); /** * BLAKE2s hash function. */ export class BLAKE2s implements SerializableHash { readonly blockSize = BLOCK_SIZE; private _state = new Uint32Array(IV); // hash state, initialized with IV private _buffer = new Uint8Array(BLOCK_SIZE); // buffer for data private _bufferLength = 0; // number of bytes in buffer private _ctr0 = 0; // low bits of byte counter private _ctr1 = 0; // high bits of byte counter private _flag0 = 0; private _flag1 = 0; private _lastNode = false; private _finished = false; private _paddedKey: Uint8Array | undefined; // copy of zero-padded key if present private _initialState: Uint32Array; // initial state after initialization constructor(public digestLength = 32, config?: Config) { // Validate digest length. if (digestLength < 1 || digestLength > DIGEST_LENGTH) { throw new Error("blake2s: wrong digest length"); } // Validate config, if present. if (config) { this.validateConfig(config); } // Get key length from config. let keyLength = 0; if (config && config.key) { keyLength = config.key.length; } // Get tree fanout and maxDepth from config. let fanout = 1; let maxDepth = 1; if (config && config.tree) { fanout = config.tree.fanout; maxDepth = config.tree.maxDepth; } // Xor common parameters into state. this._state[0] ^= digestLength | (keyLength << 8) | (fanout << 16) | (maxDepth << 24); // Xor tree parameters into state. if (config && config.tree) { this._state[1] ^= config.tree.leafSize; const nofHi = config.tree.nodeOffset / 0x100000000 >>> 0; const nofLo = config.tree.nodeOffset >>> 0; this._state[2] ^= nofLo; this._state[3] ^= nofHi | (config.tree.nodeDepth << 16) | (config.tree.innerDigestLength << 24); this._lastNode = config.tree.lastNode; } // Xor salt into state. if (config && config.salt) { this._state[4] ^= readUint32LE(config.salt, 0); this._state[5] ^= readUint32LE(config.salt, 4); } // Xor personalization into state. if (config && config.personalization) { this._state[6] ^= readUint32LE(config.personalization, 0); this._state[7] ^= readUint32LE(config.personalization, 4); } // Save a copy of initialized state for reset. this._initialState = new Uint32Array(this._state); // Process key. if (config && config.key && keyLength > 0) { this._paddedKey = new Uint8Array(BLOCK_SIZE); this._paddedKey.set(config.key); // Put padded key into buffer. this._buffer.set(this._paddedKey); this._bufferLength = BLOCK_SIZE; } } reset(): this { // Restore initial state. this._state.set(this._initialState); if (this._paddedKey) { // Put padded key into buffer. this._buffer.set(this._paddedKey); this._bufferLength = BLOCK_SIZE; } else { this._bufferLength = 0; } // Clear counters and flags. this._ctr0 = 0; this._ctr1 = 0; this._flag0 = 0; this._flag1 = 0; this._finished = false; return this; } validateConfig(config: Config) { if (config.key && config.key.length > KEY_LENGTH) { throw new Error("blake2s: wrong key length"); } if (config.salt && config.salt.length !== SALT_LENGTH) { throw new Error("blake2s: wrong salt length"); } if (config.personalization && config.personalization.length !== PERSONALIZATION_LENGTH) { throw new Error("blake2s: wrong personalization length"); } if (config.tree) { if (config.tree.fanout < 0 || config.tree.fanout > MAX_FANOUT) { throw new Error("blake2s: wrong tree fanout"); } if (config.tree.maxDepth < 0 || config.tree.maxDepth > MAX_MAX_DEPTH) { throw new Error("blake2s: wrong tree depth"); } if (config.tree.leafSize < 0 || config.tree.leafSize > MAX_LEAF_SIZE) { throw new Error("blake2s: wrong leaf size"); } if (config.tree.innerDigestLength < 0 || config.tree.innerDigestLength > DIGEST_LENGTH) { throw new Error("blake2s: wrong tree inner digest length"); } if (config.tree.nodeOffset < 0 || config.tree.nodeOffset > MAX_NODE_OFFSET) { throw new Error("blake2s: tree node offset is too large"); } } } update(data: Uint8Array, dataLength = data.length): this { if (this._finished) { throw new Error("blake2s: can't update because hash was finished."); } const left = BLOCK_SIZE - this._bufferLength; let dataPos = 0; if (dataLength === 0) { return this; } // Finish buffer. if (dataLength > left) { for (let i = 0; i < left; i++) { this._buffer[this._bufferLength + i] = data[dataPos + i]; } this._processBlock(BLOCK_SIZE); dataPos += left; dataLength -= left; this._bufferLength = 0; } // Process data blocks. while (dataLength > BLOCK_SIZE) { for (let i = 0; i < BLOCK_SIZE; i++) { this._buffer[i] = data[dataPos + i]; } this._processBlock(BLOCK_SIZE); dataPos += BLOCK_SIZE; dataLength -= BLOCK_SIZE; this._bufferLength = 0; } // Copy leftovers to buffer. for (let i = 0; i < dataLength; i++) { this._buffer[this._bufferLength + i] = data[dataPos + i]; } this._bufferLength += dataLength; return this; } finish(out: Uint8Array): this { if (!this._finished) { for (let i = this._bufferLength; i < BLOCK_SIZE; i++) { this._buffer[i] = 0; } // Set last block flag. this._flag0 = 0xffffffff; // Set last node flag if last node in tree. if (this._lastNode) { this._flag1 = 0xffffffff; } this._processBlock(this._bufferLength); this._finished = true; } // Reuse buffer as temporary space for digest. const tmp = this._buffer.subarray(0, 32); for (let i = 0; i < 8; i++) { writeUint32LE(this._state[i], tmp, i * 4); } out.set(tmp.subarray(0, out.length)); return this; } digest(): Uint8Array { const out = new Uint8Array(this.digestLength); this.finish(out); return out; } clean() { wipe(this._state); wipe(this._buffer); wipe(this._initialState); if (this._paddedKey) { wipe(this._paddedKey); } this._bufferLength = 0; this._ctr0 = 0; this._ctr1 = 0; this._flag0 = 0; this._flag1 = 0; this._lastNode = false; this._finished = false; } saveState(): SavedState { if (this._finished) { throw new Error("blake2s: cannot save finished state"); } return { state: new Uint32Array(this._state), buffer: new Uint8Array(this._buffer), bufferLength: this._bufferLength, ctr0: this._ctr0, ctr1: this._ctr1, flag0: this._flag0, flag1: this._flag1, lastNode: this._lastNode, paddedKey: this._paddedKey ? new Uint8Array(this._paddedKey) : undefined, initialState: new Uint32Array(this._initialState) }; } restoreState(savedState: SavedState): this { this._state.set(savedState.state); this._buffer.set(savedState.buffer); this._bufferLength = savedState.bufferLength; this._ctr0 = savedState.ctr0; this._ctr1 = savedState.ctr1; this._flag0 = savedState.flag0; this._flag1 = savedState.flag1; this._lastNode = savedState.lastNode; if (this._paddedKey) { wipe(this._paddedKey); } this._paddedKey = savedState.paddedKey ? new Uint8Array(savedState.paddedKey) : undefined; this._initialState.set(savedState.initialState); return this; } cleanSavedState(savedState: SavedState): void { wipe(savedState.state); wipe(savedState.buffer); wipe(savedState.initialState); if (savedState.paddedKey) { wipe(savedState.paddedKey); } savedState.bufferLength = 0; savedState.ctr0 = 0; savedState.ctr1 = 0; savedState.flag0 = 0; savedState.flag1 = 0; savedState.lastNode = false; } private _processBlock(length: number) { let nc = this._ctr0 + length; this._ctr0 = nc >>> 0; if (nc !== this._ctr0) { this._ctr1++; } let v0 = this._state[0], v1 = this._state[1], v2 = this._state[2], v3 = this._state[3], v4 = this._state[4], v5 = this._state[5], v6 = this._state[6], v7 = this._state[7], v8 = IV[0], v9 = IV[1], v10 = IV[2], v11 = IV[3], v12 = IV[4] ^ this._ctr0, v13 = IV[5] ^ this._ctr1, v14 = IV[6] ^ this._flag0, v15 = IV[7] ^ this._flag1; const x = this._buffer; const m0 = (x[3] << 24) | (x[2] << 16) | (x[1] << 8) | x[0]; const m1 = (x[7] << 24) | (x[6] << 16) | (x[5] << 8) | x[4]; const m2 = (x[11] << 24) | (x[10] << 16) | (x[9] << 8) | x[8]; const m3 = (x[15] << 24) | (x[14] << 16) | (x[13] << 8) | x[12]; const m4 = (x[19] << 24) | (x[18] << 16) | (x[17] << 8) | x[16]; const m5 = (x[23] << 24) | (x[22] << 16) | (x[21] << 8) | x[20]; const m6 = (x[27] << 24) | (x[26] << 16) | (x[25] << 8) | x[24]; const m7 = (x[31] << 24) | (x[30] << 16) | (x[29] << 8) | x[28]; const m8 = (x[35] << 24) | (x[34] << 16) | (x[33] << 8) | x[32]; const m9 = (x[39] << 24) | (x[38] << 16) | (x[37] << 8) | x[36]; const m10 = (x[43] << 24) | (x[42] << 16) | (x[41] << 8) | x[40]; const m11 = (x[47] << 24) | (x[46] << 16) | (x[45] << 8) | x[44]; const m12 = (x[51] << 24) | (x[50] << 16) | (x[49] << 8) | x[48]; const m13 = (x[55] << 24) | (x[54] << 16) | (x[53] << 8) | x[52]; const m14 = (x[59] << 24) | (x[58] << 16) | (x[57] << 8) | x[56]; const m15 = (x[63] << 24) | (x[62] << 16) | (x[61] << 8) | x[60]; // Round 1. v0 = v0 + m0 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 16) | v12 >>> 16; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 12) | v4 >>> 12; v1 = v1 + m2 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 16) | v13 >>> 16; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 12) | v5 >>> 12; v2 = v2 + m4 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 16) | v14 >>> 16; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 12) | v6 >>> 12; v3 = v3 + m6 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 16) | v15 >>> 16; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 12) | v7 >>> 12; v2 = v2 + m5 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 8) | v14 >>> 8; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 7) | v6 >>> 7; v3 = v3 + m7 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 8) | v15 >>> 8; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 7) | v7 >>> 7; v1 = v1 + m3 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 8) | v13 >>> 8; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 7) | v5 >>> 7; v0 = v0 + m1 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 8) | v12 >>> 8; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 7) | v4 >>> 7; v0 = v0 + m8 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 16) | v15 >>> 16; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 12) | v5 >>> 12; v1 = v1 + m10 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 16) | v12 >>> 16; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 12) | v6 >>> 12; v2 = v2 + m12 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 16) | v13 >>> 16; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 12) | v7 >>> 12; v3 = v3 + m14 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 16) | v14 >>> 16; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 12) | v4 >>> 12; v2 = v2 + m13 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 8) | v13 >>> 8; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 7) | v7 >>> 7; v3 = v3 + m15 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 8) | v14 >>> 8; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 7) | v4 >>> 7; v1 = v1 + m11 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 8) | v12 >>> 8; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 7) | v6 >>> 7; v0 = v0 + m9 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 8) | v15 >>> 8; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 7) | v5 >>> 7; // Round 2. v0 = v0 + m14 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 16) | v12 >>> 16; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 12) | v4 >>> 12; v1 = v1 + m4 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 16) | v13 >>> 16; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 12) | v5 >>> 12; v2 = v2 + m9 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 16) | v14 >>> 16; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 12) | v6 >>> 12; v3 = v3 + m13 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 16) | v15 >>> 16; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 12) | v7 >>> 12; v2 = v2 + m15 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 8) | v14 >>> 8; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 7) | v6 >>> 7; v3 = v3 + m6 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 8) | v15 >>> 8; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 7) | v7 >>> 7; v1 = v1 + m8 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 8) | v13 >>> 8; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 7) | v5 >>> 7; v0 = v0 + m10 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 8) | v12 >>> 8; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 7) | v4 >>> 7; v0 = v0 + m1 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 16) | v15 >>> 16; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 12) | v5 >>> 12; v1 = v1 + m0 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 16) | v12 >>> 16; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 12) | v6 >>> 12; v2 = v2 + m11 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 16) | v13 >>> 16; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 12) | v7 >>> 12; v3 = v3 + m5 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 16) | v14 >>> 16; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 12) | v4 >>> 12; v2 = v2 + m7 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 8) | v13 >>> 8; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 7) | v7 >>> 7; v3 = v3 + m3 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 8) | v14 >>> 8; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 7) | v4 >>> 7; v1 = v1 + m2 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 8) | v12 >>> 8; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 7) | v6 >>> 7; v0 = v0 + m12 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 8) | v15 >>> 8; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 7) | v5 >>> 7; // Round 3. v0 = v0 + m11 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 16) | v12 >>> 16; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 12) | v4 >>> 12; v1 = v1 + m12 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 16) | v13 >>> 16; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 12) | v5 >>> 12; v2 = v2 + m5 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 16) | v14 >>> 16; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 12) | v6 >>> 12; v3 = v3 + m15 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 16) | v15 >>> 16; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 12) | v7 >>> 12; v2 = v2 + m2 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 8) | v14 >>> 8; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 7) | v6 >>> 7; v3 = v3 + m13 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 8) | v15 >>> 8; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 7) | v7 >>> 7; v1 = v1 + m0 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 8) | v13 >>> 8; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 7) | v5 >>> 7; v0 = v0 + m8 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 8) | v12 >>> 8; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 7) | v4 >>> 7; v0 = v0 + m10 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 16) | v15 >>> 16; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 12) | v5 >>> 12; v1 = v1 + m3 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 16) | v12 >>> 16; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 12) | v6 >>> 12; v2 = v2 + m7 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 16) | v13 >>> 16; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 12) | v7 >>> 12; v3 = v3 + m9 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 16) | v14 >>> 16; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 12) | v4 >>> 12; v2 = v2 + m1 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 8) | v13 >>> 8; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 7) | v7 >>> 7; v3 = v3 + m4 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 8) | v14 >>> 8; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 7) | v4 >>> 7; v1 = v1 + m6 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 8) | v12 >>> 8; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 7) | v6 >>> 7; v0 = v0 + m14 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 8) | v15 >>> 8; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 7) | v5 >>> 7; // Round 4. v0 = v0 + m7 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 16) | v12 >>> 16; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 12) | v4 >>> 12; v1 = v1 + m3 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 16) | v13 >>> 16; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 12) | v5 >>> 12; v2 = v2 + m13 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 16) | v14 >>> 16; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 12) | v6 >>> 12; v3 = v3 + m11 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 16) | v15 >>> 16; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 12) | v7 >>> 12; v2 = v2 + m12 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 8) | v14 >>> 8; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 7) | v6 >>> 7; v3 = v3 + m14 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 8) | v15 >>> 8; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 7) | v7 >>> 7; v1 = v1 + m1 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 8) | v13 >>> 8; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 7) | v5 >>> 7; v0 = v0 + m9 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 8) | v12 >>> 8; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 7) | v4 >>> 7; v0 = v0 + m2 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 16) | v15 >>> 16; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 12) | v5 >>> 12; v1 = v1 + m5 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 16) | v12 >>> 16; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 12) | v6 >>> 12; v2 = v2 + m4 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 16) | v13 >>> 16; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 12) | v7 >>> 12; v3 = v3 + m15 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 16) | v14 >>> 16; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 12) | v4 >>> 12; v2 = v2 + m0 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 8) | v13 >>> 8; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 7) | v7 >>> 7; v3 = v3 + m8 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 8) | v14 >>> 8; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 7) | v4 >>> 7; v1 = v1 + m10 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 8) | v12 >>> 8; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 7) | v6 >>> 7; v0 = v0 + m6 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 8) | v15 >>> 8; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 7) | v5 >>> 7; // Round 5. v0 = v0 + m9 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 16) | v12 >>> 16; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 12) | v4 >>> 12; v1 = v1 + m5 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 16) | v13 >>> 16; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 12) | v5 >>> 12; v2 = v2 + m2 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 16) | v14 >>> 16; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 12) | v6 >>> 12; v3 = v3 + m10 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 16) | v15 >>> 16; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 12) | v7 >>> 12; v2 = v2 + m4 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 8) | v14 >>> 8; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 7) | v6 >>> 7; v3 = v3 + m15 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 8) | v15 >>> 8; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 7) | v7 >>> 7; v1 = v1 + m7 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 8) | v13 >>> 8; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 7) | v5 >>> 7; v0 = v0 + m0 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 8) | v12 >>> 8; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 7) | v4 >>> 7; v0 = v0 + m14 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 16) | v15 >>> 16; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 12) | v5 >>> 12; v1 = v1 + m11 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 16) | v12 >>> 16; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 12) | v6 >>> 12; v2 = v2 + m6 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 16) | v13 >>> 16; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 12) | v7 >>> 12; v3 = v3 + m3 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 16) | v14 >>> 16; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 12) | v4 >>> 12; v2 = v2 + m8 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 8) | v13 >>> 8; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 7) | v7 >>> 7; v3 = v3 + m13 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 8) | v14 >>> 8; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 7) | v4 >>> 7; v1 = v1 + m12 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 8) | v12 >>> 8; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 7) | v6 >>> 7; v0 = v0 + m1 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 8) | v15 >>> 8; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 7) | v5 >>> 7; // Round 6. v0 = v0 + m2 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 16) | v12 >>> 16; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 12) | v4 >>> 12; v1 = v1 + m6 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 16) | v13 >>> 16; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 12) | v5 >>> 12; v2 = v2 + m0 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 16) | v14 >>> 16; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 12) | v6 >>> 12; v3 = v3 + m8 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 16) | v15 >>> 16; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 12) | v7 >>> 12; v2 = v2 + m11 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 8) | v14 >>> 8; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 7) | v6 >>> 7; v3 = v3 + m3 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 8) | v15 >>> 8; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 7) | v7 >>> 7; v1 = v1 + m10 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 8) | v13 >>> 8; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 7) | v5 >>> 7; v0 = v0 + m12 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 8) | v12 >>> 8; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 7) | v4 >>> 7; v0 = v0 + m4 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 16) | v15 >>> 16; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 12) | v5 >>> 12; v1 = v1 + m7 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 16) | v12 >>> 16; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 12) | v6 >>> 12; v2 = v2 + m15 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 16) | v13 >>> 16; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 12) | v7 >>> 12; v3 = v3 + m1 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 16) | v14 >>> 16; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 12) | v4 >>> 12; v2 = v2 + m14 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 8) | v13 >>> 8; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 7) | v7 >>> 7; v3 = v3 + m9 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 8) | v14 >>> 8; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 7) | v4 >>> 7; v1 = v1 + m5 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 8) | v12 >>> 8; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 7) | v6 >>> 7; v0 = v0 + m13 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 8) | v15 >>> 8; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 7) | v5 >>> 7; // Round 7. v0 = v0 + m12 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 16) | v12 >>> 16; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 12) | v4 >>> 12; v1 = v1 + m1 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 16) | v13 >>> 16; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 12) | v5 >>> 12; v2 = v2 + m14 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 16) | v14 >>> 16; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 12) | v6 >>> 12; v3 = v3 + m4 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 16) | v15 >>> 16; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 12) | v7 >>> 12; v2 = v2 + m13 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 8) | v14 >>> 8; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 7) | v6 >>> 7; v3 = v3 + m10 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 8) | v15 >>> 8; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 7) | v7 >>> 7; v1 = v1 + m15 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 8) | v13 >>> 8; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 7) | v5 >>> 7; v0 = v0 + m5 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 8) | v12 >>> 8; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 7) | v4 >>> 7; v0 = v0 + m0 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 16) | v15 >>> 16; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 12) | v5 >>> 12; v1 = v1 + m6 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 16) | v12 >>> 16; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 12) | v6 >>> 12; v2 = v2 + m9 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 16) | v13 >>> 16; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 12) | v7 >>> 12; v3 = v3 + m8 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 16) | v14 >>> 16; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 12) | v4 >>> 12; v2 = v2 + m2 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 8) | v13 >>> 8; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 7) | v7 >>> 7; v3 = v3 + m11 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 8) | v14 >>> 8; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 7) | v4 >>> 7; v1 = v1 + m3 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 8) | v12 >>> 8; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 7) | v6 >>> 7; v0 = v0 + m7 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 8) | v15 >>> 8; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 7) | v5 >>> 7; // Round 8. v0 = v0 + m13 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 16) | v12 >>> 16; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 12) | v4 >>> 12; v1 = v1 + m7 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 16) | v13 >>> 16; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 12) | v5 >>> 12; v2 = v2 + m12 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 16) | v14 >>> 16; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 12) | v6 >>> 12; v3 = v3 + m3 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 16) | v15 >>> 16; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 12) | v7 >>> 12; v2 = v2 + m1 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 8) | v14 >>> 8; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 7) | v6 >>> 7; v3 = v3 + m9 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 8) | v15 >>> 8; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 7) | v7 >>> 7; v1 = v1 + m14 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 8) | v13 >>> 8; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 7) | v5 >>> 7; v0 = v0 + m11 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 8) | v12 >>> 8; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 7) | v4 >>> 7; v0 = v0 + m5 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 16) | v15 >>> 16; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 12) | v5 >>> 12; v1 = v1 + m15 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 16) | v12 >>> 16; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 12) | v6 >>> 12; v2 = v2 + m8 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 16) | v13 >>> 16; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 12) | v7 >>> 12; v3 = v3 + m2 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 16) | v14 >>> 16; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 12) | v4 >>> 12; v2 = v2 + m6 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 8) | v13 >>> 8; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 7) | v7 >>> 7; v3 = v3 + m10 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 8) | v14 >>> 8; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 7) | v4 >>> 7; v1 = v1 + m4 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 8) | v12 >>> 8; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 7) | v6 >>> 7; v0 = v0 + m0 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 8) | v15 >>> 8; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 7) | v5 >>> 7; // Round 9. v0 = v0 + m6 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 16) | v12 >>> 16; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 12) | v4 >>> 12; v1 = v1 + m14 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 16) | v13 >>> 16; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 12) | v5 >>> 12; v2 = v2 + m11 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 16) | v14 >>> 16; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 12) | v6 >>> 12; v3 = v3 + m0 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 16) | v15 >>> 16; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 12) | v7 >>> 12; v2 = v2 + m3 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 8) | v14 >>> 8; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 7) | v6 >>> 7; v3 = v3 + m8 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 8) | v15 >>> 8; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 7) | v7 >>> 7; v1 = v1 + m9 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 8) | v13 >>> 8; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 7) | v5 >>> 7; v0 = v0 + m15 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 8) | v12 >>> 8; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 7) | v4 >>> 7; v0 = v0 + m12 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 16) | v15 >>> 16; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 12) | v5 >>> 12; v1 = v1 + m13 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 16) | v12 >>> 16; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 12) | v6 >>> 12; v2 = v2 + m1 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 16) | v13 >>> 16; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 12) | v7 >>> 12; v3 = v3 + m10 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 16) | v14 >>> 16; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 12) | v4 >>> 12; v2 = v2 + m4 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 8) | v13 >>> 8; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 7) | v7 >>> 7; v3 = v3 + m5 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 8) | v14 >>> 8; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 7) | v4 >>> 7; v1 = v1 + m7 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 8) | v12 >>> 8; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 7) | v6 >>> 7; v0 = v0 + m2 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 8) | v15 >>> 8; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 7) | v5 >>> 7; // Round 10. v0 = v0 + m10 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 16) | v12 >>> 16; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 12) | v4 >>> 12; v1 = v1 + m8 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 16) | v13 >>> 16; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 12) | v5 >>> 12; v2 = v2 + m7 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 16) | v14 >>> 16; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 12) | v6 >>> 12; v3 = v3 + m1 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 16) | v15 >>> 16; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 12) | v7 >>> 12; v2 = v2 + m6 | 0; v2 = v2 + v6 | 0; v14 ^= v2; v14 = v14 << (32 - 8) | v14 >>> 8; v10 = v10 + v14 | 0; v6 ^= v10; v6 = v6 << (32 - 7) | v6 >>> 7; v3 = v3 + m5 | 0; v3 = v3 + v7 | 0; v15 ^= v3; v15 = v15 << (32 - 8) | v15 >>> 8; v11 = v11 + v15 | 0; v7 ^= v11; v7 = v7 << (32 - 7) | v7 >>> 7; v1 = v1 + m4 | 0; v1 = v1 + v5 | 0; v13 ^= v1; v13 = v13 << (32 - 8) | v13 >>> 8; v9 = v9 + v13 | 0; v5 ^= v9; v5 = v5 << (32 - 7) | v5 >>> 7; v0 = v0 + m2 | 0; v0 = v0 + v4 | 0; v12 ^= v0; v12 = v12 << (32 - 8) | v12 >>> 8; v8 = v8 + v12 | 0; v4 ^= v8; v4 = v4 << (32 - 7) | v4 >>> 7; v0 = v0 + m15 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 16) | v15 >>> 16; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 12) | v5 >>> 12; v1 = v1 + m9 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 16) | v12 >>> 16; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 12) | v6 >>> 12; v2 = v2 + m3 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 16) | v13 >>> 16; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 12) | v7 >>> 12; v3 = v3 + m13 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 16) | v14 >>> 16; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 12) | v4 >>> 12; v2 = v2 + m12 | 0; v2 = v2 + v7 | 0; v13 ^= v2; v13 = v13 << (32 - 8) | v13 >>> 8; v8 = v8 + v13 | 0; v7 ^= v8; v7 = v7 << (32 - 7) | v7 >>> 7; v3 = v3 + m0 | 0; v3 = v3 + v4 | 0; v14 ^= v3; v14 = v14 << (32 - 8) | v14 >>> 8; v9 = v9 + v14 | 0; v4 ^= v9; v4 = v4 << (32 - 7) | v4 >>> 7; v1 = v1 + m14 | 0; v1 = v1 + v6 | 0; v12 ^= v1; v12 = v12 << (32 - 8) | v12 >>> 8; v11 = v11 + v12 | 0; v6 ^= v11; v6 = v6 << (32 - 7) | v6 >>> 7; v0 = v0 + m11 | 0; v0 = v0 + v5 | 0; v15 ^= v0; v15 = v15 << (32 - 8) | v15 >>> 8; v10 = v10 + v15 | 0; v5 ^= v10; v5 = v5 << (32 - 7) | v5 >>> 7; this._state[0] ^= v0 ^ v8; this._state[1] ^= v1 ^ v9; this._state[2] ^= v2 ^ v10; this._state[3] ^= v3 ^ v11; this._state[4] ^= v4 ^ v12; this._state[5] ^= v5 ^ v13; this._state[6] ^= v6 ^ v14; this._state[7] ^= v7 ^ v15; } } export type SavedState = { state: Uint32Array; buffer: Uint8Array; bufferLength: number; ctr0: number; ctr1: number; flag0: number; flag1: number; lastNode: boolean; paddedKey: Uint8Array | undefined; initialState: Uint32Array; }; export function hash(data: Uint8Array, digestLength = DIGEST_LENGTH, config?: Config): Uint8Array { const h = new BLAKE2s(digestLength, config); h.update(data); const digest = h.digest(); h.clean(); return digest; }
the_stack
import React from 'react' import PropTypes from 'prop-types' function uniq (arr) { let out = [] for (let i = 0; i < arr.length; i++) { if (out.indexOf(arr[i]) === -1) { out.push(arr[i]) } } return out } /* istanbul ignore next */ function getClipboardData (e) { if (window.clipboardData) { return window.clipboardData.getData('Text') } if (e.clipboardData) { return e.clipboardData.getData('text/plain') } return '' } function defaultRenderTag (props) { let {tag, key, disabled, onRemove, classNameRemove, getTagDisplayValue, ...other} = props return ( <span key={key} {...other}> {getTagDisplayValue(tag)} {!disabled && <a className={classNameRemove} onClick={(e) => onRemove(key)} /> } </span> ) } defaultRenderTag.propTypes = { key: PropTypes.number, tag: PropTypes.string, onRemove: PropTypes.func, classNameRemove: PropTypes.string, getTagDisplayValue: PropTypes.func } function defaultRenderInput ({addTag, ...props}) { let {onChange, value, ...other} = props return ( <input type='text' onChange={onChange} value={value} {...other} /> ) } defaultRenderInput.propTypes = { value: PropTypes.string, onChange: PropTypes.func, addTag: PropTypes.func } function defaultRenderLayout (tagComponents, inputComponent) { return ( <span> {tagComponents} {inputComponent} </span> ) } function defaultPasteSplit (data) { return data.split(' ').map(d => d.trim()) } const defaultInputProps = { className: 'react-tagsinput-input', placeholder: 'Add a tag' } class TagsInput extends React.Component { /* istanbul ignore next */ constructor () { super() this.state = {tag: '', isFocused: false} this.focus = ::this.focus this.blur = ::this.blur } static propTypes = { focusedClassName: PropTypes.string, addKeys: PropTypes.arrayOf(PropTypes.oneOfType([ PropTypes.number, PropTypes.string ])), addOnBlur: PropTypes.bool, addOnPaste: PropTypes.bool, currentValue: PropTypes.string, inputValue: PropTypes.string, inputProps: PropTypes.object, onChange: PropTypes.func.isRequired, onChangeInput: PropTypes.func, removeKeys: PropTypes.arrayOf(PropTypes.oneOfType([ PropTypes.number, PropTypes.string ])), renderInput: PropTypes.func, renderTag: PropTypes.func, renderLayout: PropTypes.func, pasteSplit: PropTypes.func, tagProps: PropTypes.object, onlyUnique: PropTypes.bool, value: PropTypes.array.isRequired, maxTags: PropTypes.number, validate: PropTypes.func, validationRegex: PropTypes.instanceOf(RegExp), disabled: PropTypes.bool, tagDisplayProp: PropTypes.string, preventSubmit: PropTypes.bool } static defaultProps = { className: 'react-tagsinput', focusedClassName: 'react-tagsinput--focused', addKeys: [9, 13], addOnBlur: false, addOnPaste: false, inputProps: {}, removeKeys: [8], renderInput: defaultRenderInput, renderTag: defaultRenderTag, renderLayout: defaultRenderLayout, pasteSplit: defaultPasteSplit, tagProps: {className: 'react-tagsinput-tag', classNameRemove: 'react-tagsinput-remove'}, onlyUnique: false, maxTags: -1, validate: () => true, validationRegex: /.*/, disabled: false, tagDisplayProp: null, preventSubmit: true } _getTagDisplayValue (tag) { const {tagDisplayProp} = this.props if (tagDisplayProp) { return tag[tagDisplayProp] } return tag } _makeTag (tag) { const {tagDisplayProp} = this.props if (tagDisplayProp) { return { [tagDisplayProp]: tag } } return tag } _removeTag (index) { let value = this.props.value.concat([]) if (index > -1 && index < value.length) { let changed = value.splice(index, 1) this.props.onChange(value, changed, [index]) } } _clearInput () { if (this.hasControlledInput()) { this.props.onChangeInput('') } else { this.setState({tag: ''}) } } _tag () { if (this.hasControlledInput()) { return this.props.inputValue } return this.state.tag } _addTags (tags) { let {onChange, onValidationReject, onlyUnique, maxTags, value} = this.props if (onlyUnique) { tags = uniq(tags) tags = tags.filter(tag => value.every(currentTag => this._getTagDisplayValue(currentTag) !== this._getTagDisplayValue(tag)) ) } const rejectedTags = tags.filter(tag => !this._validate(this._getTagDisplayValue(tag))) tags = tags.filter(tag => this._validate(this._getTagDisplayValue(tag))) tags = tags.filter(tag => { let tagDisplayValue = this._getTagDisplayValue(tag) if (typeof tagDisplayValue.trim === 'function') { return tagDisplayValue.trim().length > 0 } else { return tagDisplayValue } }) if (maxTags >= 0) { let remainingLimit = Math.max(maxTags - value.length, 0) tags = tags.slice(0, remainingLimit) } if (onValidationReject && rejectedTags.length > 0) { onValidationReject(rejectedTags) } if (tags.length > 0) { let newValue = value.concat(tags) let indexes = [] for (let i = 0; i < tags.length; i++) { indexes.push(value.length + i) } onChange(newValue, tags, indexes) this._clearInput() return true } if (rejectedTags.length > 0) { return false } this._clearInput() return false } _validate (tag) { let {validate, validationRegex} = this.props return validate(tag) && validationRegex.test(tag) } _shouldPreventDefaultEventOnAdd (added, empty, keyCode) { if (added) { return true } if (keyCode === 13) { return (this.props.preventSubmit || !this.props.preventSubmit && !empty) } return false } focus () { if (this.input && typeof this.input.focus === 'function') { this.input.focus() } this.handleOnFocus() } blur () { if (this.input && typeof this.input.blur === 'function') { this.input.blur() } this.handleOnBlur() } accept () { let tag = this._tag() if (tag !== '') { tag = this._makeTag(tag) return this._addTags([tag]) } return false } addTag (tag) { return this._addTags([tag]) } clearInput () { this._clearInput() } handlePaste (e) { let {addOnPaste, pasteSplit} = this.props if (!addOnPaste) { return } e.preventDefault() let data = getClipboardData(e) let tags = pasteSplit(data).map(tag => this._makeTag(tag)) this._addTags(tags) } handleKeyDown (e) { if (e.defaultPrevented) { return } let {value, removeKeys, addKeys} = this.props const tag = this._tag() let empty = tag === '' let keyCode = e.keyCode let key = e.key let add = addKeys.indexOf(keyCode) !== -1 || addKeys.indexOf(key) !== -1 let remove = removeKeys.indexOf(keyCode) !== -1 || removeKeys.indexOf(key) !== -1 if (add) { let added = this.accept() if (this._shouldPreventDefaultEventOnAdd(added, empty, keyCode)) { e.preventDefault() } } if (remove && value.length > 0 && empty) { e.preventDefault() this._removeTag(value.length - 1) } } handleClick (e) { if (e.target === this.div) { this.focus() } } handleChange (e) { let {onChangeInput} = this.props let {onChange} = this.props.inputProps let tag = e.target.value if (onChange) { onChange(e) } if (this.hasControlledInput()) { onChangeInput(tag) } else { this.setState({tag}) } } handleOnFocus (e) { let {onFocus} = this.props.inputProps if (onFocus) { onFocus(e) } this.setState({isFocused: true}) } handleOnBlur (e) { let {onBlur} = this.props.inputProps this.setState({isFocused: false}) if (e == null) { return } if (onBlur) { onBlur(e) } if (this.props.addOnBlur) { const tag = this._makeTag(e.target.value) this._addTags([tag]) } } handleRemove (tag) { this._removeTag(tag) } inputProps () { // eslint-disable-next-line let {onChange, onFocus, onBlur, ...otherInputProps} = this.props.inputProps let props = { ...defaultInputProps, ...otherInputProps } if (this.props.disabled) { props.disabled = true } return props } inputValue (props) { return props.currentValue || props.inputValue || '' } hasControlledInput () { const {inputValue, onChangeInput} = this.props return typeof onChangeInput === 'function' && typeof inputValue === 'string' } componentDidMount () { if (this.hasControlledInput()) { return } this.setState({ tag: this.inputValue(this.props) }) } componentWillReceiveProps (nextProps) { /* istanbul ignore next */ if (this.hasControlledInput()) { return } if (!this.inputValue(nextProps)) { return } this.setState({ tag: this.inputValue(nextProps) }) } render () { /* eslint-disable */ let { value, onChange, tagProps, renderLayout, renderTag, renderInput, addKeys, removeKeys, className, focusedClassName, addOnBlur, addOnPaste, inputProps, pasteSplit, onlyUnique, maxTags, validate, validationRegex, disabled, tagDisplayProp, inputValue, onChangeInput, ...other } = this.props /* eslint-enable */ let {isFocused} = this.state if (isFocused) { className += ' ' + focusedClassName } let tagComponents = value.map((tag, index) => { return renderTag({ key: index, tag, onRemove: ::this.handleRemove, disabled, getTagDisplayValue: ::this._getTagDisplayValue, ...tagProps }) }) let inputComponent = renderInput({ ref: r => { this.input = r }, value: this._tag(), onPaste: ::this.handlePaste, onKeyDown: ::this.handleKeyDown, onChange: ::this.handleChange, onFocus: ::this.handleOnFocus, onBlur: ::this.handleOnBlur, addTag: ::this.addTag, ...this.inputProps() }) return ( <div ref={r => { this.div = r }} onClick={::this.handleClick} className={className}> {renderLayout(tagComponents, inputComponent)} </div> ) } } export default TagsInput
the_stack
import { expect } from 'chai'; import { last } from 'rxjs/operators/last'; import { take } from 'rxjs/operators/take'; import { App } from './App'; import createApp from './createApp'; describe('frint › App', () => { it('throws error when creating new instance without name', () => { expect(() => { // tslint:disable-next-line:no-unused-expression new App({ name: undefined }); }).to.throw(/Must provide `name` in options/); }); it('gets name option value', () => { const app = new App({ name: 'MyApp', }); expect(app.getName()).to.equal('MyApp'); }); it('exposes methods as class properties', () => { const methods = { foo() { return 'foo'; }, }; const app = new App({ name: 'MyApp', methods, }); expect(app.foo()).to.equal('foo'); }); it('does not overwrite app properties or methods with options methods', () => { const methods = { // tslint:disable-next-line:no-empty getName() {}, }; expect(() => ( new App({ name: 'MyApp', methods, }) )).to.throw(/Cannot overwrite app's `getName` property or method with options method/); }); it('gets parent and root app', () => { const rootApp = new App({ name: 'RootApp', }); const childApp = new App({ name: 'ChildApp', parentApp: rootApp, }); const grandchildApp = new App({ name: 'GrandchildApp', parentApp: childApp, }); expect(rootApp.getName()).to.equal('RootApp'); expect(childApp.getName()).to.equal('ChildApp'); expect(rootApp.getParentApps()).to.deep.equal([]); expect(childApp.getParentApp()).to.deep.equal(rootApp); expect(childApp.getRootApp()).to.deep.equal(rootApp); expect( childApp .getParentApps() .map(x => x.getOption('name')) ).to.deep.equal([ 'RootApp' ]); expect(grandchildApp.getParentApp()).to.deep.equal(childApp); expect(grandchildApp.getRootApp()).to.deep.equal(rootApp); expect( grandchildApp .getParentApps() .map(x => x.getOption('name')) ).to.deep.equal([ 'ChildApp', 'RootApp', ]); }); it('registers providers with direct values', () => { const app = new App({ name: 'MyApp', providers: [ { name: 'foo', useValue: 'fooValue' }, ], }); expect(app.get('foo')).to.equal('fooValue'); }); it('registers providers with factory values', () => { const app = new App({ name: 'MyApp', providers: [ { name: 'foo', useFactory: () => 'fooValue' }, ], }); expect(app.get('foo')).to.equal('fooValue'); }); it('registers providers with class values', () => { class Foo { public getValue() { return 'fooValue'; } } const app = new App({ name: 'MyApp', providers: [ { name: 'foo', useClass: Foo }, ], }); expect(app.get<Foo>('foo').getValue()).to.equal('fooValue'); }); it('registers providers with dependencies', () => { class Baz { private foo; private bar; constructor({ foo, bar }) { this.foo = foo; this.bar = bar; } public getValue() { return `bazValue, ${this.foo}, ${this.bar}`; } } const app = new App({ name: 'MyApp', providers: [ { name: 'foo', useValue: 'fooValue' }, { name: 'bar', useFactory: ({ foo }) => { return `barValue, ${foo}`; }, deps: ['foo'], }, { name: 'baz', useClass: Baz, deps: ['foo', 'bar'], } ], }); expect(app.get('foo')).to.equal('fooValue'); expect(app.get('bar')).to.equal('barValue, fooValue'); expect(app.get<Baz>('baz').getValue()).to.equal('bazValue, fooValue, barValue, fooValue'); }); it('returns services from Root that are cascaded', () => { class ServiceC { public getValue() { return 'serviceC'; } } const Root = createApp({ name: 'MyApp', providers: [ { name: 'serviceA', useValue: 'serviceA', scoped: true, cascade: true, }, { name: 'serviceB', useFactory: () => 'serviceB', scoped: true, cascade: true, }, { name: 'serviceC', useClass: ServiceC, cascade: true, }, { name: 'serviceCScoped', useClass: ServiceC, cascade: true, scoped: true, }, { name: 'serviceD', useValue: 'serviceD', cascade: false, }, { name: 'serviceE', useValue: 'serviceE', cascade: true, scoped: false, } ], }); const App1 = createApp({ name: 'App1' }); const root = new Root(); root.registerApp(App1); const app = root.getAppInstance('App1'); // expect(app.get('serviceA')).to.equal('serviceA'); expect(app.get('serviceB')).to.equal('serviceB'); expect(app.get<ServiceC>('serviceC').getValue()).to.equal('serviceC'); expect(app.get('serviceD')).to.equal(null); expect(app.get('serviceE')).to.equal('serviceE'); expect(app.get('serviceF')).to.equal(null); expect(root.get('serviceF')).to.equal(null); }); it('returns null when service is non-existent in both Child App and Root', () => { const Root = createApp({ name: 'MyApp' }); const App1 = createApp({ name: 'App1' }); const app = new Root(); app.registerApp(App1); const serviceA = app .getAppInstance('App1') .get('serviceA'); expect(serviceA).to.equal(null); }); it('gets container', () => { const app = new App({ name: 'MyApp' }); expect(app.getContainer()).to.deep.equal(app.container); }); it('gets providers definition list', () => { const app = new App({ name: 'MyApp', providers: [ { name: 'foo', useValue: 'fooValue' }, ], }); expect(app.getProviders()).to.deep.equal([ { name: 'foo', useValue: 'fooValue' }, ]); }); it('gets individual provider definition', () => { const app = new App({ name: 'MyApp', providers: [ { name: 'foo', useValue: 'fooValue' }, ], }); expect(app.getProvider('foo')).to.deep.equal({ name: 'foo', useValue: 'fooValue' }); }); it('calls initialize during construction, as passed in options', () => { let called = false; const app = new App({ name: 'MyApp', initialize() { called = true; } }); expect(app.getName()).to.equal('MyApp'); expect(called).to.equal(true); }); it('calls beforeDestroy, as passed in options', () => { let called = false; const app = new App({ name: 'MyApp', beforeDestroy() { called = true; } }); app.beforeDestroy(); expect(app.getName()).to.equal('MyApp'); expect(called).to.equal(true); }); it('registers apps', () => { const Root = createApp({ name: 'MyApp' }); const App1 = createApp({ name: 'App1' }); const app = new Root(); app.registerApp(App1, { regions: ['sidebar'], }); expect(app.hasAppInstance('App1')).to.equal(true); expect(app.getAppInstance('App1').getOption('name')).to.equal('App1'); }); it('registers apps, by overriding options', () => { const Root = createApp({ name: 'MyApp' }); const App1 = createApp({ name: 'App1' }); const app = new Root(); app.registerApp(App1, { name: 'AppOne', regions: ['sidebar'], }); expect(app.hasAppInstance('AppOne')).to.equal(true); expect(app.getAppInstance('AppOne').getOption('name')).to.equal('AppOne'); }); it('registers apps', () => { const Root = createApp({ name: 'MyApp' }); const App1 = createApp({ name: 'App1' }); const app = new Root(); app.registerApp(App1, { regions: ['sidebar'], }); expect(app.hasAppInstance('App1')).to.equal(true); expect(app.getAppInstance('App1').getOption('name')).to.equal('App1'); }); it('streams registered apps as a collection', done => { const Root = createApp({ name: 'MyApp' }); const App1 = createApp({ name: 'App1' }); const app = new Root(); app.registerApp(App1, { regions: ['sidebar'], }); const apps$ = app.getApps$(); apps$.subscribe(apps => { expect(Array.isArray(apps)).to.equal(true); expect(apps.length).to.equal(1); expect(apps[0].name).to.equal('App1'); done(); }); }); it('streams registered apps as a collection, with region filtering', done => { const Root = createApp({ name: 'MyApp' }); const App1 = createApp({ name: 'App1' }); const app = new Root(); app.registerApp(App1, { regions: ['sidebar'], }); const apps$ = app.getApps$('sidebar'); apps$.subscribe(apps => { expect(Array.isArray(apps)).to.equal(true); expect(apps.length).to.equal(1); expect(apps[0].name).to.equal('App1'); done(); }); }); it('gets app once available (that will be available in future)', done => { const Root = createApp({ name: 'MyApp' }); const App1 = createApp({ name: 'App1' }); const root = new Root(); root.getAppOnceAvailable$('App1') .subscribe(app => { expect(app.getName()).to.equal('App1'); done(); }); root.registerApp(App1); }); it('gets app once available (that is already available)', done => { const Root = createApp({ name: 'MyApp' }); const App1 = createApp({ name: 'App1' }); const root = new Root(); root.registerApp(App1); root.getAppOnceAvailable$('App1') .subscribe(app => { expect(app.getName()).to.equal('App1'); done(); }); }); it('gets app scoped by region', () => { const Root = createApp({ name: 'MyApp' }); const App1 = createApp({ name: 'App1' }); const App2 = createApp({ name: 'App2' }); const app = new Root(); app.registerApp(App1, { regions: ['sidebar'], }); app.registerApp(App2, { regions: ['footer'], multi: true, }); expect(app.getAppInstance('App1')).to.be.an('object'); expect(app.getAppInstance('App1', 'sidebar')).to.be.an('object'); expect(app.getAppInstance('App2')).to.equal(null); expect(app.getAppInstance('App2', 'footer')).to.equal(null); app.instantiateApp('App2', 'footer', 'footer-123'); expect(app.getAppInstance('App2', 'footer', 'footer-123')).to.be.an('object'); }); it('throws error when registering same App twice', () => { const Root = createApp({ name: 'MyApp' }); const App1 = createApp({ name: 'App1' }); const app = new Root(); app.registerApp(App1); expect(() => { app.registerApp(App1); }).to.throw(/App 'App1' has been already registered before/); }); it('checks for app instance availability', () => { const Root = createApp({ name: 'MyApp' }); const App1 = createApp({ name: 'App1' }); const app = new Root(); expect(app.hasAppInstance('blah')).to.equal(false); app.registerApp(App1); expect(app.hasAppInstance('App1')).to.equal(true); }); it('throws error when trying to instantiate non-existent App', () => { const Root = createApp({ name: 'MyApp' }); const app = new Root(); expect(() => { app.instantiateApp('blah'); }).to.throw(/No app found with name 'blah'/); }); it('throws error when trying to destroy non-existent App', () => { const Root = createApp({ name: 'MyApp' }); const app = new Root(); expect(() => { app.destroyApp('blah'); }).to.throw(/No app found with name 'blah'/); }); it('throws error when trying to destroy existing App without instances', () => { const Root = createApp({ name: 'MyApp' }); const App1 = createApp({ name: 'App1' }); const app = new Root(); app.registerApp(App1); app.destroyApp('App1'); expect(() => { app.destroyApp('App1'); }).to.throw(/No instance with key 'default' found for app with name 'App1'./); }); it('app instance is removed when destroyApp is called', () => { const Root = createApp({ name: 'MyApp' }); const App1 = createApp({ name: 'App1' }); const app = new Root(); app.registerApp(App1); expect(app.getAppInstance('App1')).to.not.be.null; expect(app.hasAppInstance('App1')).to.be.true; app.destroyApp('App1'); expect(app.getAppInstance('App1')).to.be.null; expect(app.hasAppInstance('App1')).to.be.false; }); it('can accept additional lifecycle callbacks for Root Apps while instantiating, without overriding', () => { let counter = 0; const Root = createApp({ name: 'RootApp', initialize() { counter += 1; }, }); // tslint:disable-next-line:no-unused-expression new Root({ initialize() { counter += 1; }, }); expect(counter).to.equal(2); }); it('can accept additional lifecycle callbacks for Child Apps while registering, without overriding', () => { let counter = 0; const Root = createApp({ name: 'RootApp', }); const ChildApp = createApp({ name: 'ChildApp', initialize() { counter += 1; }, }); const app = new Root(); app.registerApp(ChildApp, { initialize() { counter += 1; }, }); expect(counter).to.equal(2); }); it('can update providers at lifecycle level', () => { const Root = createApp({ name: 'RootApp', providers: [ { name: 'foo', useValue: 'original foo', }, ], initialize() { const foo = this.get('foo'); this.container.register({ name: 'foo', useValue: `${foo} [updated]`, }); } }); const app = new Root(); expect(app.get('foo')).to.equal('original foo [updated]'); }); it('can access and update providers from lifecycle callback defined while instantiating', () => { const Root = createApp({ name: 'RootApp', providers: [ { name: 'foo', useValue: 'original foo', }, ], initialize() { const foo = this.get('foo'); this.container.register({ name: 'foo', useValue: `${foo} [updatedFromCreateApp]`, }); } }); const app = new Root({ initialize() { const foo = this.get('foo'); this.container.register({ name: 'foo', useValue: `${foo} [updatedFromInstantiation]`, }); } }); expect(app.get('foo')).to.equal('original foo [updatedFromCreateApp] [updatedFromInstantiation]'); }); it('can listen for child apps registration from a provider', done => { const Root = createApp({ name: 'RootApp', providers: [ { name: '__EXEC__', useFactory({ app }) { app.getApps$().pipe( take(2), last() ).subscribe(appsList => { expect(appsList.length).to.equal(1); expect(appsList[0].name).to.equal('ChildApp'); done(); }); }, deps: ['app'], }, ], }); const Child = createApp({ name: 'ChildApp', }); const testApp = new Root(); testApp.registerApp(Child); }); });
the_stack
import "jest-extended"; import { Application, Contracts } from "@packages/core-kernel"; import { DelegateEvent } from "@packages/core-kernel/src/enums"; import { Identifiers } from "@packages/core-kernel/src/ioc"; import { Wallets } from "@packages/core-state"; import { StateStore } from "@packages/core-state/src/stores/state"; import { Generators } from "@packages/core-test-framework/src"; import { Factories, FactoryBuilder } from "@packages/core-test-framework/src/factories"; import passphrases from "@packages/core-test-framework/src/internal/passphrases.json"; import { Mempool } from "@packages/core-transaction-pool/src/mempool"; import { InsufficientBalanceError, NotEnoughDelegatesError, VotedForResignedDelegateError, WalletAlreadyResignedError, WalletNotADelegateError, } from "@packages/core-transactions/src/errors"; import { TransactionHandler } from "@packages/core-transactions/src/handlers"; import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; import { Crypto, Enums, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; import { configManager } from "@packages/crypto/src/managers"; import { BuilderFactory } from "@packages/crypto/src/transactions"; import { buildMultiSignatureWallet, buildRecipientWallet, buildSecondSignatureWallet, buildSenderWallet, initApp, } from "../__support__/app"; let app: Application; let senderWallet: Wallets.Wallet; let secondSignatureWallet: Wallets.Wallet; let multiSignatureWallet: Wallets.Wallet; let recipientWallet: Wallets.Wallet; let walletRepository: Contracts.State.WalletRepository; let factoryBuilder: FactoryBuilder; const mockLastBlockData: Partial<Interfaces.IBlockData> = { timestamp: Crypto.Slots.getTime(), height: 4 }; const mockGetLastBlock = jest.fn(); StateStore.prototype.getLastBlock = mockGetLastBlock; mockGetLastBlock.mockReturnValue({ data: mockLastBlockData }); const transactionHistoryService = { streamByCriteria: jest.fn(), }; beforeEach(() => { transactionHistoryService.streamByCriteria.mockReset(); const config = Generators.generateCryptoConfigRaw(); configManager.setConfig(config); Managers.configManager.setConfig(config); app = initApp(); app.bind(Identifiers.TransactionHistoryService).toConstantValue(transactionHistoryService); walletRepository = app.get<Wallets.WalletRepository>(Identifiers.WalletRepository); factoryBuilder = new FactoryBuilder(); Factories.registerWalletFactory(factoryBuilder); Factories.registerTransactionFactory(factoryBuilder); senderWallet = buildSenderWallet(factoryBuilder); secondSignatureWallet = buildSecondSignatureWallet(factoryBuilder); multiSignatureWallet = buildMultiSignatureWallet(); recipientWallet = buildRecipientWallet(factoryBuilder); walletRepository.index(senderWallet); walletRepository.index(secondSignatureWallet); walletRepository.index(multiSignatureWallet); walletRepository.index(recipientWallet); }); describe("DelegateResignationTransaction", () => { let allDelegates: Wallets.Wallet[]; let delegateWallet: Wallets.Wallet; const delegatePassphrase = "my secret passphrase"; let delegateResignationTransaction: Interfaces.ITransaction; let secondSignatureDelegateResignationTransaction: Interfaces.ITransaction; let handler: TransactionHandler; let voteHandler: TransactionHandler; beforeEach(async () => { const transactionHandlerRegistry: TransactionHandlerRegistry = app.get<TransactionHandlerRegistry>( Identifiers.TransactionHandlerRegistry, ); handler = transactionHandlerRegistry.getRegisteredHandlerByType( Transactions.InternalTransactionType.from( Enums.TransactionType.DelegateResignation, Enums.TransactionTypeGroup.Core, ), 2, ); voteHandler = transactionHandlerRegistry.getRegisteredHandlerByType( Transactions.InternalTransactionType.from(Enums.TransactionType.Vote, Enums.TransactionTypeGroup.Core), 2, ); allDelegates = []; for (let i = 0; i < passphrases.length; i++) { const delegateWallet: Wallets.Wallet = factoryBuilder .get("Wallet") .withOptions({ passphrase: passphrases[i], nonce: 0, }) .make(); delegateWallet.setAttribute("delegate", { username: "username" + i }); walletRepository.index(delegateWallet); allDelegates.push(delegateWallet); } delegateWallet = factoryBuilder .get("Wallet") .withOptions({ passphrase: delegatePassphrase, nonce: 0, }) .make(); delegateWallet.setBalance(Utils.BigNumber.make(66 * 1e8)); delegateWallet.setAttribute("delegate", { username: "dummy" }); walletRepository.index(delegateWallet); delegateResignationTransaction = BuilderFactory.delegateResignation() .nonce("1") .sign(delegatePassphrase) .build(); secondSignatureDelegateResignationTransaction = BuilderFactory.delegateResignation() .nonce("1") .sign(passphrases[1]) .secondSign(passphrases[2]) .build(); }); describe("bootstrap", () => { // TODO: assert wallet repository it("should resolve", async () => { transactionHistoryService.streamByCriteria.mockImplementationOnce(async function* () { yield delegateResignationTransaction.data; }); await expect(handler.bootstrap()).toResolve(); expect(transactionHistoryService.streamByCriteria).toBeCalledWith({ typeGroup: Enums.TransactionTypeGroup.Core, type: Enums.TransactionType.DelegateResignation, }); }); it("should resolve - simulate genesis wallet", async () => { transactionHistoryService.streamByCriteria.mockImplementationOnce(async function* () { yield delegateResignationTransaction.data; }); allDelegates[0].forgetAttribute("delegate"); walletRepository.index(allDelegates[0]); await expect(handler.bootstrap()).toResolve(); }); }); describe("emitEvents", () => { it("should dispatch", async () => { const emitter: Contracts.Kernel.EventDispatcher = app.get<Contracts.Kernel.EventDispatcher>( Identifiers.EventDispatcherService, ); const spy = jest.spyOn(emitter, "dispatch"); handler.emitEvents(delegateResignationTransaction, emitter); expect(spy).toHaveBeenCalledWith(DelegateEvent.Resigned, expect.anything()); }); }); describe("throwIfCannotBeApplied", () => { it("should not throw if wallet is a delegate", async () => { await expect(handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet)).toResolve(); }); it("should not throw if wallet is a delegate - second sign", async () => { // Add extra delegate so we don't get NotEnoughDelegatesError const anotherDelegate: Wallets.Wallet = factoryBuilder .get("Wallet") .withOptions({ passphrase: "anotherDelegate", nonce: 0, }) .make(); anotherDelegate.setAttribute("delegate", { username: "another" }); walletRepository.index(anotherDelegate); allDelegates.push(anotherDelegate); secondSignatureWallet.setAttribute("delegate", { username: "dummy" }); walletRepository.index(secondSignatureWallet); await expect( handler.throwIfCannotBeApplied(secondSignatureDelegateResignationTransaction, secondSignatureWallet), ).toResolve(); }); it("should not throw if wallet is a delegate due too many delegates", async () => { const anotherDelegate: Wallets.Wallet = factoryBuilder .get("Wallet") .withOptions({ passphrase: "anotherDelegate", nonce: 0, }) .make(); anotherDelegate.setAttribute("delegate", { username: "another" }); walletRepository.index(anotherDelegate); await expect(handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet)).toResolve(); }); it("should throw if wallet is not a delegate", async () => { delegateWallet.forgetAttribute("delegate"); await expect( handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet), ).rejects.toThrow(WalletNotADelegateError); }); it("should throw if wallet has insufficient funds", async () => { delegateWallet.setBalance(Utils.BigNumber.ZERO); await expect( handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet), ).rejects.toThrow(InsufficientBalanceError); }); it("should throw if not enough delegates", async () => { await expect(handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet)).toResolve(); allDelegates[0].setAttribute("delegate.resigned", true); await expect( handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet), ).rejects.toThrow(NotEnoughDelegatesError); }); it("should throw if not enough delegates due to already resigned delegates", async () => { await expect(handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet)).toResolve(); delegateWallet.setAttribute("delegate.resigned", true); await expect( handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet), ).rejects.toThrow(WalletAlreadyResignedError); }); // it("should throw if not enough delegates registered", async () => { // let anotherDelegateWallet: Wallets.Wallet = factoryBuilder // .get("Wallet") // .withOptions({ // passphrase: "another delegate passphrase", // nonce: 0 // }) // .make(); // // delegateWallet.setAttribute("delegate", {username: "another"}); // // await expect(handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet)).toResolve(); // }); }); describe("throwIfCannotEnterPool", () => { it("should not throw", async () => { await expect(handler.throwIfCannotEnterPool(delegateResignationTransaction)).toResolve(); }); it("should throw if transaction by sender already in pool", async () => { await app.get<Mempool>(Identifiers.TransactionPoolMempool).addTransaction(delegateResignationTransaction); await expect(handler.throwIfCannotEnterPool(delegateResignationTransaction)).rejects.toThrow( Contracts.TransactionPool.PoolError, ); }); }); describe("apply", () => { it("should apply delegate resignation", async () => { await expect(handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet)).toResolve(); await handler.apply(delegateResignationTransaction); expect(delegateWallet.getAttribute<boolean>("delegate.resigned")).toBeTrue(); }); it("should fail when already resigned", async () => { await expect(handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet)).toResolve(); await handler.apply(delegateResignationTransaction); expect(delegateWallet.getAttribute<boolean>("delegate.resigned")).toBeTrue(); await expect( handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet), ).rejects.toThrow(WalletAlreadyResignedError); }); it("should fail when not a delegate", async () => { delegateWallet.forgetAttribute("delegate"); await expect( handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet), ).rejects.toThrow(WalletNotADelegateError); }); it("should fail when voting for a resigned delegate", async () => { await expect(handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet)).toResolve(); await handler.apply(delegateResignationTransaction); expect(delegateWallet.getAttribute<boolean>("delegate.resigned")).toBeTrue(); const voteTransaction = BuilderFactory.vote() .votesAsset(["+" + delegateWallet.getPublicKey()]) .nonce("1") .sign(passphrases[0]) .build(); await expect(voteHandler.throwIfCannotBeApplied(voteTransaction, senderWallet)).rejects.toThrow( VotedForResignedDelegateError, ); }); }); describe("revert", () => { it("should be ok", async () => { expect(delegateWallet.hasAttribute("delegate.resigned")).toBeFalse(); await expect(handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet)).toResolve(); await handler.apply(delegateResignationTransaction); expect(delegateWallet.getAttribute<boolean>("delegate.resigned")).toBeTrue(); await handler.revert(delegateResignationTransaction); expect(delegateWallet.hasAttribute("delegate.resigned")).toBeFalse(); }); }); });
the_stack
import * as moment from "moment"; /** * Defines the query context that Bing used for the request. */ export interface QueryContext { /** * The query string as specified in the request. */ originalQuery: string; /** * The query string used by Bing to perform the query. Bing uses the altered query string if the * original query string contained spelling mistakes. For example, if the query string is "saling * downwind", the altered query string will be "sailing downwind". This field is included only if * the original query string contains a spelling mistake. */ readonly alteredQuery?: string; /** * The query string to use to force Bing to use the original string. For example, if the query * string is "saling downwind", the override query string will be "+saling downwind". Remember to * encode the query string which results in "%2Bsaling+downwind". This field is included only if * the original query string contains a spelling mistake. */ readonly alterationOverrideQuery?: string; /** * A Boolean value that indicates whether the specified query has adult intent. The value is true * if the query has adult intent; otherwise, false. */ readonly adultIntent?: boolean; /** * A Boolean value that indicates whether Bing requires the user's location to provide accurate * results. If you specified the user's location by using the X-MSEdge-ClientIP and * X-Search-Location headers, you can ignore this field. For location aware queries, such as * "today's weather" or "restaurants near me" that need the user's location to provide accurate * results, this field is set to true. For location aware queries that include the location (for * example, "Seattle weather"), this field is set to false. This field is also set to false for * queries that are not location aware, such as "best sellers". */ readonly askUserForLocation?: boolean; readonly isTransactional?: boolean; } /** * Defines a webpage's metadata. */ export interface WebMetaTag { /** * The metadata. */ readonly name?: string; /** * The name of the metadata. */ readonly content?: string; } export interface ResponseBase { /** * Polymorphic Discriminator */ _type: string; } /** * Defines the identity of a resource. */ export interface Identifiable extends ResponseBase { /** * A String identifier. */ readonly id?: string; } /** * Defines a response. All schemas that could be returned at the root of a response should inherit * from this */ export interface Response extends Identifiable { /** * The URL To Bing's search result for this item. */ readonly webSearchUrl?: string; } export interface Thing extends Response { /** * The name of the thing represented by this object. */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. */ readonly url?: string; readonly image?: ImageObject; /** * A short description of the item. */ readonly description?: string; /** * An ID that uniquely identifies this item. */ readonly bingId?: string; } export interface CreativeWork extends Thing { /** * The URL to a thumbnail of the item. */ readonly thumbnailUrl?: string; /** * The source of the creative work. */ readonly provider?: Thing[]; readonly text?: string; } export interface MediaObject extends CreativeWork { /** * Original URL to retrieve the source (file) for the media object (e.g the source URL for the * image). */ readonly contentUrl?: string; /** * URL of the page that hosts the media object. */ readonly hostPageUrl?: string; /** * The width of the source media object, in pixels. */ readonly width?: number; /** * The height of the source media object, in pixels. */ readonly height?: number; } /** * Defines an image */ export interface ImageObject extends MediaObject { /** * The URL to a thumbnail of the image */ readonly thumbnail?: ImageObject; } /** * Defines a webpage that is relevant to the query. */ export interface WebPage extends CreativeWork { /** * The display URL of the webpage. The URL is meant for display purposes only and is not well * formed. */ readonly displayUrl?: string; /** * A snippet of text from the webpage that describes its contents. */ readonly snippet?: string; /** * A list of links to related content that Bing found in the website that contains this webpage. * The Webpage object in this context includes only the name, url, urlPingSuffix, and snippet * fields. */ readonly deepLinks?: WebPage[]; /** * The last time that Bing crawled the webpage. The date is in the form, YYYY-MM-DDTHH:MM:SS. For * example, 2015-04-13T05:23:39. */ readonly dateLastCrawled?: string; /** * A list of search tags that the webpage owner specified on the webpage. The API returns only * indexed search tags. The name field of the MetaTag object contains the indexed search tag. * Search tags begin with search.* (for example, search.assetId). The content field contains the * tag's value. */ readonly searchTags?: WebMetaTag[]; readonly primaryImageOfPage?: ImageObject; } export interface Answer extends Response { readonly followUpQueries?: Query[]; } export interface SearchResultsAnswer extends Answer { readonly queryContext?: QueryContext; /** * The estimated number of webpages that are relevant to the query. Use this number along with * the count and offset query parameters to page the results. */ readonly totalEstimatedMatches?: number; readonly isFamilyFriendly?: boolean; } /** * Defines a list of relevant webpage links. */ export interface WebWebAnswer extends SearchResultsAnswer { /** * A list of webpages that are relevant to the query. */ value: WebPage[]; /** * A Boolean value that indicates whether the response excluded some results from the answer. If * Bing excluded some results, the value is true. */ readonly someResultsRemoved?: boolean; } /** * Defines a search query. */ export interface Query { /** * The query string. Use this string as the query term in a new search request. */ text: string; /** * The display version of the query term. This version of the query term may contain special * characters that highlight the search term found in the query string. The string contains the * highlighting characters only if the query enabled hit highlighting */ readonly displayText?: string; /** * The URL that takes the user to the Bing search results page for the query.Only related search * results include this field. */ readonly webSearchUrl?: string; readonly searchLink?: string; readonly thumbnail?: ImageObject; } /** * Defines an image answer */ export interface Images extends SearchResultsAnswer { readonly nextOffset?: number; /** * A list of image objects that are relevant to the query. If there are no results, the List is * empty. */ value: ImageObject[]; readonly queryExpansions?: Query[]; readonly similarTerms?: Query[]; readonly relatedSearches?: Query[]; } export interface Article extends CreativeWork { /** * The number of words in the text of the Article. */ readonly wordCount?: number; } /** * Defines a news article. */ export interface NewsArticle extends Article { } /** * Defines a news answer. */ export interface News extends SearchResultsAnswer { /** * An array of NewsArticle objects that contain information about news articles that are relevant * to the query. If there are no results to return for the request, the array is empty. */ value: NewsArticle[]; readonly location?: string; } /** * Defines a list of related queries made by others. */ export interface RelatedSearchesRelatedSearchAnswer extends SearchResultsAnswer { /** * A list of related queries that were made by others. */ value: Query[]; } /** * Defines a suggested query string that likely represents the user's intent. The search results * include this response if Bing determines that the user may have intended to search for something * different. For example, if the user searches for alon brown, Bing may determine that the user * likely intended to search for Alton Brown instead (based on past searches by others of Alon * Brown). */ export interface SpellSuggestions extends SearchResultsAnswer { /** * A list of suggested query strings that may represent the user's intention. The list contains * only one Query object. */ value: Query[]; } /** * Defines a date and time for a geographical location. */ export interface TimeZoneTimeZoneInformation { /** * The name of the geographical location.For example, County; City; City, State; City, State, * Country; or Time Zone. */ location: string; /** * The data and time specified in the form, YYYY-MM-DDThh;mm:ss.ssssssZ. */ time: string; /** * The offset from UTC. For example, UTC-7. */ utcOffset: string; } /** * Defines the data and time of one or more geographic locations. */ export interface TimeZone extends SearchResultsAnswer { /** * The data and time, in UTC, of the geographic location specified in the query. If the query * specified a specific geographic location (for example, a city), this object contains the name * of the geographic location and the current date and time of the location, in UTC. If the query * specified a general geographic location, such as a state or country, this object contains the * date and time of the primary city or state found in the specified state or country. If the * location contains additional time zones, the otherCityTimes field contains the data and time * of cities or states located in the other time zones. */ primaryCityTime: TimeZoneTimeZoneInformation; /** * A list of dates and times of nearby time zones. */ readonly otherCityTimes?: TimeZoneTimeZoneInformation[]; } /** * Defines a video object that is relevant to the query. */ export interface VideoObject extends MediaObject { readonly motionThumbnailUrl?: string; readonly motionThumbnailId?: string; readonly embedHtml?: string; readonly allowHttpsEmbed?: boolean; readonly viewCount?: number; readonly thumbnail?: ImageObject; readonly videoId?: string; readonly allowMobileEmbed?: boolean; readonly isSuperfresh?: boolean; } /** * Defines a video answer. */ export interface Videos extends SearchResultsAnswer { /** * A list of video objects that are relevant to the query. */ value: VideoObject[]; readonly nextOffset?: number; readonly queryExpansions?: Query[]; readonly relatedSearches?: Query[]; } /** * Defines an expression and its answer */ export interface Computation extends Answer { /** * The math or conversion expression. If the query contains a request to convert units of measure * (for example, meters to feet), this field contains the from units and value contains the to * units. If the query contains a mathematical expression such as 2+2, this field contains the * expression and value contains the answer. Note that mathematical expressions may be * normalized. For example, if the query was sqrt(4^2+8^2), the normalized expression may be * sqrt((4^2)+(8^2)). If the user's query is a math question and the textDecorations query * parameter is set to true, the expression string may include formatting markers. For example, * if the user's query is log(2), the normalized expression includes the subscript markers. For * more information, see Hit Highlighting. */ expression: string; /** * The expression's answer. */ value: string; } /** * Defines a search result item to display */ export interface RankingRankingItem { /** * The answer that contains the item to display. Use the type to find the answer in the * SearchResponse object. The type is the name of a SearchResponse field. Possible values * include: 'WebPages', 'Images', 'SpellSuggestions', 'News', 'RelatedSearches', 'Videos', * 'Computation', 'TimeZone' */ answerType: string; /** * A zero-based index of the item in the answer.If the item does not include this field, display * all items in the answer. For example, display all news articles in the News answer. */ readonly resultIndex?: number; /** * The ID that identifies either an answer to display or an item of an answer to display. If the * ID identifies an answer, display all items of the answer. */ readonly value?: Identifiable; readonly htmlIndex?: number; readonly textualIndex?: number; readonly screenshotIndex?: number; } /** * Defines a search results group, such as mainline. */ export interface RankingRankingGroup { /** * A list of search result items to display in the group. */ items: RankingRankingItem[]; } /** * Defines where on the search results page content should be placed and in what order. */ export interface RankingRankingResponse { /** * The search results that should be afforded the most visible treatment (for example, displayed * above the mainline and sidebar). */ readonly pole?: RankingRankingGroup; /** * The search results to display in the mainline. */ readonly mainline?: RankingRankingGroup; /** * The search results to display in the sidebar. */ readonly sidebar?: RankingRankingGroup; } /** * Defines the top-level object that the response includes when the request succeeds. */ export interface SearchResponse extends Response { /** * An object that contains the query string that Bing used for the request. This object contains * the query string as entered by the user. It may also contain an altered query string that Bing * used for the query if the query string contained a spelling mistake. */ readonly queryContext?: QueryContext; /** * A list of webpages that are relevant to the search query. */ readonly webPages?: WebWebAnswer; /** * A list of images that are relevant to the search query. */ readonly images?: Images; /** * A list of news articles that are relevant to the search query. */ readonly news?: News; /** * A list of related queries made by others. */ readonly relatedSearches?: RelatedSearchesRelatedSearchAnswer; /** * The query string that likely represents the user's intent. */ readonly spellSuggestions?: SpellSuggestions; /** * The date and time of one or more geographic locations. */ readonly timeZone?: TimeZone; /** * A list of videos that are relevant to the search query. */ readonly videos?: Videos; /** * The answer to a math expression or units conversion expression. */ readonly computation?: Computation; /** * The order that Bing suggests that you display the search results in. */ readonly rankingResponse?: RankingRankingResponse; } /** * Defines a local entity answer. */ export interface Places extends SearchResultsAnswer { /** * A list of local entities, such as restaurants or hotels. */ value: Thing[]; } /** * Defines the error that occurred. */ export interface ErrorModel { /** * The error code that identifies the category of error. Possible values include: 'None', * 'ServerError', 'InvalidRequest', 'RateLimitExceeded', 'InvalidAuthorization', * 'InsufficientAuthorization' */ code: string; /** * The error code that further helps to identify the error. Possible values include: * 'UnexpectedError', 'ResourceError', 'NotImplemented', 'ParameterMissing', * 'ParameterInvalidValue', 'HttpNotAllowed', 'Blocked', 'AuthorizationMissing', * 'AuthorizationRedundancy', 'AuthorizationDisabled', 'AuthorizationExpired' */ readonly subCode?: string; /** * A description of the error. */ message: string; /** * A description that provides additional information about the error. */ readonly moreDetails?: string; /** * The parameter in the request that caused the error. */ readonly parameter?: string; /** * The parameter's value in the request that was not valid. */ readonly value?: string; } /** * The top-level response that represents a failed request. */ export interface ErrorResponse extends Response { /** * A list of errors that describe the reasons why the request failed. */ errors: ErrorModel[]; } export interface WebWebGrouping { webPages: WebPage[]; /** * Polymorphic Discriminator */ _type: string; } export interface Intangible extends Thing { } export interface StructuredValue extends Intangible { }
the_stack
import _ from 'lodash'; import { Content, ContentVersion, DSL, File, FileTypes } from '@foxpage/foxpage-server-types'; import { CONT_STORE, LOG, PRE, TAG, TYPE } from '../../../config/constant'; import * as Model from '../../models'; import { AppTypeFileUpdate, FileCheck, FileContentVersion, FileFolderContentChildren, FileNameSearch, FilePathSearch, FolderChildren, NewFileInfo, } from '../../types/file-types'; import { FoxCtx, TypeStatus } from '../../types/index-types'; import { generationId, randStr } from '../../utils/tools'; import { BaseService } from '../base-service'; import * as Service from '../index'; export class FileInfoService extends BaseService<File> { private static _instance: FileInfoService; constructor() { super(Model.file); } /** * Single instance * @returns ContentInfoService */ public static getInstance(): FileInfoService { this._instance || (this._instance = new FileInfoService()); return this._instance; } /** * Add file details, only generate query statements needed for transactions, * and return the details of the created content * @param {Partial<File>} params * @returns File */ create(params: Partial<File>, options: { ctx: FoxCtx }): File { const fileDetail: File = { id: params.id || generationId(PRE.FILE), applicationId: params.applicationId || '', name: _.trim(params.name) || '', intro: params.intro || '', suffix: params.suffix || '', folderId: params.folderId || '', tags: params.tags || [], type: params.type as FileTypes, creator: params.creator || options.ctx.userInfo.id, }; options.ctx.transactions.push(Model.file.addDetailQuery(fileDetail)); options.ctx.operations.push( ...Service.log.addLogItem(LOG.CREATE, fileDetail, { dataType: fileDetail.type }), ); return fileDetail; } /** * Create file details, the content of the specified type file, version information * @param {NewFileInfo} params * @returns Record */ async addFileDetail( params: NewFileInfo, options: { ctx: FoxCtx }, ): Promise<Record<string, number | (File & { contentId: string })>> { const newFileCheck = _.pick(params, ['applicationId', 'folderId', 'name', 'type', 'suffix']) as FileCheck; newFileCheck.deleted = false; const [appDetail, fileExist] = await Promise.all([ Service.application.getDetailById(params.applicationId), this.checkExist(newFileCheck), ]); // Check the validity of the application ID, check the existence of the file if (!appDetail || appDetail.deleted || fileExist) { return fileExist ? { code: 2 } : { code: 1 }; } // Check if pathname is duplicate if (params.type === TYPE.PAGE) { const pathnameExist = await Service.file.check.pathNameExist({ applicationId: params.applicationId, tags: params.tags || [], fileId: '', }); if (pathnameExist) { return { code: 3 }; // pathname already exists } } // Create document details const fileDetail: File = { id: generationId(PRE.FILE), applicationId: params.applicationId, name: params.name, intro: params.intro || '', folderId: params.folderId || '', type: params.type as FileTypes, tags: params.tags || [], suffix: params.suffix || '', creator: params.creator || options.ctx.userInfo.id, }; options.ctx.transactions.push(Model.file.addDetailQuery(fileDetail)); options.ctx.operations.push(...Service.log.addLogItem(LOG.CREATE, fileDetail, { dataType: params.type })); const fileContentDetail = Object.assign({}, fileDetail, { contentId: '' }); // Create content details if ([TYPE.PAGE, TYPE.TEMPLATE].indexOf(params.type) === -1) { const contentDetail = Service.content.info.addContentDetail( { title: params.name, fileId: fileDetail.id }, { ctx: options.ctx, type: params.type, content: params.content }, ); fileContentDetail.contentId = contentDetail.id; } return { code: 0, data: fileContentDetail }; } /** * Update file details * @param {AppTypeFileUpdate} params * @returns Promise */ async updateFileDetail( params: AppTypeFileUpdate, options: { ctx: FoxCtx }, ): Promise<Record<string, number>> { const fileDetail = await this.getDetailById(params.id); if (!fileDetail || fileDetail.deleted) { return { code: 1 }; // Invalid file id } // Check if the file name already exists if (params.name && fileDetail.name !== params.name) { const fileExist = await Service.file.check.checkFileNameExist( params.id, Object.assign( { name: fileDetail.name }, _.pick(params, ['applicationId', 'folderId', 'name', 'type', 'suffix']), ) as FileCheck, ); if (fileExist) { return { code: 2 }; // New file name already exists } } // Check if pathname is duplicate if (fileDetail.type === TYPE.PAGE) { const pathnameExist = await Service.file.check.pathNameExist({ applicationId: params.applicationId, tags: params.tags || [], fileId: params.id, }); if (pathnameExist) { return { code: 3 }; // pathname already exists } // Record file update log if (params.tags && params.tags !== fileDetail.tags) { options.ctx.operations.push( ...Service.log.addLogItem(LOG.FILE_TAG, fileDetail, { fileId: fileDetail.id }), ); } } // Update file options.ctx.transactions.push( Model.file.updateDetailQuery(params.id, _.pick(params, ['name', 'intro', 'type', 'tags'])), ); // Update content name if ([TYPE.VARIABLE, TYPE.CONDITION].indexOf(fileDetail.type) !== -1) { const contentList = await Service.content.file.getContentByFileIds([fileDetail.id]); contentList[0] && Service.content.info.updateDetailQuery(contentList[0].id, { title: params.name }); } // Save logs options.ctx.operations.push( ...Service.log.addLogItem(LOG.FILE_UPDATE, fileDetail, { dataType: fileDetail.type }), ); return { code: 0 }; } /** * Update the specified data directly * @param {string} id * @param {Partial<Content>} params * @returns void */ updateFileItem(id: string, params: Partial<File>, options: { ctx: FoxCtx }): void { options.ctx.transactions.push(Model.file.updateDetailQuery(id, params)); options.ctx.operations.push( ...Service.log.addLogItem(LOG.FILE_UPDATE, Object.assign({ id }, params), { fileId: params.id }), ); } /** * Update the deletion status of the file. When deleting, * you need to check whether there is any content being referenced. * When you enable it, you don’t need to check * @param {TypeStatus} params * @returns Promise */ async setFileDeleteStatus(params: TypeStatus, options: { ctx: FoxCtx }): Promise<Record<string, number>> { const fileDetail = await this.getDetailById(params.id); if (!fileDetail) { return { code: 1 }; // Invalid file information } // Get all content and version under the file const contentVersion = await Service.content.list.getContentAndVersionListByFileIds([params.id]); // Check if there is information that content is referenced under file const relations = await Service.relation.getContentRelationalByIds( params.id, _.map(contentVersion.contentList, 'id'), ); if (relations.length > 0) { return { code: 2 }; // There is referenced relation information } // Set file enable state, set file, delete state of content and version options.ctx.transactions.push( this.setDeleteStatus(params.id, params.status), Service.content.info.batchUpdateDetailQuery({ fileId: params.id }, { deleted: true }), Service.version.info.setDeleteStatus(_.map(contentVersion.versionList, 'id'), true), ); // Save logs options.ctx.operations.push( ...Service.log.addLogItem(LOG.FILE_REMOVE, [fileDetail], { dataType: fileDetail.type }), ...Service.log.addLogItem(LOG.CONTENT_REMOVE, contentVersion?.contentList || [], { dataType: fileDetail.type, }), ); return { code: 0 }; } /** * Set the delete status of specified files in batches, * @param {File[]} fileList * @returns void */ batchSetFileDeleteStatus(fileList: File[], options: { ctx: FoxCtx; status?: boolean }): void { const status = options.status === false ? false : true; options.ctx.transactions.push(this.setDeleteStatus(_.map(fileList, 'id'), status)); options.ctx.operations.push(...Service.log.addLogItem(LOG.FILE_REMOVE, fileList || [])); } /** * Obtain file information by file name * @param {FileNameSearch} params * @returns {File[]} Promise */ async getFileIdByNames(params: FileNameSearch): Promise<File[]> { return Model.file.getDetailByNames(params); } /** * Get file information by name * @param {FilePathSearch} params * @param {boolean=false} createNew * @returns Promise */ async getFileDetailByNames( params: FilePathSearch, options: { ctx: FoxCtx; createNew?: boolean }, ): Promise<Partial<File>> { const createNew = options?.createNew || false; params.pathList = _.pull(params.pathList, ''); let folderId = params.parentFolderId; let fileDetail: Partial<File> = {}; if (params.pathList && params.pathList.length > 0) { folderId = await Service.folder.info.getFolderIdByPathRecursive( { applicationId: params.applicationId, parentFolderId: folderId, pathList: params.pathList, }, options, ); } if (folderId) { fileDetail = await this.getDetail({ applicationId: params.applicationId, folderId: folderId, name: params.fileName, }); } if ((_.isEmpty(fileDetail) || fileDetail.deleted) && createNew) { fileDetail = this.create( { applicationId: params.applicationId, name: params.fileName, folderId: folderId, type: TYPE.PAGE as FileTypes, }, { ctx: options.ctx }, ); } return fileDetail; } /** * Create file content and content version information * return fileId,contentId,versionId * @param {File} params * @returns Promise */ createFileContentVersion(params: File, options: FileContentVersion): Record<string, string> { // Create page content information const contentId = generationId(PRE.CONTENT); const contentDetail: Content = { id: contentId, title: params.name || '', liveVersionNumber: 0, tags: [], fileId: params.id, creator: params.creator || '', }; // Added default version information const contentVersionId = generationId(PRE.CONTENT_VERSION); const contentVersionDetail: ContentVersion = { id: contentVersionId, contentId: contentId, version: options.hasVersion ? '0.0.1' : '', versionNumber: options.hasVersion ? 1 : 0, creator: params.creator || '', content: options.content || {}, }; this.create(params, { ctx: options.ctx }); Service.content.info.create(contentDetail, { ctx: options.ctx }); Service.version.info.create(contentVersionDetail, { ctx: options.ctx }); // TODO Save logs return { fileId: params.id, contentId, contentVersionId }; } /** * Recursively get the file id in the hierarchical file directory * @param {{folders:FolderChildren[];files:File[]}} params * @returns string */ getFileIdFromResourceRecursive(params: { folders: FolderChildren[]; files: File[] }): string[] { const { folders = [], files = [] } = params; let fileIds = _.map(files, 'id'); folders.forEach((folder) => { if (folder.children) { fileIds.concat(this.getFileIdFromResourceRecursive(folder.children)); } }); return fileIds; } /** * Recursively put content details into the corresponding file * @param {FileFolderContentChildren} params * @param {Record<string} contentObject * @param {Record<string} versionObject * @returns FileFolderContentChildren */ addContentToFileRecursive( params: FileFolderContentChildren, contentObject: Record<string, Content>, versionObject: Record<string, ContentVersion>, ): FileFolderContentChildren { if (params.files?.length > 0) { params.files.forEach((file) => { file.contentId = contentObject[file.id] ? contentObject[file.id].id : ''; file.content = contentObject[file.id] ? versionObject[contentObject[file.id].id].content : {}; }); } if (params.folders?.length > 0) { params.folders.forEach((folder) => { if (folder?.children?.files?.length > 0) { folder.children = this.addContentToFileRecursive(folder.children, contentObject, versionObject); } }); } return params; } /** * Get file details through pathName * @param {string} applicationId * @param {string} pathName * @returns Promise */ async getFileDetailByPathname(applicationId: string, pathName: string): Promise<Partial<File>> { // Get files that match the pathname tag let fileDetail: File | undefined; const fileList = await Service.file.list.find({ applicationId: applicationId, tags: { $elemMatch: { pathname: pathName } }, deleted: false, }); fileDetail = fileList.find((file) => { return ( file.tags?.findIndex((tag) => { if (tag.pathname && tag.pathname === pathName && (_.isNil(tag.status) || tag.status)) { return true; } }) !== -1 ); }); return fileDetail || {}; } /** * Copy files * Get all the contents of the source file, or the contents of the live version * Copy the details of each content to the content of the new page * If there are dependencies in the content that already exist in the relations, * use the relation information directly * * setLive: set the first version to live after clone from store * @param {string} sourceFileId * @param {string} options? * @returns Promise */ async copyFile( sourceFileId: string, targetApplicationId: string, options: { ctx: FoxCtx; folderId: string; // ID of the folder to which the file belongs hasLive: boolean; // Whether to copy only the content of the live version type?: string; // store | build, store: copy file from store, build: copy file in build page targetFileId?: string; relations?: Record<string, Record<string, string>>; setLive?: boolean; }, ): Promise<Record<string, Record<string, string>>> { if (!options.relations) { options.relations = {}; } !options.folderId && (options.folderId = ''); !options.type && (options.type = CONT_STORE); options.hasLive === undefined && (options.hasLive = true); // Get a list of source file contents let [fileDetail, contentList] = await Promise.all([ this.getDetailById(sourceFileId), Service.content.list.find({ fileId: sourceFileId }), ]); if (options.hasLive) { contentList = contentList.filter((content) => content.liveVersionNumber > 0); } if (contentList.length === 0) { return options.relations; } // Get the version details of all content const contentVersionList = await Service.version.live.getContentAndRelationVersion( _.map(contentList, 'id'), ); let relationsContentIds: string[] = []; let contentDSLObject: Record<string, DSL> = {}; contentVersionList.forEach((content) => { contentDSLObject[content.content?.id] = content.content; if (content.relations) { const contentRelations = _.flatten(_.toArray(content.relations)); contentDSLObject = _.merge(contentDSLObject, _.keyBy(contentRelations, 'id')); relationsContentIds.push(..._.map(contentRelations, 'id')); } }); const [relationsFileObject, relationContentList] = await Promise.all([ Service.file.list.getContentFileByIds(relationsContentIds), Service.content.list.getDetailByIds(relationsContentIds), ]); const fileList = _.toArray(relationsFileObject); contentList = contentList.concat(relationContentList); fileList.unshift(fileDetail); // Create a new file, and file associated data file for (const file of fileList) { if (!options.relations[file.id]) { // Remove some tags in file tags file.tags = this.removeTags(file.tags || [], [TAG.CLONE, TAG.COPY]); const newFileDetail = Service.file.info.create( { applicationId: targetApplicationId, name: options.type === CONT_STORE ? file.name : [file.name, randStr(4)].join('_'), intro: file.intro, suffix: file.suffix, tags: file.tags?.concat({ [options.type === CONT_STORE ? TAG.COPY : TAG.CLONE]: file.id }), type: file.type, folderId: options.folderId || '', }, { ctx: options.ctx }, ); options.relations[file.id] = { newId: newFileDetail.id }; } } // Pre-match content Id let tempRelations: Record<string, Record<string, string>> = {}; for (const content of contentList) { !options.relations[content.id] && (tempRelations[content.id] = { newId: generationId(PRE.CONTENT_VERSION), oldName: content.title, newName: [content.title, randStr(4)].join('_'), }); } // Create file content for (const content of contentList) { options.relations = Service.content.info.copyContent(content, contentDSLObject[content.id], { ctx: options.ctx, relations: options.relations, tempRelations: {}, setLive: options.setLive || false, }); } return options.relations; } /** * @param {any[]} tagList * @param {string[]} tagIndexes * @returns any */ removeTags(tagList: any[], tagIndexes: string[]): any[] { tagList.forEach((tag, index) => { tag = _.omit(tag, tagIndexes); if (_.isEmpty(tag)) { delete tagList[index]; } }); return tagList; } }
the_stack
import * as coreClient from "@azure/core-client"; /** Result of the request to list Relay operations. It contains a list of operations and a URL link to get the next set of results. */ export interface OperationListResult { /** * List of Relay operations supported by resource provider. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: Operation[]; /** * URL to get the next set of operation list results if there are any. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** A Relay REST API operation. */ export interface Operation { /** * Operation name: {provider}/{resource}/{operation} * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** The object that represents the operation. */ display?: OperationDisplay; } /** The object that represents the operation. */ export interface OperationDisplay { /** * Service provider: Relay. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provider?: string; /** * Resource on which the operation is performed: Invoice, etc. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resource?: string; /** * Operation type: Read, write, delete, etc. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly operation?: string; } /** Error reponse indicates Relay service is not able to process the incoming request. The reason is provided in the error message. */ export interface ErrorResponse { /** Error code. */ code?: string; /** Error message indicating why the operation failed. */ message?: string; } /** Description of the check name availability request properties. */ export interface CheckNameAvailability { /** The namespace name to check for availability. The namespace name can contain only letters, numbers, and hyphens. The namespace must start with a letter, and it must end with a letter or number. */ name: string; } /** Description of the check name availability request properties. */ export interface CheckNameAvailabilityResult { /** * The detailed info regarding the reason associated with the namespace. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; /** Value indicating namespace is available. Returns true if the namespace is available; otherwise, false. */ nameAvailable?: boolean; /** The reason for unavailability of a namespace. */ reason?: UnavailableReason; } /** The response from the list namespace operation. */ export interface RelayNamespaceListResult { /** Result of the list namespace operation. */ value?: RelayNamespace[]; /** Link to the next set of results. Not empty if value contains incomplete list of namespaces. */ nextLink?: string; } /** SKU of the namespace. */ export interface Sku { /** Name of this SKU. */ name: "Standard"; /** The tier of this SKU. */ tier?: "Standard"; } /** The resource definition. */ export interface Resource { /** * Resource ID. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * Resource name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Resource type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; } /** The response from the list namespace operation. */ export interface AuthorizationRuleListResult { /** Result of the list authorization rules operation. */ value?: AuthorizationRule[]; /** Link to the next set of results. Not empty if value contains incomplete list of authorization rules. */ nextLink?: string; } /** Namespace/Relay Connection String */ export interface AccessKeys { /** Primary connection string of the created namespace authorization rule. */ primaryConnectionString?: string; /** Secondary connection string of the created namespace authorization rule. */ secondaryConnectionString?: string; /** A base64-encoded 256-bit primary key for signing and validating the SAS token. */ primaryKey?: string; /** A base64-encoded 256-bit secondary key for signing and validating the SAS token. */ secondaryKey?: string; /** A string that describes the authorization rule. */ keyName?: string; } /** Parameters supplied to the regenerate authorization rule operation, specifies which key neeeds to be reset. */ export interface RegenerateAccessKeyParameters { /** The access key to regenerate. */ keyType: KeyType; /** Optional. If the key value is provided, this is set to key type, or autogenerated key value set for key type. */ key?: string; } /** The response of the list hybrid connection operation. */ export interface HybridConnectionListResult { /** Result of the list hybrid connections. */ value?: HybridConnection[]; /** Link to the next set of results. Not empty if value contains incomplete list hybrid connection operation. */ nextLink?: string; } /** The response of the list WCF relay operation. */ export interface WcfRelaysListResult { /** Result of the list WCF relay operation. */ value?: WcfRelay[]; /** Link to the next set of results. Not empty if value contains incomplete list of WCF relays. */ nextLink?: string; } /** Definition of resource. */ export type TrackedResource = Resource & { /** Resource location. */ location: string; /** Resource tags. */ tags?: { [propertyName: string]: string }; }; /** Definition of resource. */ export type ResourceNamespacePatch = Resource & { /** Resource tags. */ tags?: { [propertyName: string]: string }; }; /** Description of a namespace authorization rule. */ export type AuthorizationRule = Resource & { /** The rights associated with the rule. */ rights: AccessRights[]; }; /** Description of hybrid connection resource. */ export type HybridConnection = Resource & { /** * The time the hybrid connection was created. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdAt?: Date; /** * The time the namespace was updated. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly updatedAt?: Date; /** * The number of listeners for this hybrid connection. Note that min : 1 and max:25 are supported. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly listenerCount?: number; /** Returns true if client authorization is needed for this hybrid connection; otherwise, false. */ requiresClientAuthorization?: boolean; /** The usermetadata is a placeholder to store user-defined string data for the hybrid connection endpoint. For example, it can be used to store descriptive data, such as a list of teams and their contact information. Also, user-defined configuration settings can be stored. */ userMetadata?: string; }; /** Description of the WCF relay resource. */ export type WcfRelay = Resource & { /** * Returns true if the relay is dynamic; otherwise, false. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly isDynamic?: boolean; /** * The time the WCF relay was created. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdAt?: Date; /** * The time the namespace was updated. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly updatedAt?: Date; /** * The number of listeners for this relay. Note that min :1 and max:25 are supported. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly listenerCount?: number; /** WCF relay type. */ relayType?: Relaytype; /** Returns true if client authorization is needed for this relay; otherwise, false. */ requiresClientAuthorization?: boolean; /** Returns true if transport security is needed for this relay; otherwise, false. */ requiresTransportSecurity?: boolean; /** The usermetadata is a placeholder to store user-defined string data for the WCF Relay endpoint. For example, it can be used to store descriptive data, such as list of teams and their contact information. Also, user-defined configuration settings can be stored. */ userMetadata?: string; }; /** Description of a namespace resource. */ export type RelayNamespace = TrackedResource & { /** SKU of the namespace. */ sku?: Sku; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: ProvisioningStateEnum; /** * The time the namespace was created. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdAt?: Date; /** * The time the namespace was updated. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly updatedAt?: Date; /** * Endpoint you can use to perform Service Bus operations. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly serviceBusEndpoint?: string; /** * Identifier for Azure Insights metrics. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly metricId?: string; }; /** Description of a namespace resource. */ export type RelayUpdateParameters = ResourceNamespacePatch & { /** SKU of the namespace. */ sku?: Sku; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: ProvisioningStateEnum; /** * The time the namespace was created. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdAt?: Date; /** * The time the namespace was updated. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly updatedAt?: Date; /** * Endpoint you can use to perform Service Bus operations. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly serviceBusEndpoint?: string; /** * Identifier for Azure Insights metrics. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly metricId?: string; }; /** Defines values for UnavailableReason. */ export type UnavailableReason = | "None" | "InvalidName" | "SubscriptionIsDisabled" | "NameInUse" | "NameInLockdown" | "TooManyNamespaceInCurrentSubscription"; /** Defines values for ProvisioningStateEnum. */ export type ProvisioningStateEnum = | "Created" | "Succeeded" | "Deleted" | "Failed" | "Updating" | "Unknown"; /** Defines values for AccessRights. */ export type AccessRights = "Manage" | "Send" | "Listen"; /** Defines values for KeyType. */ export type KeyType = "PrimaryKey" | "SecondaryKey"; /** Defines values for Relaytype. */ export type Relaytype = "NetTcp" | "Http"; /** Optional parameters. */ export interface OperationsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult; /** Optional parameters. */ export interface OperationsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult; /** Optional parameters. */ export interface NamespacesCheckNameAvailabilityOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the checkNameAvailability operation. */ export type NamespacesCheckNameAvailabilityResponse = CheckNameAvailabilityResult; /** Optional parameters. */ export interface NamespacesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type NamespacesListResponse = RelayNamespaceListResult; /** Optional parameters. */ export interface NamespacesListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type NamespacesListByResourceGroupResponse = RelayNamespaceListResult; /** Optional parameters. */ export interface NamespacesCreateOrUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the createOrUpdate operation. */ export type NamespacesCreateOrUpdateResponse = RelayNamespace; /** Optional parameters. */ export interface NamespacesDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface NamespacesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type NamespacesGetResponse = RelayNamespace; /** Optional parameters. */ export interface NamespacesUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the update operation. */ export type NamespacesUpdateResponse = RelayNamespace; /** Optional parameters. */ export interface NamespacesListAuthorizationRulesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRules operation. */ export type NamespacesListAuthorizationRulesResponse = AuthorizationRuleListResult; /** Optional parameters. */ export interface NamespacesCreateOrUpdateAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdateAuthorizationRule operation. */ export type NamespacesCreateOrUpdateAuthorizationRuleResponse = AuthorizationRule; /** Optional parameters. */ export interface NamespacesDeleteAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface NamespacesGetAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getAuthorizationRule operation. */ export type NamespacesGetAuthorizationRuleResponse = AuthorizationRule; /** Optional parameters. */ export interface NamespacesListKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listKeys operation. */ export type NamespacesListKeysResponse = AccessKeys; /** Optional parameters. */ export interface NamespacesRegenerateKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the regenerateKeys operation. */ export type NamespacesRegenerateKeysResponse = AccessKeys; /** Optional parameters. */ export interface NamespacesListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type NamespacesListNextResponse = RelayNamespaceListResult; /** Optional parameters. */ export interface NamespacesListByResourceGroupNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroupNext operation. */ export type NamespacesListByResourceGroupNextResponse = RelayNamespaceListResult; /** Optional parameters. */ export interface NamespacesListAuthorizationRulesNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRulesNext operation. */ export type NamespacesListAuthorizationRulesNextResponse = AuthorizationRuleListResult; /** Optional parameters. */ export interface HybridConnectionsListByNamespaceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByNamespace operation. */ export type HybridConnectionsListByNamespaceResponse = HybridConnectionListResult; /** Optional parameters. */ export interface HybridConnectionsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type HybridConnectionsCreateOrUpdateResponse = HybridConnection; /** Optional parameters. */ export interface HybridConnectionsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HybridConnectionsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type HybridConnectionsGetResponse = HybridConnection; /** Optional parameters. */ export interface HybridConnectionsListAuthorizationRulesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRules operation. */ export type HybridConnectionsListAuthorizationRulesResponse = AuthorizationRuleListResult; /** Optional parameters. */ export interface HybridConnectionsCreateOrUpdateAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdateAuthorizationRule operation. */ export type HybridConnectionsCreateOrUpdateAuthorizationRuleResponse = AuthorizationRule; /** Optional parameters. */ export interface HybridConnectionsDeleteAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HybridConnectionsGetAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getAuthorizationRule operation. */ export type HybridConnectionsGetAuthorizationRuleResponse = AuthorizationRule; /** Optional parameters. */ export interface HybridConnectionsListKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listKeys operation. */ export type HybridConnectionsListKeysResponse = AccessKeys; /** Optional parameters. */ export interface HybridConnectionsRegenerateKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the regenerateKeys operation. */ export type HybridConnectionsRegenerateKeysResponse = AccessKeys; /** Optional parameters. */ export interface HybridConnectionsListByNamespaceNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByNamespaceNext operation. */ export type HybridConnectionsListByNamespaceNextResponse = HybridConnectionListResult; /** Optional parameters. */ export interface HybridConnectionsListAuthorizationRulesNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRulesNext operation. */ export type HybridConnectionsListAuthorizationRulesNextResponse = AuthorizationRuleListResult; /** Optional parameters. */ export interface WCFRelaysListByNamespaceOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByNamespace operation. */ export type WCFRelaysListByNamespaceResponse = WcfRelaysListResult; /** Optional parameters. */ export interface WCFRelaysCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type WCFRelaysCreateOrUpdateResponse = WcfRelay; /** Optional parameters. */ export interface WCFRelaysDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface WCFRelaysGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type WCFRelaysGetResponse = WcfRelay; /** Optional parameters. */ export interface WCFRelaysListAuthorizationRulesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRules operation. */ export type WCFRelaysListAuthorizationRulesResponse = AuthorizationRuleListResult; /** Optional parameters. */ export interface WCFRelaysCreateOrUpdateAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdateAuthorizationRule operation. */ export type WCFRelaysCreateOrUpdateAuthorizationRuleResponse = AuthorizationRule; /** Optional parameters. */ export interface WCFRelaysDeleteAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface WCFRelaysGetAuthorizationRuleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getAuthorizationRule operation. */ export type WCFRelaysGetAuthorizationRuleResponse = AuthorizationRule; /** Optional parameters. */ export interface WCFRelaysListKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listKeys operation. */ export type WCFRelaysListKeysResponse = AccessKeys; /** Optional parameters. */ export interface WCFRelaysRegenerateKeysOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the regenerateKeys operation. */ export type WCFRelaysRegenerateKeysResponse = AccessKeys; /** Optional parameters. */ export interface WCFRelaysListByNamespaceNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByNamespaceNext operation. */ export type WCFRelaysListByNamespaceNextResponse = WcfRelaysListResult; /** Optional parameters. */ export interface WCFRelaysListAuthorizationRulesNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listAuthorizationRulesNext operation. */ export type WCFRelaysListAuthorizationRulesNextResponse = AuthorizationRuleListResult; /** Optional parameters. */ export interface RelayAPIOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import { URLSearchParams } from 'url'; import { Route } from '@vercel/routing-utils'; import { Proxy } from '../src/proxy'; import { generateMockedFetchResponse } from './test-utils'; describe('Proxy unit', () => { test('Captured groups', async () => { const mockedFetch = jest .fn() .mockImplementation(() => generateMockedFetchResponse(404, {}, { etag: '"notfound"' }) ); const routesConfig = [{ src: '/api/(.*)', dest: '/endpoints/$1.js' }]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, {}, 'http://localhost', '/api/user' ); expect(result).toEqual({ found: true, dest: '/endpoints/user.js', continue: false, status: undefined, headers: {}, uri_args: new URLSearchParams(), matched_route: routesConfig[0], matched_route_idx: 0, userDest: true, isDestUrl: false, phase: undefined, }); }); test('Named groups', async () => { const mockedFetch = jest .fn() .mockImplementation(() => generateMockedFetchResponse(404, {}, { etag: '"notfound"' }) ); const routesConfig = [{ src: '/user/(?<id>.+)', dest: '/user.js?id=$id' }]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, {}, 'http://localhost', '/user/123' ); expect(result).toEqual({ found: true, dest: '/user.js', continue: false, status: undefined, headers: {}, uri_args: new URLSearchParams('id=123'), matched_route: routesConfig[0], matched_route_idx: 0, userDest: true, isDestUrl: false, phase: undefined, }); }); test('Optional named groups', async () => { const mockedFetch = jest .fn() .mockImplementation(() => generateMockedFetchResponse(404, {}, { etag: '"notfound"' }) ); const routesConfig = [ { src: '/api/hello(/(?<name>[^/]+))?', dest: '/api/functions/hello/index.js?name=$name', }, ]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, {}, 'http://localhost', '/api/hello' ); expect(result).toEqual({ found: true, dest: '/api/functions/hello/index.js', continue: false, status: undefined, headers: {}, uri_args: new URLSearchParams('name'), matched_route: routesConfig[0], matched_route_idx: 0, userDest: true, isDestUrl: false, phase: undefined, }); }); test('Shared lambda', async () => { const mockedFetch = jest .fn() .mockImplementation(() => generateMockedFetchResponse(404, {}, { etag: '"notfound"' }) ); const routesConfig = [ { src: '^/product/\\[\\.\\.\\.slug\\]/?$', dest: '/__NEXT_PAGE_LAMBDA_0', headers: { 'x-nextjs-page': '/product/[...slug]', }, check: true, }, ]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, { '/__NEXT_PAGE_LAMBDA_0': 'localhost' }, 'http://localhost', '/product/[...slug]?slug=hello/world' ); expect(result).toEqual({ found: true, dest: '/__NEXT_PAGE_LAMBDA_0', continue: false, status: undefined, headers: { 'x-nextjs-page': '/product/[...slug]' }, uri_args: new URLSearchParams('slug=hello/world'), matched_route: routesConfig[0], matched_route_idx: 0, userDest: true, isDestUrl: false, phase: undefined, target: 'lambda', }); }); test('Slug group and shared lambda', async () => { const mockedFetch = jest .fn() .mockImplementation(() => generateMockedFetchResponse(404, {}, { etag: '"notfound"' }) ); const routesConfig = [ { src: '^/product/(?<slug>.+?)(?:/)?$', dest: '/product/[...slug]?slug=$slug', check: true, }, { src: '^/product/\\[\\.\\.\\.slug\\]/?$', dest: '/__NEXT_PAGE_LAMBDA_0', headers: { 'x-nextjs-page': '/product/[...slug]', }, check: true, }, ]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, { '/__NEXT_PAGE_LAMBDA_0': 'localhost', }, 'http://localhost', '/product/hello/world' ); expect(result).toEqual({ found: true, dest: '/__NEXT_PAGE_LAMBDA_0', continue: false, status: undefined, headers: { 'x-nextjs-page': '/product/[...slug]' }, uri_args: new URLSearchParams('slug=hello/world'), matched_route: routesConfig[1], matched_route_idx: 1, userDest: true, isDestUrl: false, phase: undefined, target: 'lambda', }); }); test('Ignore other routes when no continue is set', async () => { const mockedFetch = jest .fn() .mockImplementation(() => generateMockedFetchResponse(404, {}, { etag: '"notfound"' }) ); const routesConfig = [ { src: '/about', dest: '/about.html' }, { src: '/about', dest: '/about.php' }, ]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, {}, 'http://localhost', '/about' ); expect(result).toEqual({ found: true, dest: '/about.html', continue: false, status: undefined, headers: {}, uri_args: new URLSearchParams(), matched_route: routesConfig[0], matched_route_idx: 0, userDest: true, isDestUrl: false, phase: undefined, }); }); test('Continue after first route found', async () => { const mockedFetch = jest .fn() .mockImplementation(() => generateMockedFetchResponse(404, {}, { etag: '"notfound"' }) ); const routesConfig = [ { src: '/about', dest: '/about.html', headers: { 'x-test': 'test', }, continue: true, }, { src: '/about', dest: '/about.php' }, ]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, {}, 'http://localhost', '/about' ); expect(result).toEqual({ found: true, dest: '/about.php', continue: false, status: undefined, headers: { 'x-test': 'test', }, uri_args: new URLSearchParams(), matched_route: routesConfig[1], matched_route_idx: 1, userDest: true, isDestUrl: false, phase: undefined, }); }); describe('Redirect: Remove trailing slash', () => { const routesConfig: Route[] = [ { src: '^(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))\\/$', headers: { Location: '/$1', }, status: 308, continue: true, }, { handle: 'filesystem', }, ]; let proxy: Proxy; beforeAll(() => { const mockedFetch = jest.fn().mockImplementation((url: string) => { if (url === `localhost/filesystem/123/${encodeURIComponent('test')}`) { return generateMockedFetchResponse(200, {}, { etag: '"found"' }); } return generateMockedFetchResponse(404, {}, { etag: '"notfound"' }); }); proxy = new Proxy(mockedFetch as any); }); test('Matches static route, but has a trailing slash', async () => { const result = await proxy.route( '123', routesConfig, {}, 'http://localhost', '/test/' ); expect(result).toEqual({ found: true, dest: '/test/', continue: true, status: 308, headers: { Location: '/test' }, uri_args: new URLSearchParams(), matched_route: routesConfig[0], matched_route_idx: 0, userDest: false, isDestUrl: false, phase: undefined, target: undefined, }); }); test('Matches no route', async () => { const result = await proxy.route( '123', routesConfig, {}, 'http://localhost', '/other-route/' ); expect(result).toEqual({ found: true, dest: '/other-route/', continue: true, status: 308, headers: { Location: '/other-route' }, uri_args: new URLSearchParams(), matched_route: routesConfig[0], matched_route_idx: 0, userDest: false, isDestUrl: false, phase: undefined, target: undefined, }); }); test('Has querystring', async () => { const result = await proxy.route( '123', routesConfig, {}, 'http://localhost', '/other-route/?foo=bar' ); expect(result).toEqual({ found: true, dest: '/other-route/', continue: true, status: 308, headers: { Location: '/other-route' }, uri_args: new URLSearchParams('foo=bar'), matched_route: routesConfig[0], matched_route_idx: 0, userDest: false, isDestUrl: false, phase: undefined, target: undefined, }); }); }); test('With trailing slash', async () => { const mockedFetch = jest.fn().mockImplementation((url: string) => { if ( url === `http://localhost/filesystem/123/${encodeURIComponent( 'test/index' )}` || url === `http://localhost/filesystem/123/${encodeURIComponent('index')}` ) { return generateMockedFetchResponse(200, {}, { etag: '"found"' }); } return generateMockedFetchResponse(404, {}, { etag: '"notfound"' }); }); const routesConfig: Route[] = [ { handle: 'filesystem', }, ]; const proxy = new Proxy(mockedFetch as any); const result1 = await proxy.route( '123', routesConfig, {}, 'http://localhost', '/test/' ); expect(result1).toEqual({ found: true, dest: '/test/index', continue: false, status: undefined, headers: {}, isDestUrl: false, phase: 'filesystem', target: 'filesystem', }); const result2 = await proxy.route( '123', routesConfig, {}, 'http://localhost', '/' ); expect(result2).toEqual({ found: true, dest: '/index', continue: false, status: undefined, headers: {}, isDestUrl: false, phase: 'filesystem', target: 'filesystem', }); }); test('Redirect partial replace', async () => { const mockedFetch = jest .fn() .mockImplementation(() => generateMockedFetchResponse(404, {}, { etag: '"notfound"' }) ); const routesConfig = [ { src: '^\\/redir(?:\\/([^\\/]+?))$', headers: { Location: '/$1', }, status: 307, }, { src: '^/param/?$', dest: '/__NEXT_PAGE_LAMBDA_0', headers: { 'x-nextjs-page': '/param', }, check: true, }, ] as Route[]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, {}, 'http://localhost', '/redir/other-path' ); expect(result).toEqual({ found: true, dest: '/redir/other-path', continue: false, status: 307, headers: { Location: '/other-path' }, uri_args: new URLSearchParams(), matched_route: routesConfig[0], matched_route_idx: 0, userDest: false, isDestUrl: false, phase: undefined, target: undefined, }); }); test('Redirect to partial path', async () => { const mockedFetch = jest .fn() .mockImplementation(() => generateMockedFetchResponse(404, {}, { etag: '"notfound"' }) ); const routesConfig = [ { src: '^\\/two(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))?$', headers: { Location: '/newplacetwo/$1', }, status: 308, }, ] as Route[]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, {}, 'http://localhost', '/two/some/path?foo=bar' ); expect(result).toEqual({ found: true, dest: '/two/some/path', continue: false, status: 308, headers: { Location: '/newplacetwo/some/path' }, uri_args: new URLSearchParams('foo=bar'), matched_route: routesConfig[0], matched_route_idx: 0, userDest: false, isDestUrl: false, phase: undefined, target: undefined, }); }); test('External rewrite', async () => { const mockedFetch = jest .fn() .mockImplementation(() => generateMockedFetchResponse(404, {}, { etag: '"notfound"' }) ); const routesConfig = [ { src: '^\\/docs(?:\\/([^\\/]+?))$', dest: 'http://example.com/docs/$1', check: true, }, ] as Route[]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, {}, 'http://localhost', '/docs/hello-world' ); expect(result).toEqual({ found: true, dest: 'http://example.com/docs/hello-world', continue: false, status: undefined, headers: {}, uri_args: new URLSearchParams(''), matched_route: routesConfig[0], matched_route_idx: 0, userDest: false, isDestUrl: true, phase: undefined, target: 'url', }); }); test('Rewrite with ^ and $', async () => { const mockedFetch = jest .fn() .mockImplementation(() => generateMockedFetchResponse(404, {}, { etag: '"notfound"' }) ); const routesConfig = [ { src: '^/$', dest: '/en', continue: true, }, ] as Route[]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, {}, 'http://localhost', '/' ); expect(result).toEqual({ found: true, dest: '/en', continue: true, status: undefined, headers: {}, uri_args: new URLSearchParams(), matched_route: routesConfig[0], matched_route_idx: 0, userDest: true, isDestUrl: false, phase: undefined, target: undefined, }); }); test('I18n default locale', async () => { const mockedFetch = jest .fn() .mockImplementation(() => generateMockedFetchResponse(404, {}, { etag: '"notfound"' }) ); const routesConfig = [ { src: '^/(?!(?:_next/.*|en|fr\\-FR|nl)(?:/.*|$))(.*)$', dest: '$wildcard/$1', continue: true, }, { src: '/', locale: { redirect: { en: '/', 'fr-FR': '/fr-FR', nl: '/nl', }, cookie: 'NEXT_LOCALE', }, continue: true, }, { src: '^/$', dest: '/en', continue: true, }, ] as Route[]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, {}, 'http://localhost', '/' ); expect(result).toEqual({ found: true, dest: '/en', continue: true, status: undefined, headers: {}, uri_args: new URLSearchParams(''), matched_route: routesConfig[2], matched_route_idx: 2, userDest: true, isDestUrl: false, phase: undefined, target: undefined, }); }); test('Static index route', async () => { const mockedFetch = jest.fn().mockImplementation((url: string) => { if ( url === `http://localhost/filesystem/123/${encodeURIComponent('index')}` ) { return generateMockedFetchResponse(200, {}, { etag: '"found"' }); } return generateMockedFetchResponse(404, {}, { etag: '"notfound"' }); }); const routesConfig = [ { handle: 'filesystem' as const, }, ]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, {}, 'http://localhost', '/' ); expect(result).toEqual({ found: true, dest: '/index', target: 'filesystem', continue: false, status: undefined, headers: {}, isDestUrl: false, phase: 'filesystem', }); }); test('Multiple dynamic parts', async () => { const mockedFetch = jest.fn().mockImplementation((url: string) => { if ( url === `http://localhost/filesystem/123/${encodeURIComponent( '[teamSlug]/[project]/[id]' )}` ) { return generateMockedFetchResponse(200, {}, { etag: '"found"' }); } return generateMockedFetchResponse(404, {}, { etag: '"notfound"' }); }); const routesConfig: Route[] = [ { handle: 'filesystem', }, { handle: 'rewrite', }, { // Original path of the page: /pages/[teamSlug]/[project]/[id].js src: '^/(?<teamSlug>[^/]+?)/(?<project>[^/]+?)/(?<id>[^/]+?)(?:/)?$', dest: '/[teamSlug]/[project]/[id]?teamSlug=$teamSlug&project=$project&id=$id', check: true, }, { handle: 'hit', }, ]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, {}, 'http://localhost', '/another/invite/hello' ); expect(result).toEqual({ found: true, dest: '/[teamSlug]/[project]/[id]', target: 'filesystem', continue: false, status: undefined, headers: {}, isDestUrl: false, phase: 'rewrite', }); }); test('Dynamic static route', async () => { const mockedFetch = jest.fn().mockImplementation((url: string) => { if ( url === `http://localhost/filesystem/123/${encodeURIComponent( 'users/[user_id]' )}` ) { return generateMockedFetchResponse(200, {}, { etag: '"found"' }); } return generateMockedFetchResponse(404, {}, { etag: '"notfound"' }); }); const routesConfig: Route[] = [ { handle: 'rewrite', }, { src: '^/users/(?<user_id>[^/]+?)(?:/)?$', dest: '/users/[user_id]?user_id=$user_id', check: true, }, { handle: 'hit', }, ]; const result = await new Proxy(mockedFetch as any).route( '123', routesConfig, {}, 'http://localhost', '/users/123' ); expect(result).toEqual({ found: true, dest: '/users/[user_id]', target: 'filesystem', continue: false, status: undefined, headers: {}, isDestUrl: false, phase: 'rewrite', }); }); });
the_stack
import { assert } from "chai"; import { suite, test } from "mocha-typescript"; import { outdent } from "outdent"; import { BlockCompiler, BlockDefinitionCompiler, INLINE_DEFINITION_FILE } from "../../src"; import { REGEXP_COMMENT_DEFINITION_REF } from "../../src/PrecompiledDefinitions"; import { setupImporting } from "../util/setupImporting"; @suite("Acceptance Test - Definition Files Full Workflow") export class AcceptanceTestDefinitionFilesFullWorkflow { @test async "Process basic CSS Blocks source file and parse from definition file, using mock importer"() { // Setup our infrastructure... we need an importer, compiler, and parser ready to go. let { imports, config, factory, postcss } = setupImporting(); const blockDfnCompiler = new BlockDefinitionCompiler(postcss, (_b, p) => p.replace(".block", ""), config); const compiler = new BlockCompiler(postcss, config); compiler.setDefinitionCompiler(blockDfnCompiler); imports.registerSource( "/foo/bar/other.block.css", `:scope { color: red; }`, ); // Part 1: Given a basic CSS Blocks source file, generate a definition file. imports.registerSource( "/foo/bar/source.block.css", outdent` @block (default as other) from './other.block.css'; @export (other); :scope { background-color: #FFF; } :scope[toggled] { color: #000; } :scope[foo="bar"] { border-top-color: #F00; } .item { width: 100px; } .item[toggled] { height: 100px; } .item[foo="bar"] { min-width: 100px; } .item + .item { border-left-color: #F00; } :scope[toggled] .item { border-right-color: #F00; } :scope[toggled] .item[foo="bar"] { border-bottom-color: #F00; } `, ); const originalBlock = await factory.getBlockFromPath("/foo/bar/source.block.css"); const { css: cssTree, definition: definitionTree } = compiler.compileWithDefinition(originalBlock, originalBlock.stylesheet!, new Set(), "/foo/bar/source.block.d.css"); const compiledCss = cssTree.toString(); const definition = definitionTree.toString(); // Test that the compiled content that we just generated is as expected. assert.equal( outdent` ${compiledCss} `, outdent` /*#css-blocks ${originalBlock.guid}*/ .source { background-color: #FFF; } .source--toggled { color: #000; } .source--foo-bar { border-top-color: #F00; } .source__item { width: 100px; } .source__item--toggled { height: 100px; } .source__item--foo-bar { min-width: 100px; } .source__item + .source__item { border-left-color: #F00; } .source--toggled .source__item { border-right-color: #F00; } .source--toggled .source__item--foo-bar { border-bottom-color: #F00; } /*#blockDefinitionURL=/foo/bar/source.block.d.css*/ /*#css-blocks end*/ `, "Compiled CSS contents match expected output", ); assert.equal( outdent` ${definition} `, outdent` @block-syntax-version 1; @block other from "./other.css"; @export (other); :scope { block-id: "${originalBlock.guid}"; block-name: "source"; block-class: source } :scope[toggled] { block-class: source--toggled } :scope[foo="bar"] { block-class: source--foo-bar } .item { block-class: source__item } .item[toggled] { block-class: source__item--toggled } .item[foo="bar"] { block-class: source__item--foo-bar } `, "Compiled definition contents match expected output", ); // Part 2: Reset the importer and factory instances and try importing // the compiled css and definition data we just created. imports.reset(); factory.reset(); imports.registerSource( "/foo/bar/other.css", `:scope { color: red; }`, ); imports.registerCompiledCssSource( "/foo/bar/source.css", compiledCss, "/foo/bar/source.block.d.css", definition, ); await factory.getBlockFromPath("/foo/bar/other.css"); const reconstitutedBlock = await factory.getBlockFromPath("/foo/bar/source.css"); // And now some checks to validate that we were able to reconstitute accurately. assert.equal(reconstitutedBlock.guid, originalBlock.guid, "GUIDs of original and reconstituted blocks match"); assert.equal(reconstitutedBlock.name, originalBlock.name, "Names of original and reconstituted blocks match"); const expectedProperties = { "source": { "::self": [ "background-color", ], }, "source--toggled": { "::self": [ "color", ], }, "source--foo-bar": { "::self": [ "border-top-color", ], }, "source__item": { "::self": [ "width", "border-left-color", "border-right-color", ], }, "source__item--toggled": { "::self": [ "height", ], }, "source__item--foo-bar": { "::self": [ "min-width", "border-bottom-color", ], }, }; const expectedFoundClasses = Object.keys(expectedProperties); const foundClasses = reconstitutedBlock.presetClassesMap(true); assert.deepEqual( Object.keys(foundClasses), expectedFoundClasses, "Class nodes on reconstituted block matches expected list of classes", ); expectedFoundClasses.forEach(expectedClass => { Object.keys(expectedProperties[expectedClass]).forEach(psuedo => { assert.deepEqual( [...foundClasses[expectedClass].rulesets.getProperties(psuedo)].sort(), expectedProperties[expectedClass][psuedo].sort(), `Properties on reconstituted class node ${expectedClass}${psuedo} match expected list`, ); }); }); } @test async "Process basic CSS Blocks source file and parse from embedded definitions, using mock importer"() { // Setup our infrastructure... we need an importer, compiler, and parser ready to go. let { imports, config, factory, postcss } = setupImporting(); const blockDfnCompiler = new BlockDefinitionCompiler(postcss, (_b, p) => p.replace(".block", ""), config); const compiler = new BlockCompiler(postcss, config); compiler.setDefinitionCompiler(blockDfnCompiler); // Part 1: Given a basic CSS Blocks source file, generate a definition file. imports.registerSource( "/foo/bar/source.block.css", outdent` :scope { background-color: #FFF; } :scope[toggled] { color: #000; } :scope[foo="bar"] { border-top-color: #F00; } .item { width: 100px; } .item[toggled] { height: 100px; } .item[foo="bar"] { min-width: 100px; } .item + .item { border-left-color: #F00; } :scope[toggled] .item { border-right-color: #F00; } :scope[toggled] .item[foo="bar"] { border-bottom-color: #F00; } `, ); const originalBlock = await factory.getBlockFromPath("/foo/bar/source.block.css"); const { css: cssTree } = compiler.compileWithDefinition(originalBlock, originalBlock.stylesheet!, new Set(), INLINE_DEFINITION_FILE); const compiledCss = cssTree.toString(); // Test that the compiled content that we just generated is as expected. // Because the GUID isn't fixed, and a part of the base64 encoded blob, we'll // need to remove it from the tested output and validate it separately. const embeddedDfnRegexResult = REGEXP_COMMENT_DEFINITION_REF.exec(compiledCss); if (!embeddedDfnRegexResult) { assert.fail(false, true, "Expected to find embedded definition data"); return; // This isn't necessary, but TypeScript doesn't recognize that assert.fail() always throws. } const compiledCssNoDfn = compiledCss.replace(embeddedDfnRegexResult[0], ""); assert.equal( outdent` ${compiledCssNoDfn} `, outdent` /*#css-blocks ${originalBlock.guid}*/ .source { background-color: #FFF; } .source--toggled { color: #000; } .source--foo-bar { border-top-color: #F00; } .source__item { width: 100px; } .source__item--toggled { height: 100px; } .source__item--foo-bar { min-width: 100px; } .source__item + .source__item { border-left-color: #F00; } .source--toggled .source__item { border-right-color: #F00; } .source--toggled .source__item--foo-bar { border-bottom-color: #F00; } /*#css-blocks end*/ `, "Compiled CSS contents match expected output", ); assert.equal( outdent` ${Buffer.from(embeddedDfnRegexResult[1].split(",")[1], "base64").toString("utf-8")} `, outdent` @block-syntax-version 1; :scope { block-id: "${originalBlock.guid}"; block-name: "source"; block-class: source } :scope[toggled] { block-class: source--toggled } :scope[foo="bar"] { block-class: source--foo-bar } .item { block-class: source__item } .item[toggled] { block-class: source__item--toggled } .item[foo="bar"] { block-class: source__item--foo-bar } `, "Unencoded definition data matches expected output", ); // Part 2: Reset the importer and factory instances and try importing // the compiled css and definition data we just created. imports.reset(); factory.reset(); imports.registerSource( "/foo/bar/source.css", compiledCss, undefined, true, ); const reconstitutedBlock = await factory.getBlockFromPath("/foo/bar/source.css"); // And now some checks to validate that we were able to reconstitute accurately. assert.equal(reconstitutedBlock.guid, originalBlock.guid, "GUIDs of original and reconstituted blocks match"); assert.equal(reconstitutedBlock.name, originalBlock.name, "Names of original and reconstituted blocks match"); const expectedProperties = { "source": { "::self": [ "background-color", ], }, "source--toggled": { "::self": [ "color", ], }, "source--foo-bar": { "::self": [ "border-top-color", ], }, "source__item": { "::self": [ "width", "border-left-color", "border-right-color", ], }, "source__item--toggled": { "::self": [ "height", ], }, "source__item--foo-bar": { "::self": [ "min-width", "border-bottom-color", ], }, }; const expectedFoundClasses = Object.keys(expectedProperties); const foundClasses = reconstitutedBlock.presetClassesMap(true); assert.deepEqual( Object.keys(foundClasses), expectedFoundClasses, "Class nodes on reconstituted block matches expected list of classes", ); expectedFoundClasses.forEach(expectedClass => { Object.keys(expectedProperties[expectedClass]).forEach(psuedo => { assert.deepEqual( [...foundClasses[expectedClass].rulesets.getProperties(psuedo)].sort(), expectedProperties[expectedClass][psuedo].sort(), `Properties on reconstituted class node ${expectedClass}${psuedo} match expected list`, ); }); }); } }
the_stack
import { SpecPage } from '@stencil/core/testing'; import { flushTransitions, parseTransform, asyncForEach } from './unit-test-utils'; export const wrapLabel_applied_default = { prop: 'wrapLabel', group: 'axes', name: 'wrap label should be applied by default on load', testProps: {}, testSelector: '[data-testid=x-axis] [data-testid=axis-tick-text]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE component.width = 500; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const xAxisTicksText = page.doc.querySelectorAll(testSelector); await asyncForEach(xAxisTicksText, async text => { flushTransitions(text); await page.waitForChanges(); const textTspans = text.querySelectorAll('[data-testid=axis-tick-text-tspan]'); expect(textTspans.length).toBeGreaterThanOrEqual(1); }); } }; export const wrapLabel_false_on_load = { prop: 'wrapLabel', group: 'axes', name: 'wrap label should be disabled when passed on load', testProps: {}, testSelector: '[data-testid=x-axis] [data-testid=axis-tick-text]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE component.width = 500; component.wrapLabel = false; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const xAxisTicksText = page.doc.querySelectorAll(testSelector); await asyncForEach(xAxisTicksText, async text => { flushTransitions(text); await page.waitForChanges(); const textTspans = text.querySelectorAll('[data-testid=axis-tick-text-tspan]'); expect(textTspans.length).toEqual(0); }); } }; export const wrapLabel_false_on_update = { prop: 'wrapLabel', group: 'axes', name: 'wrap label should be disabled when passed on update', testProps: {}, testSelector: '[data-testid=x-axis] [data-testid=axis-tick-text]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE component.width = 500; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.wrapLabel = false; await page.waitForChanges(); // ASSERT const xAxisTicksText = page.doc.querySelectorAll(testSelector); await asyncForEach(xAxisTicksText, async text => { flushTransitions(text); await page.waitForChanges(); const textTspans = text.querySelectorAll('[data-testid=axis-tick-text-tspan]'); expect(textTspans.length).toEqual(0); }); } }; export const xaxis_visible_default = { prop: 'xAxis.visible', group: 'axes', name: 'axis should be visible by default', testProps: {}, testSelector: '[data-testid=x-axis]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const xAxis = page.doc.querySelector(testSelector); flushTransitions(xAxis); await page.waitForChanges(); expect(xAxis).toEqualAttribute('opacity', 1); } }; export const yaxis_visible_default = { prop: 'yAxis.visible', group: 'axes', name: 'axis should be visible by default', testProps: {}, testSelector: '[data-testid=y-axis]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const yAxis = page.doc.querySelector(testSelector); flushTransitions(yAxis); await page.waitForChanges(); expect(yAxis).toEqualAttribute('opacity', 1); } }; export const xaxis_visible_false_load = { prop: 'xAxis.visible', group: 'axes', name: 'axis should not be visible when passed on load', testProps: {}, testSelector: '[data-testid=x-axis]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE component.xAxis = { visible: false }; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const xAxis = page.doc.querySelector(testSelector); flushTransitions(xAxis); await page.waitForChanges(); expect(xAxis).toEqualAttribute('opacity', 0); } }; export const yaxis_visible_false_load = { prop: 'yAxis.visible', group: 'axes', name: 'axis should not be visible when passed on load', testProps: {}, testSelector: '[data-testid=y-axis]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE component.yAxis = { visible: false }; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const yAxis = page.doc.querySelector(testSelector); flushTransitions(yAxis); await page.waitForChanges(); expect(yAxis).toEqualAttribute('opacity', 0); } }; export const xaxis_visible_false_update = { prop: 'xAxis.visible', group: 'axes', name: 'axis should not be visible when passed on update', testProps: {}, testSelector: '[data-testid=x-axis]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.xAxis = { visible: false }; await page.waitForChanges(); // ASSERT const xAxis = page.doc.querySelector(testSelector); flushTransitions(xAxis); await page.waitForChanges(); expect(xAxis).toEqualAttribute('opacity', 0); } }; export const yaxis_visible_false_update = { prop: 'yAxis.visible', group: 'axes', name: 'axis should not be visible when passed on update', testProps: {}, testSelector: '[data-testid=y-axis]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.yAxis = { visible: false }; await page.waitForChanges(); // ASSERT const yAxis = page.doc.querySelector(testSelector); flushTransitions(yAxis); await page.waitForChanges(); expect(yAxis).toEqualAttribute('opacity', 0); } }; export const xaxis_grid_visible_default = { prop: 'xAxis.gridVisible', group: 'axes', name: 'axis gridlines should not be visible by default', testProps: {}, testSelector: '[data-testid=grid-bottom]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const gridBottom = page.doc.querySelector(testSelector); flushTransitions(gridBottom); await page.waitForChanges(); expect(gridBottom).toEqualAttribute('opacity', 0); } }; export const yaxis_grid_visible_default = { prop: 'yAxis.gridVisible', group: 'axes', name: 'axis gridlines should be visible by default', testProps: {}, testSelector: '[data-testid=grid-left]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const gridLeft = page.doc.querySelector(testSelector); flushTransitions(gridLeft); await page.waitForChanges(); expect(gridLeft).toEqualAttribute('opacity', 1); } }; export const xaxis_grid_visible_load = { prop: 'xAxis.gridVisible', group: 'axes', name: 'axis gridlines should be visible on load', testProps: {}, testSelector: '[data-testid=grid-bottom]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE component.xAxis = { visible: true, gridVisible: true, label: 'x axis', unit: 'month', format: '%b %y', tickInterval: 1 }; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const gridBottom = page.doc.querySelector(testSelector); flushTransitions(gridBottom); await page.waitForChanges(); expect(gridBottom).toEqualAttribute('opacity', 1); } }; export const yaxis_grid_visible_load = { prop: 'yAxis.gridVisible', group: 'axes', name: 'axis gridlines should not be visible on load', testProps: {}, testSelector: '[data-testid=grid-left]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE component.yAxis = { visible: true, gridVisible: false, label: 'Y Axis', format: '0[.][0][0]a', tickInterval: 1 }; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const gridLeft = page.doc.querySelector(testSelector); flushTransitions(gridLeft); await page.waitForChanges(); expect(gridLeft).toEqualAttribute('opacity', 0); } }; export const xaxis_grid_visible_update = { prop: 'xAxis.gridVisible', group: 'axes', name: 'axis gridlines should be visible on update', testProps: {}, testSelector: '[data-testid=grid-bottom]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.xAxis = { visible: true, gridVisible: true, label: 'x axis', unit: 'month', format: '%b %y', tickInterval: 1 }; await page.waitForChanges(); // ASSERT const gridBottom = page.doc.querySelector(testSelector); flushTransitions(gridBottom); await page.waitForChanges(); expect(gridBottom).toEqualAttribute('opacity', 1); } }; export const yaxis_grid_visible_update = { prop: 'yAxis.gridVisible', group: 'axes', name: 'axis gridlines should not be visible on update', testProps: {}, testSelector: '[data-testid=grid-left]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.yAxis = { visible: true, gridVisible: false, label: 'Y Axis', format: '0[.][0][0]a', tickInterval: 1 }; await page.waitForChanges(); // ASSERT const gridLeft = page.doc.querySelector(testSelector); flushTransitions(gridLeft); await page.waitForChanges(); expect(gridLeft).toEqualAttribute('opacity', 0); } }; export const xaxis_label_default = { prop: 'xAxis.label', group: 'axes', name: 'axis label should be X Axis by default', testProps: {}, testSelector: '[data-testid=x-axis-label]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const xAxisLabel = page.doc.querySelector(testSelector); expect(xAxisLabel).toEqualText('X Axis'); } }; export const yaxis_label_default = { prop: 'yAxis.label', group: 'axes', name: 'axis label should be Y Axis by default', testProps: {}, testSelector: '[data-testid=y-axis-label]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const yAxisLabel = page.doc.querySelector(testSelector); expect(yAxisLabel).toEqualText('Y Axis'); } }; export const xaxis_label_load = { prop: 'xAxis.label', group: 'axes', name: 'axis label should be passed on load', testProps: {}, testSelector: '[data-testid=x-axis-label]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE component.xAxis = { visible: true, gridVisible: true, label: 'Cats and Dogs', unit: 'month', format: '%b %y', tickInterval: 1 }; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const xAxisLabel = page.doc.querySelector(testSelector); expect(xAxisLabel).toEqualText('Cats and Dogs'); } }; export const yaxis_label_load = { prop: 'yAxis.label', group: 'axes', name: 'axis label should be passed on load', testProps: {}, testSelector: '[data-testid=y-axis-label]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE component.yAxis = { visible: true, gridVisible: false, label: 'Cats and Dogs', format: '0[.][0][0]a', tickInterval: 1 }; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const yAxisLabel = page.doc.querySelector(testSelector); expect(yAxisLabel).toEqualText('Cats and Dogs'); } }; export const xaxis_label_update = { prop: 'xAxis.label', group: 'axes', name: 'axis label should be passed on update', testProps: {}, testSelector: '[data-testid=x-axis-label]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.xAxis = { visible: true, gridVisible: true, label: 'Cats and Dogs', unit: 'month', format: '%b %y', tickInterval: 1 }; await page.waitForChanges(); // ASSERT const xAxisLabel = page.doc.querySelector(testSelector); expect(xAxisLabel).toEqualText('Cats and Dogs'); } }; export const yaxis_label_update = { prop: 'yAxis.label', group: 'axes', name: 'axis label should be passed on update', testProps: {}, testSelector: '[data-testid=y-axis-label]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.yAxis = { visible: true, gridVisible: false, label: 'Cats and Dogs', format: '0[.][0][0]a', tickInterval: 1 }; await page.waitForChanges(); // ASSERT const yAxisLabel = page.doc.querySelector(testSelector); expect(yAxisLabel).toEqualText('Cats and Dogs'); } }; export const xaxis_format_default = { prop: 'xAxis.format', group: 'axes', name: 'axis date format should be %b %y by default', testProps: {}, testSelector: '[data-testid=x-axis] [data-testid=axis-tick-text]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE const EXPECTEDTICKS = expectedOutput || [ 'Jan 16', 'Feb 16', 'Mar 16', 'Apr 16', 'May 16', 'Jun 16', 'Jul 16', 'Aug 16', 'Sep 16', 'Oct 16', 'Nov 16', 'Dec 16' ]; component.wrapLabel = false; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const xAxisTicks = page.doc.querySelectorAll(testSelector); xAxisTicks.forEach((tick, i) => { expect(tick).toEqualText(EXPECTEDTICKS[i]); }); } }; export const yaxis_format_default = { prop: 'yAxis.format', group: 'axes', name: 'axis number format should be 0[.][0][0]a by default', testProps: {}, testSelector: '[data-testid=y-axis] [data-testid=axis-tick-text]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE const EXPECTEDTICKS = expectedOutput || ['3b', '4b', '5b', '6b', '7b', '8b', '9b', '10b']; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const yAxisTicks = page.doc.querySelectorAll(testSelector); yAxisTicks.forEach((tick, i) => { expect(tick).toEqualText(EXPECTEDTICKS[i]); }); } }; export const xaxis_format_load = { prop: 'xAxis.format', group: 'axes', name: 'axis date format should be %b %Y when passed on load', testProps: {}, testSelector: '[data-testid=x-axis] [data-testid=axis-tick-text]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE const EXPECTEDTICKS = expectedOutput || [ 'Jan 2016', 'Feb 2016', 'Mar 2016', 'Apr 2016', 'May 2016', 'Jun 2016', 'Jul 2016', 'Aug 2016', 'Sep 2016', 'Oct 2016', 'Nov 2016', 'Dec 2016' ]; component.xAxis = { visible: true, gridVisible: true, label: 'Cats and Dogs', unit: 'month', format: '%b %Y', tickInterval: 1 }; component.wrapLabel = false; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const xAxisTicks = page.doc.querySelectorAll(testSelector); xAxisTicks.forEach((tick, i) => { expect(tick).toEqualText(EXPECTEDTICKS[i]); }); } }; export const yaxis_format_load = { prop: 'yAxis.format', group: 'axes', name: 'axis number format should be $0[.][0]a when passed on load', testProps: {}, testSelector: '[data-testid=y-axis] [data-testid=axis-tick-text]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE component.yAxis = { visible: true, gridVisible: false, label: 'Cats and Dogs', format: '$0[.][0]a', tickInterval: 1 }; const EXPECTEDTICKS = expectedOutput || ['$3b', '$4b', '$5b', '$6b', '$7b', '$8b', '$9b', '$10b']; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const yAxisTicks = page.doc.querySelectorAll(testSelector); yAxisTicks.forEach((tick, i) => { expect(tick).toEqualText(EXPECTEDTICKS[i]); }); } }; export const xaxis_format_update = { prop: 'xAxis.format', group: 'axes', name: 'axis date format should be %b %Y when passed on update', testProps: {}, testSelector: '[data-testid=x-axis] [data-testid=axis-tick-text]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE const EXPECTEDTICKS = expectedOutput || [ 'Jan 2016', 'Feb 2016', 'Mar 2016', 'Apr 2016', 'May 2016', 'Jun 2016', 'Jul 2016', 'Aug 2016', 'Sep 2016', 'Oct 2016', 'Nov 2016', 'Dec 2016' ]; component.wrapLabel = false; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.xAxis = { visible: true, gridVisible: true, label: 'Cats and Dogs', unit: 'month', format: '%b %Y', tickInterval: 1 }; await page.waitForChanges(); // ASSERT const xAxisTicks = page.doc.querySelectorAll(testSelector); xAxisTicks.forEach((tick, i) => { expect(tick).toEqualText(EXPECTEDTICKS[i]); }); } }; export const yaxis_format_update = { prop: 'yAxis.format', group: 'axes', name: 'axis number format should be $0[.][0]a when passed on update', testProps: {}, testSelector: '[data-testid=y-axis] [data-testid=axis-tick-text]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE const EXPECTEDTICKS = expectedOutput || ['$3b', '$4b', '$5b', '$6b', '$7b', '$8b', '$9b', '$10b']; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.yAxis = { visible: true, gridVisible: false, label: 'Cats and Dogs', format: '$0[.][0]a', tickInterval: 1 }; await page.waitForChanges(); // ASSERT const yAxisTicks = page.doc.querySelectorAll(testSelector); yAxisTicks.forEach((tick, i) => { expect(tick).toEqualText(EXPECTEDTICKS[i]); }); } }; export const xaxis_tickInterval_load = { prop: 'xAxis.tickInterval', group: 'axes', name: 'axis tick interval should be 2 when passed on load', testProps: {}, testSelector: '[data-testid=x-axis] [data-testid=axis-tick-text]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE const EXPECTEDTICKS = expectedOutput || [ 'Jan 2016', 'Feb 2016', 'Mar 2016', 'Apr 2016', 'May 2016', 'Jun 2016', 'Jul 2016', 'Aug 2016', 'Sep 2016', 'Oct 2016', 'Nov 2016', 'Dec 2016' ]; component.xAxis = { visible: true, gridVisible: true, label: 'Cats and Dogs', unit: 'month', format: '%b %Y', tickInterval: 2 }; component.wrapLabel = false; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const xAxisTicks = page.doc.querySelectorAll(testSelector); xAxisTicks.forEach((tick, i) => { expect(tick).toEqualText(i % 2 === 0 ? EXPECTEDTICKS[i] : ''); }); } }; export const yaxis_tickInterval_load = { prop: 'yAxis.tickInterval', group: 'axes', name: 'axis tick interval should be 2 when passed on load', testProps: {}, testSelector: '[data-testid=y-axis] [data-testid=axis-tick-text]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE component.yAxis = { visible: true, gridVisible: false, label: 'Cats and Dogs', format: '$0[.][0]a', tickInterval: 2 }; const EXPECTEDTICKS = expectedOutput || ['$3b', '$4b', '$5b', '$6b', '$7b', '$8b', '$9b', '$10b']; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const yAxisTicks = page.doc.querySelectorAll(testSelector); yAxisTicks.forEach((tick, i) => { expect(tick).toEqualText(i % 2 === 0 ? EXPECTEDTICKS[i] : ''); }); } }; export const xaxis_tickInterval_update = { prop: 'xAxis.tickInterval', group: 'axes', name: 'axis tick interval should be 2 when passed on load', testProps: {}, testSelector: '[data-testid=x-axis] [data-testid=axis-tick-text]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE const EXPECTEDTICKS = expectedOutput || [ 'Jan 2016', 'Feb 2016', 'Mar 2016', 'Apr 2016', 'May 2016', 'Jun 2016', 'Jul 2016', 'Aug 2016', 'Sep 2016', 'Oct 2016', 'Nov 2016', 'Dec 2016' ]; component.wrapLabel = false; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.xAxis = { visible: true, gridVisible: true, label: 'Cats and Dogs', unit: 'month', format: '%b %Y', tickInterval: 2 }; await page.waitForChanges(); // ASSERT const xAxisTicks = page.doc.querySelectorAll(testSelector); xAxisTicks.forEach((tick, i) => { expect(tick).toEqualText(i % 2 === 0 ? EXPECTEDTICKS[i] : ''); }); } }; export const yaxis_tickInterval_update = { prop: 'yAxis.tickInterval', group: 'axes', name: 'axis tick interval should be 2 when passed on update', testProps: {}, testSelector: '[data-testid=y-axis] [data-testid=axis-tick-text]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE const EXPECTEDTICKS = expectedOutput || ['$3b', '$4b', '$5b', '$6b', '$7b', '$8b', '$9b', '$10b']; // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.yAxis = { visible: true, gridVisible: false, label: 'Cats and Dogs', format: '$0[.][0]a', tickInterval: 2 }; await page.waitForChanges(); // ASSERT const yAxisTicks = page.doc.querySelectorAll(testSelector); yAxisTicks.forEach((tick, i) => { expect(tick).toEqualText(i % 2 === 0 ? EXPECTEDTICKS[i] : ''); }); } }; export const xaxis_unit_load = { prop: 'xAxis.unit', group: 'axes', name: 'axis date format should be unit millisecond when passed on load', testProps: {}, testSelector: '[data-testid=x-axis] [data-testid=axis-tick]', testFunc: async (component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any) => { // ARRANGE component.xAxis = { visible: true, gridVisible: true, label: 'Cats and Dogs', unit: 'millisecond', format: '%b %Y', tickInterval: 1 }; component.wrapLabel = false; // if we have any testProps apply them // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const xAxisTick = page.doc.querySelector(testSelector); flushTransitions(xAxisTick); await page.waitForChanges(); const transformData = parseTransform(xAxisTick.getAttribute('transform')); expect(parseFloat(transformData['translate'][0])).toBeLessThan(2); } }; /* CANNOT TEST TRANSFORM ATTRIBUTE ON UPDATE DUE TO JSDOM LIMITATIONS export const xaxis_unit_update = { prop: 'xAxis.unit', group: 'axes', name: 'axis date format should be unit millisecond when passed on update', testProps: {}, testSelector: "[data-testid=x-axis] [data-testid=axis-tick]", testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, expectedOutput: any ) => { // ARRANGE component.wrapLabel = false; // if we have any testProps apply them // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.xAxis = { visible: true, gridVisible: true, label: "Cats and Dogs", unit: "millisecond", format: "%b %Y", tickInterval: 1 } await page.waitForChanges(); // ASSERT const xAxisTick = page.doc.querySelector(testSelector); flushTransitions(xAxisTick); await page.waitForChanges(); const transformData = parseTransform(xAxisTick.getAttribute('transform')); expect(parseFloat(transformData['translate'][0])).toBeLessThan(2); } }; */
the_stack
import { getRandomBytes } from '@liskhq/lisk-cryptography'; import { sortByBitmapAndKey, binaryStringToBuffer, bufferToBinaryString, areSiblingQueries, filterQueries, calculateRoot, getOverlappingStr, verify, leafData, isLeaf, branchData, parseBranchData, parseLeafData, binaryExpansion, } from '../../src/sparse_merkle_tree/utils'; const binarySampleData = [ { str: '101', buf: '05' }, { str: '11111111', buf: 'FF' }, { str: '11111111', buf: 'FF' }, { str: '100000000', buf: '0100' }, { str: '10101001101100', buf: '2A6C' }, { str: '1111110010101001101100', buf: '3F2A6C' }, ]; const createQueryObject = ({ key, value, bitmap, }: { key: string; value: string; bitmap: string; }) => ({ key: Buffer.from(key, 'hex'), value: Buffer.from(value, 'hex'), bitmap: Buffer.from(bitmap, 'hex'), binaryBitmap: bufferToBinaryString(Buffer.from(bitmap, 'hex')), }); describe('utils', () => { describe('sortByBitmapAndKey', () => { it('should sort by longest bitmap', () => { const res1 = { key: getRandomBytes(2), binaryBitmap: '011', }; const res2 = { key: getRandomBytes(2), binaryBitmap: '0011', }; expect(sortByBitmapAndKey([res1, res2])).toEqual([res2, res1]); }); it('should sort by longest bitmap breaking tie with smaller key', () => { const res1 = { key: getRandomBytes(2), binaryBitmap: '111', }; const res2 = { key: getRandomBytes(1), binaryBitmap: '111', }; expect(sortByBitmapAndKey([res1, res2])).toEqual([res2, res1]); }); }); describe('areSiblingQueries', () => { it('should return true for valid sibling queries', () => { // These values are generate from inclusion proof tree diagram for keys "11101101" and "11100001" expect( areSiblingQueries( createQueryObject({ key: 'ed', value: 'f3df1f9c', bitmap: '17' }), createQueryObject({ key: 'e1', value: 'f031efa5', bitmap: '17' }), 1, ), ).toBeTrue(); }); it('should return true for valid sibling queries even if swapped', () => { // These values are generate from inclusion proof tree diagram for keys "11101101" and "11100001" expect( areSiblingQueries( createQueryObject({ key: 'e1', value: 'f031efa5', bitmap: '17' }), createQueryObject({ key: 'ed', value: 'f3df1f9c', bitmap: '17' }), 1, ), ).toBeTrue(); }); it('should return false for invalid sibling queries', () => { // These values are generate from inclusion proof tree diagram for keys "00110011" and "01101100" expect( areSiblingQueries( createQueryObject({ key: '33', value: '4e074085', bitmap: '17' }), createQueryObject({ key: '6c', value: 'acac86c0', bitmap: '1f' }), 1, ), ).toBeFalse(); }); it('should return false for invalid sibling queries even if swapped', () => { // These values are generate from inclusion proof tree diagram for keys "00110011" and "01101100" expect( areSiblingQueries( createQueryObject({ key: '6c', value: 'acac86c0', bitmap: '1f' }), createQueryObject({ key: '33', value: '4e074085', bitmap: '17' }), 1, ), ).toBeFalse(); }); }); describe('filterQueries', () => { it('should remove queries which are merged together', () => { // These values are generate from inclusion proof tree diagram // for keys "01111110", "01110110", "01110111", "01011010" const q1 = createQueryObject({ key: '7e', value: '7ace431c', bitmap: '1f' }); const q2 = createQueryObject({ key: '76', value: '4c94485e', bitmap: '1f' }); const q3 = createQueryObject({ key: '76', value: '4c94485e', bitmap: '1f' }); const q4 = createQueryObject({ key: '5a', value: 'bbeebd87', bitmap: '07' }); expect(filterQueries([q1, q2, q3, q4], 1)).toEqual([q1, q2, q4]); }); }); describe('calculateRoot', () => { it('should calculate correct root hash for single proof', () => { const siblingHashes = [ 'e6fa536eaac055d524e29fb4682893e3111bf3a027f7cd5ba312aec56460eb1b', '63a154f88e6f5898bada58cbcb0dfcfa84e18cd5d50783e6703d904bef8be36b', 'da7f3bd33f419f025fc34ada50e26bc0094a7f0018f91fa7e51b66c88c6a7e78', 'ed9b2d408363d6edec46b055de68e67b37091f5b7dece4415200082ba01bc73e', ].map(h => Buffer.from(h, 'hex')); const queries = [ createQueryObject({ key: 'e1', value: 'f031efa58744e97a34555ca98621d4e8a52ceb5f20b891d5c44ccae0daaaa644', bitmap: '17', }), ]; const rootHash = '21ecda9db382eff32c9ec899fc7090cf58858e8c22a2af82510cd4d9c9a42c2f'; expect(calculateRoot(siblingHashes, queries, 1).toString('hex')).toEqual(rootHash); }); it('should calculate correct root hash for multi proof', () => { const siblingHashes = [ 'b2157891142f7416efc259560b181fcbb52d95abe326409f55754b7f453455b4', 'c5368d8ea5128f897a723662ea8ca092ee30029175f193e9fe37d3e7f6641264', 'e6fa536eaac055d524e29fb4682893e3111bf3a027f7cd5ba312aec56460eb1b', 'ecb4e7940250348fcbd38c3eb7982ce7d0a748fd832f48a0154b4ff7ded6fe04', '63a154f88e6f5898bada58cbcb0dfcfa84e18cd5d50783e6703d904bef8be36b', '99b0161609748a131c16d46c72ff79ffbfa85e9e2694c52ee665635c4d48ecae', 'da7f3bd33f419f025fc34ada50e26bc0094a7f0018f91fa7e51b66c88c6a7e78', ].map(h => Buffer.from(h, 'hex')); const queries = [ createQueryObject({ key: 'e1', value: 'f031efa58744e97a34555ca98621d4e8a52ceb5f20b891d5c44ccae0daaaa644', bitmap: '17', }), createQueryObject({ key: '60', value: '8d33f520a3c4cef80d2453aef81b612bfe1cb44c8b2025630ad38662763f13d3', bitmap: '1f', }), createQueryObject({ key: '7e', value: '7ace431cb61584cb9b8dc7ec08cf38ac0a2d649660be86d349fb43108b542fa4', bitmap: '1f', }), ]; const rootHash = '21ecda9db382eff32c9ec899fc7090cf58858e8c22a2af82510cd4d9c9a42c2f'; expect(calculateRoot(siblingHashes, queries, 1).toString('hex')).toEqual(rootHash); }); it('should calculate correct root hash for single proof of exclusion', () => { const siblingHashes = [ 'c4d5a0ec88593441501521e1217be34f8875d1a2f8d2d882f6a411debaa7467e', '508e7ce32a2dfb6c39123ad6daaea8dde3bbcb096dd255bea05bea9b717898c3', 'ecb4e7940250348fcbd38c3eb7982ce7d0a748fd832f48a0154b4ff7ded6fe04', '99b0161609748a131c16d46c72ff79ffbfa85e9e2694c52ee665635c4d48ecae', '7ef9d01187c522f5d7198874a28cdb495abefe4fc5b3fa4fb235ba21633928a6', ].map(h => Buffer.from(h, 'hex')); const queries = [ createQueryObject({ key: '76', value: '4c94485e0c21ae6c41ce1dfe7b6bfaceea5ab68e40a2476f50208e526f506080', bitmap: '1f', }), ]; const rootHash = '21ecda9db382eff32c9ec899fc7090cf58858e8c22a2af82510cd4d9c9a42c2f'; expect(calculateRoot(siblingHashes, queries, 1).toString('hex')).toEqual(rootHash); }); it('should calculate correct root hash for multi proof of exclusion', () => { const siblingHashes = [ '60a8e2b790e91ca7e05c6eb758a694e42635772b2fa23c0706df4c3423d92a11', 'c4d5a0ec88593441501521e1217be34f8875d1a2f8d2d882f6a411debaa7467e', 'ecb4e7940250348fcbd38c3eb7982ce7d0a748fd832f48a0154b4ff7ded6fe04', '99b0161609748a131c16d46c72ff79ffbfa85e9e2694c52ee665635c4d48ecae', '7ef9d01187c522f5d7198874a28cdb495abefe4fc5b3fa4fb235ba21633928a6', ].map(h => Buffer.from(h, 'hex')); const queries = [ createQueryObject({ key: '76', value: '4c94485e0c21ae6c41ce1dfe7b6bfaceea5ab68e40a2476f50208e526f506080', bitmap: '1f', }), createQueryObject({ key: '6c', value: 'acac86c0e609ca906f632b0e2dacccb2b77d22b0621f20ebece1a4835b93f6f0', bitmap: '1f', }), ]; const rootHash = '21ecda9db382eff32c9ec899fc7090cf58858e8c22a2af82510cd4d9c9a42c2f'; expect(calculateRoot(siblingHashes, queries, 1).toString('hex')).toEqual(rootHash); }); it('should calculate correct root hash for mix proof of inclusion and exclusion', () => { const siblingHashes = [ '60a8e2b790e91ca7e05c6eb758a694e42635772b2fa23c0706df4c3423d92a11', 'ae63f64dd16496628e978c8f8f8659f65de41850be64db2a54ec24f4d5893ffd', 'ecb4e7940250348fcbd38c3eb7982ce7d0a748fd832f48a0154b4ff7ded6fe04', '7ef9d01187c522f5d7198874a28cdb495abefe4fc5b3fa4fb235ba21633928a6', ].map(h => Buffer.from(h, 'hex')); const queries = [ createQueryObject({ key: '76', value: '4c94485e0c21ae6c41ce1dfe7b6bfaceea5ab68e40a2476f50208e526f506080', bitmap: '1f', }), createQueryObject({ key: '7e', value: '7ace431cb61584cb9b8dc7ec08cf38ac0a2d649660be86d349fb43108b542fa4', bitmap: '1f', }), createQueryObject({ key: '6c', value: 'acac86c0e609ca906f632b0e2dacccb2b77d22b0621f20ebece1a4835b93f6f0', bitmap: '1f', }), createQueryObject({ key: '1b', value: '77adfc95029e73b173f60e556f915b0cd8850848111358b1c370fb7c154e61fd', bitmap: '07', }), ]; const rootHash = '21ecda9db382eff32c9ec899fc7090cf58858e8c22a2af82510cd4d9c9a42c2f'; expect(calculateRoot(siblingHashes, queries, 1).toString('hex')).toEqual(rootHash); }); }); describe('binaryStringToBuffer', () => { it.each(binarySampleData)('should convert binary string "%o" to correct buffer value', data => { expect(binaryStringToBuffer(data.str)).toEqual(Buffer.from(data.buf, 'hex')); }); }); describe('bufferToBinaryString', () => { it.each(binarySampleData)('should convert buffer "%o" to correct binary string', data => { expect(bufferToBinaryString(Buffer.from(data.buf, 'hex'))).toEqual(data.str); }); }); describe('getOverlappingStr', () => { it('returns valid overlapping strings', () => { expect(getOverlappingStr('12356', '123456')).toEqual('123'); expect(getOverlappingStr('1010110', '1010010')).toEqual('1010'); }); it('returns empty string if no overlapping strings found', () => { expect(getOverlappingStr('12356', '2356')).toEqual(''); expect(getOverlappingStr('0110011', '110011')).toEqual(''); }); }); describe('verify', () => { it('should return false if number of query keys are not same as proof', () => { const queryKeys = ['01111110', '01101101', '00011011'].map(binaryStringToBuffer); const proof = { siblingHashes: [ 'e6fa536eaac055d524e29fb4682893e3111bf3a027f7cd5ba312aec56460eb1b', '63a154f88e6f5898bada58cbcb0dfcfa84e18cd5d50783e6703d904bef8be36b', 'da7f3bd33f419f025fc34ada50e26bc0094a7f0018f91fa7e51b66c88c6a7e78', 'ed9b2d408363d6edec46b055de68e67b37091f5b7dece4415200082ba01bc73e', ].map(h => Buffer.from(h, 'hex')), queries: [ createQueryObject({ key: 'e1', value: 'f031efa58744e97a34555ca98621d4e8a52ceb5f20b891d5c44ccae0daaaa644', bitmap: '17', }), ], }; const merkleRoot = Buffer.from( '21ecda9db382eff32c9ec899fc7090cf58858e8c22a2af82510cd4d9c9a42c2f', 'hex', ); expect(verify(queryKeys, proof, merkleRoot, 1)).toBeFalse(); }); it('should return false if queries does not match and proof does not provide inclusion proof of one of query key', () => { const queryKeys = ['00110011', '01100000'].map(binaryStringToBuffer); const proof = { siblingHashes: [ '8c221b658e18c43d92b10f8080163db3126af55c093f0cd0d982343388fb7d94', 'e6fa536eaac055d524e29fb4682893e3111bf3a027f7cd5ba312aec56460eb1b', '3c51615213470ea985d3d8622117b3495bd0642d89e0f5816516958229169279', '63a154f88e6f5898bada58cbcb0dfcfa84e18cd5d50783e6703d904bef8be36b', '5577aaf6e0896ee04e13a5f06004ba763d20a668a815b7b39f8cfd6748373406', 'da7f3bd33f419f025fc34ada50e26bc0094a7f0018f91fa7e51b66c88c6a7e78', ].map(h => Buffer.from(h, 'hex')), queries: [ createQueryObject({ key: '33', // 00110011 value: '4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce', bitmap: '17', }), createQueryObject({ key: 'e1', // 11100001 value: 'f031efa58744e97a34555ca98621d4e8a52ceb5f20b891d5c44ccae0daaaa644', bitmap: '17', }), ], }; const merkleRoot = Buffer.from( '21ecda9db382eff32c9ec899fc7090cf58858e8c22a2af82510cd4d9c9a42c2f', 'hex', ); expect(verify(queryKeys, proof, merkleRoot, 1)).toBeFalse(); }); it('should return true if queries do not match but response query object provides a matching/valid merkle root', () => { const queryKeys = ['01011010', '10101000'].map(binaryStringToBuffer); const proof = { siblingHashes: [ 'e041e1c0e364cc015af04118c1cd5a6554a7b357727ed937aac49436f0fbbf9c', '6400721efe3b54db24f248b0d8c93c0aa21eee1eebca058a143da44abeeea0e3', '99b0161609748a131c16d46c72ff79ffbfa85e9e2694c52ee665635c4d48ecae', '3c32b1317e5021885cda1625d28d8f90c44a1338f60ef476f5a7992d35c765e2', ].map(h => Buffer.from(h, 'hex')), queries: [ createQueryObject({ key: '5a', // 01011010 value: 'bbeebd879e1dff6918546dc0c179fdde505f2a21591c9a9c96e36b054ec5af83', bitmap: '07', }), createQueryObject({ key: 'a9', // 10101001 value: '9e8e8c37a53bac77a653d590b783b2508e8ed2fed040a278bf4f4703bbd5d82d', bitmap: '07', }), ], }; const merkleRoot = Buffer.from( '21ecda9db382eff32c9ec899fc7090cf58858e8c22a2af82510cd4d9c9a42c2f', 'hex', ); expect(verify(queryKeys, proof, merkleRoot, 1)).toBeTrue(); }); it('should return true for matching queries and root', () => { const queryKeys = ['01011010', '10101001'].map(binaryStringToBuffer); const proof = { siblingHashes: [ 'e041e1c0e364cc015af04118c1cd5a6554a7b357727ed937aac49436f0fbbf9c', '6400721efe3b54db24f248b0d8c93c0aa21eee1eebca058a143da44abeeea0e3', '99b0161609748a131c16d46c72ff79ffbfa85e9e2694c52ee665635c4d48ecae', '3c32b1317e5021885cda1625d28d8f90c44a1338f60ef476f5a7992d35c765e2', ].map(h => Buffer.from(h, 'hex')), queries: [ createQueryObject({ key: '5a', // 01011010 value: 'bbeebd879e1dff6918546dc0c179fdde505f2a21591c9a9c96e36b054ec5af83', bitmap: '07', }), createQueryObject({ key: 'a9', // 10101001 value: '9e8e8c37a53bac77a653d590b783b2508e8ed2fed040a278bf4f4703bbd5d82d', bitmap: '07', }), ], }; const merkleRoot = Buffer.from( '21ecda9db382eff32c9ec899fc7090cf58858e8c22a2af82510cd4d9c9a42c2f', 'hex', ); expect(verify(queryKeys, proof, merkleRoot, 1)).toBeTrue(); }); }); describe('binaryExpansion', () => { const sampleData = [ { str: '00010010', buf: Buffer.from('12', 'hex'), keyLength: 1, }, { str: '00111100', buf: Buffer.from('3c', 'hex'), keyLength: 1, }, { str: '1110011101111011100110101001101011101001111000110000101100001101101111011011011011110101000100001010001001100100111011111001110111100111100000010101000000011101011110110110101110010010101011101000100111101011000001011001110001011010101101110100001111011011', buf: Buffer.from('e77b9a9ae9e30b0dbdb6f510a264ef9de781501d7b6b92ae89eb059c5ab743db', 'hex'), keyLength: 32, }, { str: '0000100001001111111011010000100010111001011110001010111101001101011111010001100101101010011101000100011010101000011010110101100000000000100111100110001101101011011000010001110110110001011000100001000110110110010110101001101010101101111111110010100111000101', buf: Buffer.from('084fed08b978af4d7d196a7446a86b58009e636b611db16211b65a9aadff29c5', 'hex'), keyLength: 32, }, { str: '1101101100010011101111100000000100111100101000011011000011100111000100110010100000001111100110111100011000110000000101111111001010100011010001010010001110010001111010011000101100000001100010010011010111100000000010110110010110111010010101011001101100100101001001111101100010010010010100001110000111000000', buf: Buffer.from( 'db13be013ca1b0e713280f9bc63017f2a3452391e98b018935e00b65ba559b2527d89250e1c0', 'hex', ), keyLength: 38, }, { str: '0110010101001101100110110101111000110011111000101000000101101001111101110001000001101000100111010100001000000010110000111101111111010000011010000001000011110000101110000111101101110010010010001100111110000000001010011011101101110101011100111101110100110110110001010001111001010111101110111011100110110100', buf: Buffer.from( '654d9b5e33e28169f710689d4202c3dfd06810f0b87b7248cf8029bb7573dd36c51e57bbb9b4', 'hex', ), keyLength: 38, }, ]; for (const data of sampleData) { it(`should return correct binary string for ${data.keyLength} byte size`, () => expect(data.str).toEqual(binaryExpansion(data.buf, data.keyLength))); } }); describe('isLeaf', () => { const sampleKey = Buffer.from('46', 'hex'); const sampleValue = Buffer.from( 'f031efa58744e97a34555ca98621d4e8a52ceb5f20b891d5c44ccae0daaaa644', 'hex', ); const leafDataBuffer = leafData(sampleKey, sampleValue); const branchDataBuffer = branchData(sampleKey, sampleValue); it('Should return true when a leaf node data is passed', () => expect(isLeaf(leafDataBuffer)).toEqual(true)); it('Should return false when a branch node data is passed', () => expect(isLeaf(branchDataBuffer)).toEqual(false)); }); describe('parseLeaf', () => { const sampleKey = Buffer.from('46', 'hex'); const sampleValue = Buffer.from( 'f031efa58744e97a34555ca98621d4e8a52ceb5f20b891d5c44ccae0daaaa644', 'hex', ); const leafDataBuffer = leafData(sampleKey, sampleValue); it('Should return key value from leaf data buffer', () => expect(parseLeafData(leafDataBuffer, 1)).toEqual({ key: sampleKey, value: sampleValue, })); it('should get key value of 38 bytes from leaf data buffer', () => { const key38Bytes = getRandomBytes(38); const leafDataWith38ByteKey = leafData(key38Bytes, sampleValue); expect(parseLeafData(leafDataWith38ByteKey, key38Bytes.byteLength)).toEqual({ key: key38Bytes, value: sampleValue, }); }); }); describe('parseBranch', () => { const leftHash = Buffer.from( '2031efa58744e97a34555ca98621d4e8a52ceb5f20b891d5c44ccae0daaaa644', 'hex', ); const rightHash = Buffer.from( '1031efa58744e97a34555ca98621d4e8a52ceb5f20b891d5c44ccae0daaaa644', 'hex', ); const branchDataBuffer = branchData(leftHash, rightHash); it('Should return key value from leaf data buffer', () => expect(parseBranchData(branchDataBuffer)).toEqual({ leftHash, rightHash, })); }); });
the_stack
* {{cookiecutter.project_name}} * {{cookiecutter.project_name}} API * * The version of the OpenAPI document: 0.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; import { Configuration } from '../configuration'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '../common'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from '../base'; // @ts-ignore import { HTTPValidationError } from '../models'; // @ts-ignore import { Item } from '../models'; // @ts-ignore import { ItemCreate } from '../models'; // @ts-ignore import { ItemUpdate } from '../models'; /** * ItemsApi - axios parameter creator * @export */ export const ItemsApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * * @summary Create Item * @param {ItemCreate} itemCreate * @param {*} [options] Override http request option. * @throws {RequiredError} */ createItem: async (itemCreate: ItemCreate, options: AxiosRequestConfig = {}): Promise<RequestArgs> => { // verify required parameter 'itemCreate' is not null or undefined assertParamExists('createItem', 'itemCreate', itemCreate) const localVarPath = `/api/v1/items`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication OAuth2PasswordBearer required // oauth required await setOAuthToObject(localVarHeaderParameter, "OAuth2PasswordBearer", [], configuration) localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(itemCreate, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @summary Delete Item * @param {number} itemId * @param {*} [options] Override http request option. * @throws {RequiredError} */ deleteItem: async (itemId: number, options: AxiosRequestConfig = {}): Promise<RequestArgs> => { // verify required parameter 'itemId' is not null or undefined assertParamExists('deleteItem', 'itemId', itemId) const localVarPath = `/api/v1/items/{item_id}` .replace(`{${"item_id"}}`, encodeURIComponent(String(itemId))); // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication OAuth2PasswordBearer required // oauth required await setOAuthToObject(localVarHeaderParameter, "OAuth2PasswordBearer", [], configuration) setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @summary Get Item * @param {number} itemId * @param {*} [options] Override http request option. * @throws {RequiredError} */ getItem: async (itemId: number, options: AxiosRequestConfig = {}): Promise<RequestArgs> => { // verify required parameter 'itemId' is not null or undefined assertParamExists('getItem', 'itemId', itemId) const localVarPath = `/api/v1/items/{item_id}` .replace(`{${"item_id"}}`, encodeURIComponent(String(itemId))); // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication OAuth2PasswordBearer required // oauth required await setOAuthToObject(localVarHeaderParameter, "OAuth2PasswordBearer", [], configuration) setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @summary Get Items * @param {string} [sort] Format: &#x60;[\&quot;field_name\&quot;, \&quot;direction\&quot;]&#x60; * @param {string} [range] Format: &#x60;[start, end]&#x60; * @param {*} [options] Override http request option. * @throws {RequiredError} */ getItems: async (sort?: string, range?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/items`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication OAuth2PasswordBearer required // oauth required await setOAuthToObject(localVarHeaderParameter, "OAuth2PasswordBearer", [], configuration) if (sort !== undefined) { localVarQueryParameter['sort'] = sort; } if (range !== undefined) { localVarQueryParameter['range'] = range; } setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @summary Update Item * @param {number} itemId * @param {ItemUpdate} itemUpdate * @param {*} [options] Override http request option. * @throws {RequiredError} */ updateItem: async (itemId: number, itemUpdate: ItemUpdate, options: AxiosRequestConfig = {}): Promise<RequestArgs> => { // verify required parameter 'itemId' is not null or undefined assertParamExists('updateItem', 'itemId', itemId) // verify required parameter 'itemUpdate' is not null or undefined assertParamExists('updateItem', 'itemUpdate', itemUpdate) const localVarPath = `/api/v1/items/{item_id}` .replace(`{${"item_id"}}`, encodeURIComponent(String(itemId))); // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication OAuth2PasswordBearer required // oauth required await setOAuthToObject(localVarHeaderParameter, "OAuth2PasswordBearer", [], configuration) localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(itemUpdate, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * ItemsApi - functional programming interface * @export */ export const ItemsApiFp = function(configuration?: Configuration) { const localVarAxiosParamCreator = ItemsApiAxiosParamCreator(configuration) return { /** * * @summary Create Item * @param {ItemCreate} itemCreate * @param {*} [options] Override http request option. * @throws {RequiredError} */ async createItem(itemCreate: ItemCreate, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Item>> { const localVarAxiosArgs = await localVarAxiosParamCreator.createItem(itemCreate, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @summary Delete Item * @param {number} itemId * @param {*} [options] Override http request option. * @throws {RequiredError} */ async deleteItem(itemId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<any>> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteItem(itemId, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @summary Get Item * @param {number} itemId * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getItem(itemId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Item>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getItem(itemId, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @summary Get Items * @param {string} [sort] Format: &#x60;[\&quot;field_name\&quot;, \&quot;direction\&quot;]&#x60; * @param {string} [range] Format: &#x60;[start, end]&#x60; * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getItems(sort?: string, range?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Array<Item>>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getItems(sort, range, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @summary Update Item * @param {number} itemId * @param {ItemUpdate} itemUpdate * @param {*} [options] Override http request option. * @throws {RequiredError} */ async updateItem(itemId: number, itemUpdate: ItemUpdate, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Item>> { const localVarAxiosArgs = await localVarAxiosParamCreator.updateItem(itemId, itemUpdate, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, } }; /** * ItemsApi - factory interface * @export */ export const ItemsApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { const localVarFp = ItemsApiFp(configuration) return { /** * * @summary Create Item * @param {ItemCreate} itemCreate * @param {*} [options] Override http request option. * @throws {RequiredError} */ createItem(itemCreate: ItemCreate, options?: any): AxiosPromise<Item> { return localVarFp.createItem(itemCreate, options).then((request) => request(axios, basePath)); }, /** * * @summary Delete Item * @param {number} itemId * @param {*} [options] Override http request option. * @throws {RequiredError} */ deleteItem(itemId: number, options?: any): AxiosPromise<any> { return localVarFp.deleteItem(itemId, options).then((request) => request(axios, basePath)); }, /** * * @summary Get Item * @param {number} itemId * @param {*} [options] Override http request option. * @throws {RequiredError} */ getItem(itemId: number, options?: any): AxiosPromise<Item> { return localVarFp.getItem(itemId, options).then((request) => request(axios, basePath)); }, /** * * @summary Get Items * @param {string} [sort] Format: &#x60;[\&quot;field_name\&quot;, \&quot;direction\&quot;]&#x60; * @param {string} [range] Format: &#x60;[start, end]&#x60; * @param {*} [options] Override http request option. * @throws {RequiredError} */ getItems(sort?: string, range?: string, options?: any): AxiosPromise<Array<Item>> { return localVarFp.getItems(sort, range, options).then((request) => request(axios, basePath)); }, /** * * @summary Update Item * @param {number} itemId * @param {ItemUpdate} itemUpdate * @param {*} [options] Override http request option. * @throws {RequiredError} */ updateItem(itemId: number, itemUpdate: ItemUpdate, options?: any): AxiosPromise<Item> { return localVarFp.updateItem(itemId, itemUpdate, options).then((request) => request(axios, basePath)); }, }; }; /** * Request parameters for createItem operation in ItemsApi. * @export * @interface ItemsApiCreateItemRequest */ export interface ItemsApiCreateItemRequest { /** * * @type {ItemCreate} * @memberof ItemsApiCreateItem */ readonly itemCreate: ItemCreate } /** * Request parameters for deleteItem operation in ItemsApi. * @export * @interface ItemsApiDeleteItemRequest */ export interface ItemsApiDeleteItemRequest { /** * * @type {number} * @memberof ItemsApiDeleteItem */ readonly itemId: number } /** * Request parameters for getItem operation in ItemsApi. * @export * @interface ItemsApiGetItemRequest */ export interface ItemsApiGetItemRequest { /** * * @type {number} * @memberof ItemsApiGetItem */ readonly itemId: number } /** * Request parameters for getItems operation in ItemsApi. * @export * @interface ItemsApiGetItemsRequest */ export interface ItemsApiGetItemsRequest { /** * Format: &#x60;[\&quot;field_name\&quot;, \&quot;direction\&quot;]&#x60; * @type {string} * @memberof ItemsApiGetItems */ readonly sort?: string /** * Format: &#x60;[start, end]&#x60; * @type {string} * @memberof ItemsApiGetItems */ readonly range?: string } /** * Request parameters for updateItem operation in ItemsApi. * @export * @interface ItemsApiUpdateItemRequest */ export interface ItemsApiUpdateItemRequest { /** * * @type {number} * @memberof ItemsApiUpdateItem */ readonly itemId: number /** * * @type {ItemUpdate} * @memberof ItemsApiUpdateItem */ readonly itemUpdate: ItemUpdate } /** * ItemsApi - object-oriented interface * @export * @class ItemsApi * @extends {BaseAPI} */ export class ItemsApi extends BaseAPI { /** * * @summary Create Item * @param {ItemsApiCreateItemRequest} requestParameters Request parameters. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ItemsApi */ public createItem(requestParameters: ItemsApiCreateItemRequest, options?: AxiosRequestConfig) { return ItemsApiFp(this.configuration).createItem(requestParameters.itemCreate, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Delete Item * @param {ItemsApiDeleteItemRequest} requestParameters Request parameters. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ItemsApi */ public deleteItem(requestParameters: ItemsApiDeleteItemRequest, options?: AxiosRequestConfig) { return ItemsApiFp(this.configuration).deleteItem(requestParameters.itemId, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Get Item * @param {ItemsApiGetItemRequest} requestParameters Request parameters. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ItemsApi */ public getItem(requestParameters: ItemsApiGetItemRequest, options?: AxiosRequestConfig) { return ItemsApiFp(this.configuration).getItem(requestParameters.itemId, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Get Items * @param {ItemsApiGetItemsRequest} requestParameters Request parameters. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ItemsApi */ public getItems(requestParameters: ItemsApiGetItemsRequest = {}, options?: AxiosRequestConfig) { return ItemsApiFp(this.configuration).getItems(requestParameters.sort, requestParameters.range, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Update Item * @param {ItemsApiUpdateItemRequest} requestParameters Request parameters. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ItemsApi */ public updateItem(requestParameters: ItemsApiUpdateItemRequest, options?: AxiosRequestConfig) { return ItemsApiFp(this.configuration).updateItem(requestParameters.itemId, requestParameters.itemUpdate, options).then((request) => request(this.axios, this.basePath)); } }
the_stack
import * as Fs from 'fs-extra'; import * as Handlebars from 'handlebars'; import * as Path from 'path'; import { Git} from '../git'; import { Paths} from '../paths'; import { Release} from '../release'; import { Utils} from '../utils'; /** A wrapper for Handlebars with several additions which are essential for Tortilla */ // Creating a new instance of handlebars which will then be merged with the module const handlebars = Handlebars.create(); // Keep original handlers since these methods are gonna be overriden const superRegisterHelper = handlebars.registerHelper.bind(handlebars); const superRegisterPartial = handlebars.registerPartial.bind(handlebars); // Used to store registered transformations const transformations = {}; // Cache for templates which were already compiled const cache = {}; // Read the provided file, render it, and overwrite it. Use with caution! function overwriteTemplateFile(templatePath, scope) { templatePath = resolveTemplatePath(templatePath); const view = renderTemplateFile(templatePath, scope); return Fs.writeFileSync(templatePath, view); } // Read provided file and render its template. Note that the default path would // be tortilla's template dir, so specifying a file name would be ok as well function renderTemplateFile(templatePath, scope) { templatePath = resolveTemplatePath(templatePath); if (process.env.TORTILLA_CACHE_DISABLED || !cache[templatePath]) { const templateContent = Fs.readFileSync(templatePath, 'utf8'); cache[templatePath] = handlebars.compile(templateContent); } const template = cache[templatePath]; return renderTemplate(template, scope); } // Render provided template function renderTemplate(template, scope: any = {}) { // Template can either be a string or a compiled template object if (typeof template === 'string') { template = handlebars.compile(template); } let viewDir; if (scope.viewPath) { // Relative path of view dir // e.g. manuals/views viewDir = Path.dirname(scope.viewPath); } const oldResolve = (handlebars as any).resolve; try { // Set the view file for the resolve utility. If no view path was provided, the // resolve function below still won't work (handlebars as any).resolve = resolvePath.bind(null, viewDir); // Remove trailing white-space return template(scope).replace(/ *\n/g, '\n'); } finally { // Either if an error was thrown or not, unbind it (handlebars as any).resolve = oldResolve; } } // Returns a template path relative to tortilla with an '.tmpl' extension function resolveTemplatePath(templatePath) { if (templatePath.indexOf('.tmpl') === -1) { templatePath += '.tmpl'; } // User defined templates const relativeTemplatePath = Path.resolve(Paths.manuals.templates, templatePath); if (Utils.exists(relativeTemplatePath)) { return relativeTemplatePath; } // Tortilla defined templates return Path.resolve(Paths.tortilla.renderer.templates, templatePath); } // Register a new helper. Registered helpers will be wrapped with a // [{]: <helper> (name ...args) [}]: # function registerHelper(name, helper, options?) { options = options || {}; const wrappedHelper = function() { const oldCall = (handlebars as any).call; let out; try { // Bind the call method to the current context (handlebars as any).call = callHelper.bind(this); out = helper.apply(this, arguments); } finally { // Fallback // Restore method to its original (handlebars as any).call = oldCall; } if (typeof out !== 'string' && !(out instanceof String)) { throw Error([ 'Template helper', name, 'must return a string!', 'Instead it returned', out, ].join(' ')); } const target = process.env.TORTILLA_RENDER_TARGET; const args = [].slice.call(arguments); // Transform helper output const transformation = transformations[target] && transformations[target][name]; if (transformation) { out = transformation(...[out].concat(args)); } // Wrap helper output if (options.mdWrap) { out = mdWrapComponent('helper', name, args, out); } return out; }; superRegisterHelper(name, wrappedHelper); } // Register a new partial. Registered partials will be wrapped with a // [{]: <partial> (name) [}]: # function registerPartial(name, partial, options) { options = options || {}; // Wrap partial template if (options.mdWrap) { partial = mdWrapComponent('partial', name, partial); } return superRegisterPartial(name, partial); } // Register a new transformation which will take effect on rendered helpers. This is // useful when setting the TORTILLA_RENDER_TARGET variable, so we can make additional // adjustments for custom targets. For now this is NOT part of the official API and // is used only for development purposes function registerTransformation(targetName, helperName, transformation) { if (!transformations[targetName]) { transformations[targetName] = {}; } transformations[targetName][helperName] = transformation; } // Returns content wrapped by component notations. Mostly useful if we want to detect // components in the view later on using external softwares later on. // e.g. https://github.com/Urigo/angular-meteor-docs/blob/master/src/app/tutorials/ // improve-code-resolver.ts#L24 function mdWrapComponent(type, name, args, content?) { let hash = {}; if (typeof content !== 'string') { content = args; args = []; } if (args[args.length - 1] instanceof Object) { hash = args.pop().hash; } // Stringify arguments const params = args.map((param) => typeof param === 'string' ? `"${param}"` : param).join(' '); hash = stringifyHash(hash); // Concat all stringified arguments args = [name, params, hash] // Get rid of empty strings .filter(Boolean) .join(' '); return `[{]: <${type}> (${Utils.escapeBrackets(args)})\n\n${content}\n\n[}]: #`; } // Takes a helper hash and stringifying it // e.g. { foo: '1', bar: 2 } -> foo="1" bar=2 function stringifyHash(hash) { return Object.keys(hash).map((key) => { let value = hash[key]; if (typeof value === 'string') { value = `"${value}"`; } return `${key}=${value}`; }).join(' '); } // Calls a template helper with the provided context and arguments function callHelper(methodName) { const args = [].slice.call(arguments, 1); let options = args.pop(); // Simulate call from template if (options instanceof Object) { options = { hash: options }; } args.push(options); return handlebars.helpers[methodName].apply(this, args); } // Takes a bunch of paths and resolved them relatively to the current rendered view function resolvePath(/* reserved path, user defined path */) { const paths = [].slice.call(arguments); // A default path that the host's markdown renderer will know how to resolve by its own let defaultPath = paths.slice(1).join('/'); /* tslint:disable-next-line */ defaultPath = new String(defaultPath); // The 'isRelative' flag can be used later on to determine if this is an absolute path // or a relative path defaultPath.isRelative = true; const cwd = paths.shift(); // If function is unbound, return default path if (typeof cwd !== 'string') { return defaultPath; } const repository = Fs.readJsonSync(Paths.npm.package).repository; let repositoryUrl = typeof repository === 'object' ? repository.url : repository; // If no repository was defined, or // repository type is not git, or // no repository url is defined, return default path if (!repositoryUrl) { return defaultPath; } repositoryUrl = repositoryUrl // Remove .git postfix .replace(/.git$/, '') // Remove USERNAME@githost.com prefix .replace(/[\w]+@/g, ''); let releaseTag // First try to see if HEAD is referencing a release tag already. This is necessary // if we're running executing the current template helper for a submodule try { releaseTag = Git(['describe', '--tags', '--exact-match', 'HEAD']); // If not, manually compose it. Necessary for the main git-module } catch (e) { const currentRelease = Release.format(Release.current()); // Any release is yet to exist if (currentRelease === '0.0.0') { return defaultPath; } releaseTag = `${Git.activeBranchName()}@${currentRelease}`; } // Compose branch path for current release tree // e.g. github.com/Urigo/Ionic2CLI-Meteor-Whatsapp/tree/master@0.0.1 const branchUrl = [repositoryUrl, 'tree', releaseTag].join('\/'); const protocol = (branchUrl.match(/^.+\:\/\//) || [''])[0]; // Using a / so we can use it with the 'path' module const branchPath = `/${branchUrl.substr(protocol.length)}`; // If we use tilde (~) at the beginning of the path, we will be referenced to the // repo's root URL. This is useful when we want to compose links which are // completely disconnected from the current state, like commits, issues and PRs let resolved = paths.map((path) => path.replace(/\~/g, Path.resolve(branchPath, '../..'))); // The view dir URL // e.g. github.com/DAB0mB/radial-snake/tree/master@0.1.5/.tortilla/manuals/views resolved.unshift(Path.join(branchPath, Path.relative(Utils.cwd(), Path.resolve(Utils.cwd(), cwd)))); resolved = Path.resolve(...resolved); // Concatenating the protocol back after final path has been formed resolved = protocol + resolved.substr(1); return resolved; } export const Renderer = Utils.extend(handlebars, { overwriteTemplateFile, renderTemplateFile, renderTemplate, registerHelper, registerPartial, registerTransformation, // This should be set whenever we're in a helper scope call: callHelper, // Should be bound by the `renderTemplate` method resolve: resolvePath.bind(null, null), }); // Built-in helpers and partials import './helpers/comment'; import './helpers/diff-step'; import './helpers/nav-step'; import './helpers/resolve-path'; import './helpers/step-message'; import './helpers/toc'; import './helpers/translate';
the_stack
import { t, N, AnyOp, VarUint7 } from './ast' import { utf8 } from './utf8' import { uint8, uint16, uint32, float32, float64 } from './basic-types'; import { opcodes } from './info' export type Writer = (s :string)=>void export interface Options { readonly colors :boolean // explicitly enable or disable terminal colors readonly immSeparator :string // defaults to `:` readonly detailedTypes? :boolean, // `vi32(9)` or just `9` } interface Ctx { readonly write :(depth :number, s :string)=>void readonly writeln :(depth :number, s :string)=>void readonly writeinline :(s :string)=>void readonly options :Options } function symname(y :Symbol) { const s = y.toString() return s.length > 8 ? s.substr(7,s.length-8) : 'Symbol(?)'; } // const indln = (indent? :string) => (indent ? '\n' + indent : '') const style = (str :string, style :string) => '\x1B[' + style + 'm' + str + '\x1B[0m' const reprop = (op :uint8) => style(opcodes.get(op), '96') const styleType = (s :string) => style(s, '33') function readVarInt7(byte :uint8) { return byte < 64 ? byte : -(128 - byte) } function visitAll(nodes :N[], c :Ctx, depth :number) { for (let n of nodes) { visit(n, c, depth) } } function visitCell(n :N, tname :string, c :Ctx, depth :number) { c.write(depth, '(' + tname) visitAll(n.v, c, depth + 1) c.write(depth, ')') } function visitValue(v :any, tname :string, c :Ctx, depth :number) { const s = String(v) return c.write(depth, c.options.detailedTypes ? `${tname}(${s})` : s) } function visit(n :N, c :Ctx, depth :number) { const tname = style(symname(n.t), '92') switch (n.t) { // Atoms case t.uint8: case t.uint16: case t.uint32: case t.varuint1: case t.varuint7: case t.varuint32: case t.varint32: case t.varint64: case t.float32: case t.float64: { return visitValue(n.v, tname, c, depth) } case t.varint7: { return visitValue(readVarInt7(n.v), tname, c, depth) } case t.external_kind: { switch (n.v) { case 0: return c.write(depth, styleType('external_kind.function')) case 1: return c.write(depth, styleType('external_kind.table')) case 2: return c.write(depth, styleType('external_kind.memory')) case 3: return c.write(depth, styleType('external_kind.global')) default: return visitValue(readVarInt7(n.v), tname, c, depth) } } // Instructions case t.instr: { return c.write(depth, reprop(n.v)) } case t.instr_imm1: { c.write(depth, '(' + reprop(n.v) + ' [') visit((n as AnyOp).imm as N, c, depth + 1) return c.write(depth, '])') } case t.instr_pre: { c.write(depth, '(' + reprop(n.v)) visitAll((n as AnyOp).pre as N[], c, depth + 1) return c.writeln(depth , ')') } case t.instr_pre1: { c.write(depth, '(' + reprop(n.v)) visit((n as AnyOp).pre as N, c, depth + 1) return c.writeln(depth, ')') } case t.instr_imm1_post: { c.write(depth, '(' + reprop(n.v) + ' [') visit((n as AnyOp).imm as N, c, depth + 1) c.write(depth, ']') visitAll((n as AnyOp).post as N[], c, depth + 1) return c.write(depth, ')') } case t.instr_pre_imm: { c.write(depth, '(' + reprop(n.v) + ' [') visitAll((n as AnyOp).imm as N[], c, depth + 1) c.write(depth, ']') visitAll((n as AnyOp).pre as N[], c, depth + 1) return c.write(depth, ')') } case t.instr_pre_imm_post: { c.write(depth, '(' + reprop(n.v) + ' [') visitAll((n as AnyOp).imm as N[], c, depth + 1) c.write(depth, ']') visitAll((n as AnyOp).pre as N[], c, depth + 1) visitAll((n as AnyOp).post as N[], c, depth + 1) return c.write(depth, ')') } // TODO: special case of "if" // { // let s = ind(indent) + '(' + reprop(this.v) // // if (this.v == 0x04/*if*/) { // let cind = (indent || '') + ' ' // // s += ' ' + this.imm[0].repr() + // type // this.pre[0].repr(cind) + // cond // ind(cind) + '(then'; // // let i = 1, ci = (cind || '') + ' ', E = this.imm.length-1 // skip `end` // for (; i < E; ++i) { // let n = this.imm[i] // if (n.v == 0x05/*else*/) { // s += ')' // end of "then" // break // } // s += ' ' + n.repr(ci) // } // // if (i < E) { // s += ind(cind) + '(else'; // ++i // for (; i < E; ++i) { // let n = this.imm[i] // s += ' ' + n.repr(ci) // } // } // // return s + ') end)' // end of "then" or "else" // } // // return s + `${reprv(indent, this.imm)}${reprv(indent, this.pre)})` // } case t.data: { let v :string[] = [] for (let i = 0, L = n.v.length; i != L; ++i) { if (v.length == 8) { v.push('...') ;break } v.push((n.v[i] as number).toString(16)) } return c.write(depth, '(' + tname + ' ' + v.join(' ') + ')') } case t.type: { switch (n.v) { case -1: return c.write(depth, styleType('i32')) case -2: return c.write(depth, styleType('i64')) case -3: return c.write(depth, styleType('f32')) case -4: return c.write(depth, styleType('f64')) case -0x10: return c.write(depth, styleType('anyfunc')) case -0x20: return c.write(depth, styleType('func')) case -0x40: return c.write(depth, styleType('void')) // aka empty_block default: return c.write(depth, styleType('?')) } } // ————————————————————————————————————————————————————————————————— // Cells case t.module: { c.write(depth, '(' + tname + ' ' + n.v[1].v) visitAll(n.v.slice(2), c, depth + 1) return c.write(depth, ')') } case t.section: { const id = (n.v[0] as VarUint7).v const name = [ 'custom', // 0 Custom named section 'type', // 1 Function signature declarations 'import', // 2 Import declarations 'function', // 3 Function declarations 'table', // 4 Indirect function table and other tables 'memory', // 5 Memory attributes 'global', // 6 Global declarations 'export', // 7 Exports 'start', // 8 Start function declaration 'element', // 9 Elements section 'code', // 10 Function bodies (code) 'data', // 11 Data segments ][id] || ('0x' + id.toString(16)) c.write(depth, '(' + tname + ' ' + name) visitAll(n.v.slice(1), c, depth + 1) return c.write(depth, ')') } case t.import_entry: case t.export_entry: case t.local_entry: case t.table_type: case t.memory_type: { return visitCell(n, tname, c, depth) } case t.func_type: { // func, paramCount, paramT*, retCount, retT* -> "(" paramT* ")" retT c.write(depth, '(' + tname + ' (') const paramCount = n.v[1].v as number const resCount = n.v[1 + paramCount + 1].v as number visitAll(n.v.slice(2, 2+paramCount), c, depth) c.writeinline(')') if (resCount > 0) { visitAll(n.v.slice(1 + paramCount + 2), c, depth) } return c.write(depth, ')') } case t.global_type: { c.write(depth, '(' + tname) visitAll(n.v.slice(0, n.v.length-1), c, depth + 1) c.write(depth + 1, (n.v[1].v ? ' mutable' : 'immutable')) return c.write(depth, ')') } case t.resizable_limits: { return c.write(depth, '(' + tname + ' ' + n.v[1].v + '..' + (n.v[0].v ? n.v[2].v : '') + ')' ) } case t.global_variable: case t.init_expr: case t.elem_segment: case t.data_segment: case t.function_body: { return visitCell(n, tname, c, depth) } case t.str: { return c.write(depth, '"' + utf8.decode(n.v) + '"') } default: throw new Error('unexpected type ' + n.t.toString()) } } export function reprBuffer( buffer :ArrayBuffer, w :Writer, limit? :number, highlightRange? :number[], options? :Options) { limit = Math.min(buffer.byteLength, limit || Infinity) if (highlightRange && !highlightRange[1]) { highlightRange[1] = highlightRange[0]+1 } let s = [], i = 0, view = new DataView(buffer) for (; i < limit; ++i) { let b = view.getUint8(i) const inHLRange = (highlightRange && i < highlightRange[1] && i >= highlightRange[0]) if (b == 0 && !inHLRange) { s.push('\x1B[2m00\x1B[0m') } else { let str = b.toString(16) s.push( inHLRange ? ('\x1B[45;97m' + (str.length == 1 ? '0' : '') + str + '\x1B[0m' ) : str.length == 1 ? '\x1B[2m0\x1B[0m' + str : str ) } if (s.length % 20 == 19) { w(s.join(' ') + '\n'); s = []; } else if (s.length % 5 == 4) { s.push('') } } const tail = (highlightRange && highlightRange[0] >= i) ? '\x1B[45;97m..\x1B[0m' : '' if (s.length) { w(s.join(' ') + (tail ? ' ' + tail : '') + '\n'); } else if (tail) { w(tail + '\n') } } export function repr(n :N, w :Writer, options? :Options) { const maxLineLength = 40 const SP = ' ' let currLineLen = 0 let lastCh = '' let writer = w if (!options || options.colors !== false) { // writer that colors immediate brackets let immOpen = style('[', '2'), immClose = style(']', '2') writer = s => { w(s.replace(/([^\x1B]|^)[\[\]]/g, m => m.length == 2 ? m[0] + (m[1] == '[' ? immOpen : immClose) : (m[0] == '[' ? immOpen : immClose) )) } } const ctx = { options: Object.assign({ // detailedTypes: true, immSeparator: ':', }, options || {}) as Options, writeln(depth :number, chunk :string) { const line = SP.substr(0, depth * 2) + chunk currLineLen = line.length lastCh = chunk[chunk.length-1] writer('\n' + line) }, writeinline(chunk :string) { currLineLen += chunk.length lastCh = chunk[chunk.length-1] writer(chunk) }, write(depth :number, chunk :string) { if (currLineLen > 0 && depth > 0) { const ch0 = chunk[0] if (ch0 == '(') { return this.writeln(depth, chunk) } if (ch0 != ')' && ch0 != ']' && lastCh != '[' && lastCh != '(') { currLineLen += 1 chunk = ' ' + chunk } } this.writeinline(chunk) }, } visit(n, ctx, 0) } // Simple Writer that buffers everything as a string that export function BufferedWriter() { const buf = [] const w = s => { buf.push(s) } w.toString = () => buf.join('') return w } // Convenience functions that returns strings. // Will be slower and use more memory than `repr` but convenient for // visualizing smaller structures. export function strRepr(n :N, options? :Options) { const w = BufferedWriter() repr(n, w, options) return w.toString() } export function strReprBuffer( buffer :ArrayBuffer, limit? :number, highlightRange? :number[], options? :Options) { const w = BufferedWriter() reprBuffer(buffer, w, limit, highlightRange, options) return w.toString() }
the_stack
import * as a from '../parser/ast'; import { wat2wasm, convertMiBToPage } from '../wasm'; import { CodegenContext } from './context'; import { SExp, beautify } from 's-exify'; export function genWASM( mod: a.Module, opts: { exports: Array<string>; memorySize: number }, ): Buffer { return wat2wasm(genWAT(mod, opts)); } export function genWAT( mod: a.Module, opts: { exports: Array<string>; memorySize: number }, ): string { return beautify( codegenModule(mod, new CodegenContext(), { exports: opts.exports, pageCount: convertMiBToPage(opts.memorySize), }), ); } const exp = (...nodes: Array<string | SExp>): SExp => nodes; const str = (raw: string) => `"${raw.replace('"', '\\"')}"`; const wat = (name: string) => `$${name}`; const sys = (name: string) => wat(`/${name}`); function codegenModule( mod: a.Module, ctx: CodegenContext, opts: { exports: Array<string>; pageCount: number; }, ): SExp { const modE = exp('module'); // imports modE.push( exp( 'import', str('js'), str('memory'), exp('memory', String(opts.pageCount)), ), ); // system registries for language implementation modE.push(...codegenRegistry(ctx)); for (const decl of mod.value.decls) { // register global names first ctx.pushName(decl.value.name.value); } for (const decl of mod.value.decls) { // actual codegen for global decls const declE = codegenGlobalDecl(decl, ctx); if (declE) modE.push(declE); } modE.push(...codegenStartFunc(ctx)); // used tuple constructors for (const [name, { types, sizes }] of ctx.tupleConstructors.entries()) { modE.push(codegenTupleConstructor(name, types, sizes)); } for (const exportName of opts.exports) { const watName = ctx.getGlobalWATName(exportName)!; modE.push(exp('export', str(exportName), exp('func', wat(watName)))); } return modE; } function* codegenRegistry(ctx: CodegenContext): Iterable<SExp> { const reg = (name: string, ty: string) => exp('global', sys(name), exp('mut', ty), exp(`${ty}.const`, '0')); yield reg('reg/addr', 'i32'); yield reg('reg/i32/1', 'i32'); yield reg('reg/i32/2', 'i32'); yield reg('reg/f64/1', 'f64'); yield reg('reg/f64/2', 'f64'); } function* codegenStartFunc(ctx: CodegenContext): Iterable<SExp> { if (ctx.globalInitializers.length === 0) { return; } const funcE = exp('func', sys('start')); for (const { watName, expr } of ctx.globalInitializers) { funcE.push(...codegenExpr(expr, ctx)); funcE.push(exp('set_global', wat(watName))); } yield funcE; yield exp('start', sys('start')); } function codegenGlobalDecl(decl: a.Decl, ctx: CodegenContext): SExp | null { const expr = decl.value.expr; if (expr instanceof a.FuncExpr) { return codegenFunction(decl.value.name.value, decl.value.expr, ctx); } else if (expr instanceof a.IdentExpr && expr.type instanceof a.FuncType) { // function name alias ctx.pushAlias(decl.value.name.value, expr.value.value); return null; } else { return codegenGlobalVar(decl, ctx); } } function codegenFunction( origName: string, func: a.FuncExpr, ctx: CodegenContext, ): SExp { const name = ctx.pushName(origName); const funcE = exp('func', wat(name)); ctx.enterFunction(); for (const param of func.value.params.items) { funcE.push( exp( 'param', wat(ctx.pushName(param.name.value)), codegenType(param.type, ctx), ), ); } funcE.push(exp('result', codegenType(func.value.returnType, ctx))); funcE.push(...codegenBlock(func.value.body, true, ctx)); ctx.leaveFunction(); return funcE; } function codegenType(ty: a.Type<any>, ctx: CodegenContext): string { if (ty instanceof a.IntType) { return 'i32'; } else if (ty instanceof a.FloatType) { return 'f64'; } else if (ty instanceof a.BoolType) { return 'i32'; // 0 or 1 } else if (ty instanceof a.CharType) { return 'i32'; // ascii } else if (ty instanceof a.VoidType) { return ''; } else { return 'i32'; // memory offset } } function getByteSizeOfType(ty: a.Type<any>): number { if (ty instanceof a.FloatType) { return 8; } else if (ty instanceof a.VoidType) { return 0; } else { return 4; } } function* codegenBlock( block: a.Block, isFunction: boolean, ctx: CodegenContext, ): Iterable<SExp> { if (isFunction) { yield* codegenLocalVarDef(block, ctx); ctx.resetScopeID(); } else { ctx.enterBlock(); } for (const body of block.value.bodies) { if (body instanceof a.Expr) { // expr yield* codegenExpr(body, ctx); } else if (body instanceof a.Decl) { // local decl yield* codegenLocalVarDecl(body, ctx); } else if (body instanceof a.Assign) { // assignment yield* codegenAssign(body, ctx); } else { // break yield codegenBreak(body, ctx); } } if (isFunction) { yield exp('return'); } else { ctx.leaveBlock(); } } function codegenBlockType(block: a.Block, ctx: CodegenContext): string { if (block.value.returnVoid) { return ''; } else { // the last body should be an expr; const lastExpr: a.Expr<any> = block.value.bodies[ block.value.bodies.length - 1 ] as any; return codegenType(lastExpr.type!, ctx); } } function* codegenExpr(expr: a.Expr<any>, ctx: CodegenContext): Iterable<SExp> { if (expr instanceof a.LitExpr) { yield codegenLiteral(expr.value, ctx); } else if (expr instanceof a.IdentExpr) { yield codegenIdent(expr.value, ctx); } else if (expr instanceof a.CallExpr) { yield* codegenCallExpr(expr, ctx); } else if (expr instanceof a.UnaryExpr) { yield* codegenUnaryExpr(expr, ctx); } else if (expr instanceof a.BinaryExpr) { yield* codegenBinaryExpr(expr, ctx); } else if (expr instanceof a.CondExpr) { yield* codegenCondExpr(expr, ctx); } else if (expr instanceof a.TupleExpr) { yield* codegenTupleExpr(expr, ctx); } else if (expr instanceof a.ArrayExpr) { yield* codegenArrayExpr(expr, ctx); } else if (expr instanceof a.IndexExpr) { yield* codegenIndexExpr(expr, ctx); } else if (expr instanceof a.NewExpr) { yield* codegenNewExpr(expr, ctx); } else if (expr instanceof a.LoopExpr) { yield codegenLoopExpr(expr, ctx); } } function codegenLiteral(lit: a.Literal<any>, ctx: CodegenContext): SExp { if (lit instanceof a.IntLit) { return exp('i32.const', String(lit.value)); } else if (lit instanceof a.FloatLit) { const rep = lit.value.startsWith('.') ? '0' + lit.value : lit.value; return exp('f64.const', rep); } else if (lit instanceof a.StrLit) { // TODO: string literal return exp('i32.const', '0'); } else if (lit instanceof a.CharLit) { return exp('i32.const', String(lit.parsedValue.codePointAt(0))); } else if (lit instanceof a.BoolLit) { return exp('i32.const', lit.parsedValue ? '1' : '0'); } else { return exp('unreachable'); } } function codegenInitialValForType(lit: a.Type<any>, ctx: CodegenContext): SExp { if (lit instanceof a.IntType) { return exp('i32.const', '0'); } else if (lit instanceof a.FloatType) { return exp('f64.const', '0'); } else if (lit instanceof a.CharType) { return exp('i32.const', '0'); } else if (lit instanceof a.BoolType) { return exp('i32.const', '0'); } else { // memory address return exp('i32.const', '0'); } } function codegenIdent(ident: a.Ident, ctx: CodegenContext): SExp { let name = ctx.getLocalWATName(ident.value); if (name) { return exp('get_local', wat(name)); } else { name = ctx.getGlobalWATName(ident.value)!; return exp('get_global', wat(name)); } } function* codegenCallExpr( call: a.CallExpr, ctx: CodegenContext, ): Iterable<SExp> { if (!(call.value.func instanceof a.IdentExpr)) { // do not support return; } if (call.value.args instanceof a.TupleExpr) { for (const arg of call.value.args.value.items) { yield* codegenExpr(arg, ctx); } } else { yield* codegenExpr(call.value.args, ctx); } const funcName = ctx.getGlobalWATName(call.value.func.value.value); if (typeof funcName === 'string') { yield exp('call', wat(funcName)); } else { // must be stdlib const stdFunc = ctx.getStdFunc(call.value.func.value.value)!; if (stdFunc.expr) { yield* stdFunc.expr; } } } function* codegenUnaryExpr( unary: a.UnaryExpr, ctx: CodegenContext, ): Iterable<SExp> { const op = unary.value.op; const right = unary.value.right; // used for '-' let ty = codegenType(right.type!, ctx); if (op.value === '-') { yield exp(`${ty}.const`, '0'); } yield* codegenExpr(right, ctx); if (op.value === '-') { yield exp(`${ty}.sub`); } else if (op.value === '!') { yield exp('i32.eqz'); } // '+' should be removed already in desugarer, no need to handle } function* codegenBinaryExpr( binary: a.BinaryExpr, ctx: CodegenContext, ): Iterable<SExp> { const op = binary.value.op; const left = binary.value.left; const right = binary.value.right; const ty = codegenType(right.type!, ctx); const signed = ty === 'i32' ? '_s' : ''; switch (op.value) { case '==': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp(`${ty}.eq`); break; case '!=': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp(`${ty}.ne`); break; case '<': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp(`${ty}.lt${signed}`); break; case '<=': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp(`${ty}.le${signed}`); break; case '>': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp(`${ty}.gt${signed}`); break; case '>=': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp(`${ty}.ge${signed}`); break; case '+': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp(`${ty}.add`); break; case '-': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp(`${ty}.sub`); break; case '^': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp('i32.xor'); break; case '&': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp('i32.and'); break; case '|': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp('i32.or'); break; case '*': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp(`${ty}.mul`); break; case '/': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp(`${ty}.div${signed}`); break; case '%': yield* codegenExpr(left, ctx); yield* codegenExpr(right, ctx); yield exp('i32.rem_s'); break; case '&&': // for short circuit evaluation yield* codegenExpr(left, ctx); yield exp( 'if', exp('result', 'i32'), exp('then', ...codegenExpr(right, ctx)), exp('else', exp('i32.const', '0')), ); break; case '||': // for short circuit evaluation yield* codegenExpr(left, ctx); yield exp( 'if', exp('result', 'i32'), exp('then', exp('i32.const', '1')), exp('else', ...codegenExpr(right, ctx)), ); break; } } function* codegenCondExpr( cond: a.CondExpr, ctx: CodegenContext, ): Iterable<SExp> { yield* codegenExpr(cond.value.if, ctx); yield exp( 'if', exp('result', codegenBlockType(cond.value.then, ctx)), exp('then', ...codegenBlock(cond.value.then, false, ctx)), exp('else', ...codegenBlock(cond.value.else, false, ctx)), ); } function* codegenGetCurrentHeapPointer(): Iterable<SExp> { yield exp('i32.const', '0'); yield exp('i32.load'); } function* codegenSetCurrentHeapPointer(): Iterable<SExp> { yield exp('i32.const', '0'); yield* codegenSwapStackTop('i32'); yield exp('i32.store'); } function* codegenSwapStackTop(ty1: string, ty2: string = ty1): Iterable<SExp> { yield exp('set_global', sys(`reg/${ty1}/1`)); yield exp('set_global', sys(`reg/${ty2}/2`)); yield exp('get_global', sys(`reg/${ty1}/1`)); yield exp('get_global', sys(`reg/${ty2}/2`)); } function* codegenMemoryAllocation(size?: number): Iterable<SExp> { if (typeof size === 'number') { yield exp('i32.const', String(size)); } yield* codegenGetCurrentHeapPointer(); yield exp('set_global', sys('reg/addr')); yield exp('get_global', sys('reg/addr')); yield exp('i32.add'); yield* codegenSetCurrentHeapPointer(); yield exp('get_global', sys('reg/addr')); } function* codegenTupleExpr( tuple: a.TupleExpr, ctx: CodegenContext, ): Iterable<SExp> { if (tuple.value.size === 0) { yield exp('i32.const', '0'); return; } for (let i = 0; i < tuple.value.size; i++) { const expr = tuple.value.items[i]; yield* codegenExpr(expr, ctx); } const tupleTy: a.TupleType = tuple.type as any; const types = tupleTy.value.items.map(ty => codegenType(ty, ctx)); const sizes = tupleTy.value.items.map(getByteSizeOfType); const constName = ctx.useTupleConstructor(types, sizes); yield exp('call', sys(constName)); } function* codegenArrayExpr( array: a.ArrayExpr, ctx: CodegenContext, ): Iterable<SExp> { const arrTy = array.type! as a.ArrayType; const ty = codegenType(arrTy.value, ctx); const size = getByteSizeOfType(arrTy.value); const len = array.value.length; yield* codegenMemoryAllocation(4 + size * len); yield exp('set_global', sys('reg/i32/1')); for (let i = 0; i < len + 2; i++) { // prepare for set // +2: +1 to store length, +1 to return yield exp('get_global', sys('reg/i32/1')); } // store length let offset = 4; yield exp('i32.const', String(len)); yield exp('i32.store'); yield exp('i32.const', String(offset)); yield exp('i32.add'); // store values for (let i = 0; i < len; i++) { yield* codegenExpr(array.value[i], ctx); yield exp(`${ty}.store`); if (i < len - 1) { offset += size; yield exp('i32.const', String(offset)); yield exp('i32.add'); } } } function codegenTupleConstructor( name: string, types: Array<string>, sizes: Array<number>, ): SExp { const funcE = exp('func', sys(name)); for (let i = 0; i < types.length; i++) { funcE.push(exp('param', types[i])); } funcE.push(exp('result', 'i32')); const offset = wat('offset'); funcE.push(exp('local', wat('offset'), 'i32')); funcE.push(...codegenMemoryAllocation(sizes.reduce((x, y) => x + y))); funcE.push(exp('set_local', offset)); funcE.push(exp('get_local', offset)); // this becomes return value for (let i = 0; i < types.length; i++) { funcE.push(exp('get_local', offset)); funcE.push(exp('get_local', String(i))); funcE.push(exp(`${types[i]}.store`)); // calculate next offset funcE.push(exp('get_local', offset)); funcE.push(exp('i32.const', String(sizes[i]))); funcE.push(exp('i32.add')); funcE.push(exp('set_local', offset)); } return funcE; } function getTupleIdx(expr: a.IndexExpr): number { // The index of a tuple expr should be an int literal const idxLit: a.IntLit = expr.value.index.value as any; return idxLit.parsedValue; } function* codegenTupleAddr( target: a.Expr<any>, idx: number, ctx: CodegenContext, ): Iterable<SExp> { yield* codegenExpr(target, ctx); const tupleTy = target.type! as a.TupleType; let offset = 0; for (let i = 0; i < idx; i++) { offset += getByteSizeOfType(tupleTy.value.items[i]); } yield exp('i32.const', String(offset)); yield exp('i32.add'); } function* codegenArrayAddr( target: a.Expr<any>, index: a.Expr<any>, byteSize: number, ctx: CodegenContext, ): Iterable<SExp> { yield* codegenExpr(target, ctx); yield exp('i32.const', '4'); yield exp('i32.add'); yield* codegenExpr(index, ctx); yield exp('i32.const', String(byteSize)); yield exp('i32.mul'); yield exp('i32.add'); } function* codegenIndexExpr( expr: a.IndexExpr, ctx: CodegenContext, ): Iterable<SExp> { const target = expr.value.target; if (target.type instanceof a.ArrayType) { const byteSize = getByteSizeOfType(target.type.value); yield* codegenArrayAddr(target, expr.value.index, byteSize, ctx); const ty = codegenType(target.type.value, ctx); yield exp(`${ty}.load`); } else if (target.type instanceof a.TupleType) { const idx = getTupleIdx(expr); yield* codegenTupleAddr(target, idx, ctx); const ty = codegenType(target.type.value.items[idx], ctx); yield exp(`${ty}.load`); } } function* codegenNewExpr(expr: a.NewExpr, ctx: CodegenContext): Iterable<SExp> { const size = getByteSizeOfType(expr.value.type); yield* codegenExpr(expr.value.length, ctx); yield exp('set_global', sys('reg/i32/1')); yield exp('get_global', sys('reg/i32/1')); yield exp('get_global', sys('reg/i32/1')); yield exp('i32.const', String(size)); yield exp('i32.mul'); yield exp('i32.const', '4'); yield exp('i32.add'); yield* codegenMemoryAllocation(); yield exp('set_global', sys('reg/addr')); yield exp('get_global', sys('reg/addr')); yield* codegenSwapStackTop('i32'); yield exp('i32.store'); yield exp('get_global', sys('reg/addr')); } function codegenLoopExpr(expr: a.LoopExpr, ctx: CodegenContext): SExp { return exp( 'block', exp( 'loop', ...codegenExpr(expr.value.while, ctx), exp( 'if', exp( 'then', ...codegenBlock(expr.value.body, false, ctx), exp('br', '1'), ), ), ), ); } function* codegenLocalVarDef( block: a.Block, ctx: CodegenContext, ): Iterable<SExp> { for (const body of block.value.bodies) { if (body instanceof a.Decl) { const origName = body.value.name.value; const expr = body.value.expr; // ignore function alias if (expr instanceof a.IdentExpr && expr.type instanceof a.FuncType) { continue; } const name = ctx.convertLocalName(origName); yield exp('local', wat(name), codegenType(expr.type!, ctx)); } else if (body instanceof a.CondExpr) { ctx.enterBlock(); yield* codegenLocalVarDef(body.value.then, ctx); ctx.leaveBlock(); ctx.enterBlock(); yield* codegenLocalVarDef(body.value.else, ctx); ctx.leaveBlock(); } else if (body instanceof a.LoopExpr) { ctx.enterBlock(); yield* codegenLocalVarDef(body.value.body, ctx); ctx.leaveBlock(); } } } function* codegenLocalVarDecl( decl: a.Decl, ctx: CodegenContext, ): Iterable<SExp> { const origName = decl.value.name.value; const expr = decl.value.expr; if (expr instanceof a.IdentExpr && expr.type instanceof a.FuncType) { ctx.pushAlias(origName, ctx.getGlobalWATName(expr.value.value)!); } else { yield* codegenExpr(expr, ctx); const name = ctx.pushName(origName); yield exp('set_local', wat(name)); } } function codegenGlobalVar(decl: a.Decl, ctx: CodegenContext): SExp { const name = ctx.getGlobalWATName(decl.value.name.value)!; const varE = exp('global', wat(name)); const expr = decl.value.expr; varE.push(exp('mut', codegenType(expr.type!, ctx))); if (expr instanceof a.LitExpr) { varE.push(...codegenLiteral(expr.value, ctx)); } else { varE.push(codegenInitialValForType(expr.type!, ctx)); ctx.pushInitializer(name, expr); } return varE; } function* codegenAssign(assign: a.Assign, ctx: CodegenContext): Iterable<SExp> { yield* codegenExpr(assign.value.expr, ctx); const lVal = assign.value.lVal; if (lVal instanceof a.IdentExpr) { // ident const ident = lVal.value; let name = ctx.getLocalWATName(ident.value); if (name) { yield exp('set_local', wat(name)); } else { name = ctx.getGlobalWATName(ident.value)!; yield exp('set_global', wat(name)); } } else { // index expr const target = lVal.value.target; if (target.type instanceof a.ArrayType) { const byteSize = getByteSizeOfType(target.type.value); yield* codegenArrayAddr(target, lVal.value.index, byteSize, ctx); const ty = codegenType(target.type.value, ctx); yield* codegenSwapStackTop('i32', ty); yield exp(`${ty}.store`); } else if (target.type instanceof a.TupleType) { const idx = getTupleIdx(lVal); yield* codegenTupleAddr(target, idx, ctx); const ty = codegenType(target.type.value.items[idx], ctx); yield* codegenSwapStackTop('i32', ty); yield exp(`${ty}.store`); } } } function codegenBreak(break_: a.Break, ctx: CodegenContext): SExp { return exp('br', '1'); }
the_stack
import { URL_SOUND_LIST_CONVERSATION } from './../chat21-core/utils/constants'; import { ArchivedConversationsHandlerService } from 'src/chat21-core/providers/abstract/archivedconversations-handler.service'; import { AppStorageService } from 'src/chat21-core/providers/abstract/app-storage.service'; import { Component, ViewChild, NgZone, OnInit, HostListener, ElementRef, Renderer2, } from '@angular/core'; import { Config, Platform, IonRouterOutlet, IonSplitPane, NavController, MenuController, AlertController, IonNav, ToastController } from '@ionic/angular'; import { ActivatedRoute, NavigationStart, Router } from '@angular/router'; import { Subscription, VirtualTimeScheduler } from 'rxjs'; import { ModalController } from '@ionic/angular'; // import * as firebase from 'firebase/app'; import firebase from "firebase/app"; import 'firebase/auth'; // nk in watch connection status import { StatusBar } from '@ionic-native/status-bar/ngx'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { TranslateService } from '@ngx-translate/core'; // services import { AppConfigProvider } from './services/app-config'; // import { UserService } from './services/user.service'; // import { CurrentUserService } from './services/current-user/current-user.service'; import { EventsService } from './services/events-service'; import { MessagingAuthService } from '../chat21-core/providers/abstract/messagingAuth.service'; import { PresenceService } from '../chat21-core/providers/abstract/presence.service'; import { TypingService } from '../chat21-core/providers/abstract/typing.service'; import { UploadService } from '../chat21-core/providers/abstract/upload.service'; // import { ChatPresenceHandler} from './services/chat-presence-handler'; import { NavProxyService } from './services/nav-proxy.service'; import { ChatManager } from 'src/chat21-core/providers/chat-manager'; // import { ChatConversationsHandler } from './services/chat-conversations-handler'; import { ConversationsHandlerService } from 'src/chat21-core/providers/abstract/conversations-handler.service'; import { CustomTranslateService } from 'src/chat21-core/providers/custom-translate.service'; // pages import { LoginPage } from './pages/authentication/login/login.page'; import { ConversationListPage } from './pages/conversations-list/conversations-list.page'; // utils import { createExternalSidebar, checkPlatformIsMobile, isGroup, getParameterByName } from '../chat21-core/utils/utils'; import { STORAGE_PREFIX, PLATFORM_MOBILE, PLATFORM_DESKTOP, CHAT_ENGINE_FIREBASE, AUTH_STATE_OFFLINE, AUTH_STATE_ONLINE } from '../chat21-core/utils/constants'; import { environment } from '../environments/environment'; import { UserModel } from '../chat21-core/models/user'; import { ConversationModel } from 'src/chat21-core/models/conversation'; import { LoggerService } from 'src/chat21-core/providers/abstract/logger.service'; import { LoggerInstance } from 'src/chat21-core/providers/logger/loggerInstance'; import { TiledeskAuthService } from 'src/chat21-core/providers/tiledesk/tiledesk-auth.service'; // FCM import { NotificationsService } from 'src/chat21-core/providers/abstract/notifications.service'; import { getImageUrlThumbFromFirebasestorage } from 'src/chat21-core/utils/utils-user'; // import { Network } from '@ionic-native/network/ngx'; // import { Observable, Observer, fromEvent, merge, of } from 'rxjs'; // import { mapTo } from 'rxjs/operators'; import { TiledeskService } from './services/tiledesk/tiledesk.service'; import { NetworkService } from './services/network-service/network.service'; import * as PACKAGE from 'package.json'; import { Subject } from 'rxjs'; import { filter, takeUntil } from 'rxjs/operators' // import { filter } from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: 'app.component.html', styleUrls: ['app.component.scss'] }) export class AppComponent implements OnInit { @ViewChild('sidebarNav', { static: false }) sidebarNav: IonNav; @ViewChild('detailNav', { static: false }) detailNav: IonRouterOutlet; // public appIsOnline$: Observable<boolean> = undefined; checkInternet: boolean; private subscription: Subscription; public sidebarPage: any; public notificationsEnabled: boolean; public zone: NgZone; private platformIs: string; private doitResize: any; private timeModalLogin: any; public tenant: string; public persistence: string; public authModal: any; private audio: any; private setIntervalTime: any; private setTimeoutSound: any; private isTabVisible: boolean = true; private tabTitle: string; private logger: LoggerService = LoggerInstance.getInstance(); public toastMsgErrorWhileUnsubscribingFromNotifications: string; public toastMsgCloseToast: string; public toastMsgWaitingForNetwork: string; private modalOpen: boolean = false; private hadBeenCalledOpenModal: boolean = false; public missingConnectionToast: any public executedInitializeAppByWatchConnection: boolean = false; private version: string; private unsubscribe$: Subject<any> = new Subject<any>(); private isOnline: boolean = false; constructor( private platform: Platform, private splashScreen: SplashScreen, private statusBar: StatusBar, private appConfigProvider: AppConfigProvider, private events: EventsService, public config: Config, public chatManager: ChatManager, public translate: TranslateService, public alertController: AlertController, public navCtrl: NavController, // public userService: UserService, // public currentUserService: CurrentUserService, public modalController: ModalController, public messagingAuthService: MessagingAuthService, public tiledeskAuthService: TiledeskAuthService, public presenceService: PresenceService, private router: Router, private route: ActivatedRoute, private renderer: Renderer2, private navService: NavProxyService, // public chatPresenceHandler: ChatPresenceHandler, public typingService: TypingService, public uploadService: UploadService, public appStorageService: AppStorageService, // public chatConversationsHandler: ChatConversationsHandler, public conversationsHandlerService: ConversationsHandlerService, public archivedConversationsHandlerService: ArchivedConversationsHandlerService, private translateService: CustomTranslateService, public notificationsService: NotificationsService, public toastController: ToastController, // private network: Network, // private tiledeskService: TiledeskService, private networkService: NetworkService ) { this.logger.log('[APP-COMP] HELLO Constuctor !!!!!!!') // HACK: fix toast not presented when offline, due to lazy loading the toast controller. // this.toastController.create({ animated: false }).then(t => { // console.log('[APP-COMP] toastController create') // t.present(); // t.dismiss(); // }); } param() { // PARAM const url: URL = new URL(window.top.location.href); const params: URLSearchParams = url.searchParams; return params; } /** */ ngOnInit() { const appconfig = this.appConfigProvider.getConfig(); this.persistence = appconfig.authPersistence; this.appStorageService.initialize(environment.storage_prefix, this.persistence, '') this.logger.log('[APP-COMP] HELLO ngOnInit !!!!!!!') this.logger.info('[APP-COMP] ngOnInit this.route.snapshot.params -->', this.route.snapshot.params); // this.initializeApp('oninit'); const token = getParameterByName('jwt') this.logger.info('[APP-COMP] ngOnInit token get from params -->', token); if (token) { this.isOnline = false; this.logger.log('[APP-COMP] AUTLOGIN > RUN SIGNINWITHCUSTOMTOKEN params ', token) // save token in local storage then this.appStorageService.setItem('tiledeskToken', token); } this.initializeApp('oninit'); // else { // this.isOnline = false; // this.logger.log('[APP-COMP] NO AUTLOGIN > RUN INIZIALIZE APP') // this.initializeApp('oninit'); // } // const param = this.param(); // const token: string = param.get("jwt"); // this.logger.info('[APP-COMP] ngOnInit token geet from params -->', token); // this.subscription = this.router.events.subscribe((event) => { // if (event instanceof NavigationStart) { // const current_url = event.url // this.logger.info('[APP-COMP] - NavigationStart event current_url ', current_url); // if (current_url.includes('jwt')) { // this.logger.info('[APP-COMP] - NavigationStart event current_url INCLUDES jwt'); // const tokenString = current_url.slice(current_url.lastIndexOf('=') + 1) // // const token = tokenString.substring(1, tokenString.length - 1) // const token = tokenString // this.logger.info('[APP-COMP] - NavigationStart event current_url INCLUDES jwt > token ', token); // this.signInWithCustomToken("JWT%20eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MDhhZDAyZDNhNGRjMDAwMzQ0YWRlMTciLCJlbWFpbCI6Im51b3ZvcHJlZ2lub0BtYWlsbmEuY28iLCJmaXJzdG5hbWUiOiJOdW92byIsImxhc3RuYW1lIjoiUHJlZ2lubyIsImVtYWlsdmVyaWZpZWQiOnRydWUsImlhdCI6MTYzNDE5OTU1NiwiYXVkIjoiaHR0cHM6Ly90aWxlZGVzay5jb20iLCJpc3MiOiJodHRwczovL3RpbGVkZXNrLmNvbSIsInN1YiI6InVzZXIiLCJqdGkiOiIwMGQyNTI0MS05MDI4LTRmYTYtYmJhNi0xOGNmZTUwNzdiYTMifQ.4kCuHOyceIMWnlyOiCvQEiDPqDZR8HwYgyQoqMYJxX0") // } else { // this.logger.info('[APP-COMP] - NavigationStart event current_url NOT INCLUDES jwt'); // } // } // }); // this.route.queryParams.subscribe(params => { // this.logger.log('[APP-COMP] ROUTE QUERY PARAMS params', params) // if (params.jwt) { // this.isOnline = false; // this.logger.log('[APP-COMP] AUTLOGIN > RUN SIGNINWITHCUSTOMTOKEN params ', params) // this.tiledeskAuthService.signInWithCustomToken(params.jwt).then(user => { // this.logger.log('[APP-COMP] AUTLOGIN > RUN SIGNINWITHCUSTOMTOKEN user', user) // // if (user) { // this.logger.log('[APP-COMP] AUTLOGIN > RUN INIZIALIZE APP') // this.initializeApp('oninit'); // // } // this.messagingAuthService.createCustomToken(params.jwt) // }).catch(error => { // this.logger.error('[APP-COMP] AUTLOGIN > RUN SIGNINWITHCUSTOMTOKE - ERROR', error) // }) // } // else { // this.isOnline = false; // this.logger.log('[APP-COMP] NO AUTLOGIN > RUN INIZIALIZE APP') // this.initializeApp('oninit'); // } // }); } signInWithCustomToken(token) { this.isOnline = false; this.logger.log('[APP-COMP] SIGNINWITHCUSTOMTOKEN AUTLOGIN token', token) this.tiledeskAuthService.signInWithCustomToken(token) .then((user: any) => { this.logger.log('[APP-COMP] SIGNINWITHCUSTOMTOKEN AUTLOGIN user', user) this.messagingAuthService.createCustomToken(token) }) .catch(error => { this.logger.error('[APP-COMP] SIGNINWITHCUSTOMTOKEN error::', error) }) } /** */ initializeApp(calledby: string) { this.logger.info('[APP-COMP] - initializeApp !!! CALLED-BY: ', calledby); this.logger.log('[APP-COMP] appconfig platform is cordova: ', this.platform.is('cordova')) if (!this.platform.is('cordova')) { this.splashScreen.show(); } this.tabTitle = document.title; this.getRouteParamsAndSetLoggerConfig(); const appconfig = this.appConfigProvider.getConfig(); this.logger.info('[APP-COMP] appconfig: ', appconfig) this.version = PACKAGE.version; this.logger.info('[APP-COMP] version: ', this.version) this.logger.setLoggerConfig(true, appconfig.logLevel) this.logger.info('[APP-COMP] logLevel: ', appconfig.logLevel); this.tenant = appconfig.firebaseConfig.tenant; this.logger.info('[APP-COMP] appconfig firebaseConfig tenant: ', this.tenant); this.notificationsEnabled = true; this.zone = new NgZone({}); // a cosa serve? this.platform.ready().then(() => { this.setLanguage(); if (this.splashScreen) { this.splashScreen.hide(); } this.statusBar.styleDefault(); this.navService.init(this.sidebarNav, this.detailNav); // this.persistence = appconfig.authPersistence; // this.appStorageService.initialize(environment.storage_prefix, this.persistence, '') this.tiledeskAuthService.initialize(this.appConfigProvider.getConfig().apiUrl); this.messagingAuthService.initialize(); // this.currentUserService.initialize(); this.chatManager.initialize(); this.presenceService.initialize(this.tenant); this.typingService.initialize(this.tenant); const pushEngine = this.appConfigProvider.getConfig().pushEngine const vap_id_Key = this.appConfigProvider.getConfig().firebaseConfig.vapidKey if (pushEngine && pushEngine !== 'none') { this.notificationsService.initialize(this.tenant, vap_id_Key) } this.uploadService.initialize(); this.initAuthentication(); this.initSubscriptions(); this.initAudio() this.logger.debug('[APP-COMP] initializeApp:: ', this.sidebarNav, this.detailNav); // this.listenToLogoutEvent() this.translateToastMsgs(); // --------------------------------------- // Watch to network status // --------------------------------------- this.watchToConnectionStatus(); // this.listenToUserIsSignedIn(); }); } // listenToUserIsSignedIn() { // this.tiledeskAuthService.isOnline$ // .pipe(filter((isOnline) => isOnline !== null)) // .subscribe((isOnline: any) => { // console.log('[APP-COMP] user isOnline: ', isOnline); // // if (isOnline === false) { // // this.events.publish('profileInfoButtonClick:logout', true); // // } // }); // } watchToConnectionStatus() { this.networkService.checkInternetFunc().subscribe(isOnline => { this.checkInternet = isOnline this.logger.log('[APP-COMP] - watchToConnectionStatus - isOnline', this.checkInternet) // checking internet connection if (this.checkInternet == true) { // this.events.publish('internetisonline', true); // show success alert if internet is working // alert('Internet is working.') this.logger.log('[APP-COMP] - watchToConnectionStatus - Internet is working.') // this.logger.log('[APP-COMP] - watchToConnectionStatus - this.missingConnectionToast', this.missingConnectionToast) if (!checkPlatformIsMobile()) { const elemIonNav = <HTMLElement>document.querySelector('ion-nav'); this.logger.log('[APP-COMP] - watchToConnectionStatus - desktop * elemIonNav *', elemIonNav) if (this.executedInitializeAppByWatchConnection === false) { setTimeout(() => { const elemIonNavchildNodes = elemIonNav.childNodes; this.logger.log('[APP-COMP] - watchToConnectionStatus - elemIonNavchildNodes ', elemIonNavchildNodes); if (elemIonNavchildNodes.length === 0) { this.logger.log('[APP-COMP] - watchToConnectionStatus - elemIonNavchildNodes HERE YES', elemIonNavchildNodes); this.initializeApp('checkinternet'); this.executedInitializeAppByWatchConnection = true; } }, 2000); } } else if (checkPlatformIsMobile()) { this.logger.log('[APP-COMP] - watchToConnectionStatus - mobile ') const elemIonRouterOutlet = <HTMLElement>document.querySelector('ion-router-outlet'); this.logger.log('[APP-COMP] - watchToConnectionStatus - mobile * elemIonRouterOutlet *', elemIonRouterOutlet) if (this.executedInitializeAppByWatchConnection === false) { setTimeout(() => { const childElementCount = elemIonRouterOutlet.childElementCount; this.logger.log('[APP-COMP] - watchToConnectionStatus - mobile * childElementCount *', childElementCount) if (childElementCount === 1) { this.initializeApp('checkinternet'); this.executedInitializeAppByWatchConnection = true; } }, 2000); } } } else { this.logger.log('[APP-COMP] - watchToConnectionStatus - Internet is slow or not working.'); } }); } getRouteParamsAndSetLoggerConfig() { const appconfig = this.appConfigProvider.getConfig(); this.route.queryParams.subscribe(params => { this.logger.info('[APP-COMP] getRouteParamsAndSetLoggerConfig - queryParams params: ', params) if (params.logLevel) { this.logger.info('[APP-COMP] getRouteParamsAndSetLoggerConfig - log level get from queryParams: ', params.logLevel) this.logger.setLoggerConfig(true, params.logLevel) } else { this.logger.info('[APP-COMP] getRouteParamsAndSetLoggerConfig - log level get from appconfig: ', appconfig.logLevel) this.logger.setLoggerConfig(true, appconfig.logLevel) } }); } translateToastMsgs() { this.translate.get('AnErrorOccurredWhileUnsubscribingFromNotifications') .subscribe((text: string) => { this.toastMsgErrorWhileUnsubscribingFromNotifications = text; }); this.translate.get('CLOSE_TOAST') .subscribe((text: string) => { this.toastMsgCloseToast = text; }); this.translate.get('WAITING_FOR_NETWORK') .subscribe((text: string) => { this.toastMsgWaitingForNetwork = text; }); } /***************************************************+*/ /**------- AUTHENTICATION FUNCTIONS --> START <--- +*/ private initAuthentication() { const tiledeskToken = this.appStorageService.getItem('tiledeskToken') this.logger.log('[APP-COMP] >>> INIT-AUTHENTICATION !!! ') this.logger.log('[APP-COMP] >>> initAuthentication tiledeskToken ', tiledeskToken) const currentUser = JSON.parse(this.appStorageService.getItem('currentUser')); this.logger.log('[APP-COMP] >>> initAuthentication currentUser ', currentUser) if (tiledeskToken) { this.logger.log('[APP-COMP] >>> initAuthentication I LOG IN WITH A TOKEN EXISTING IN THE LOCAL STORAGE OR WITH A TOKEN PASSED IN THE URL PARAMETERS <<<') this.tiledeskAuthService.signInWithCustomToken(tiledeskToken).then(user => { this.logger.log('[APP-COMP] >>> initAuthentication user ', user) this.messagingAuthService.createCustomToken(tiledeskToken) }).catch(error => { this.logger.error('[APP-COMP] initAuthentication SIGNINWITHCUSTOMTOKEN error::' + error) }) } else { this.logger.warn('[APP-COMP] >>> I AM NOT LOGGED IN <<<') const that = this; clearTimeout(this.timeModalLogin); this.timeModalLogin = setTimeout(() => { if (!this.hadBeenCalledOpenModal) { this.authModal = this.presentModal('initAuthentication'); this.hadBeenCalledOpenModal = true; } }, 1000); } // this.route.queryParams.subscribe(params => { // this.logger.log('[APP-COMP] SIGNINWITHCUSTOMTOKEN AUTLOGIN params 1', params) // if (params.jwt) { // this.isOnline = false; // this.logger.log('[APP-COMP] SIGNINWITHCUSTOMTOKEN AUTLOGIN params 2', params) // this.tiledeskAuthService.signInWithCustomToken(params.jwt).then(user => { // this.messagingAuthService.createCustomToken(params.jwt) // }).catch(error => { // this.logger.error('[APP-COMP] SIGNINWITHCUSTOMTOKEN error::', error) // }) // } // }); } authenticate() { let token = this.appStorageService.getItem('tiledeskToken'); this.logger.info('[APP-COMP] ***** authenticate - stored token *****', token); if (!token) { this.goOffLine() } } /** * goOnLine: * 1 - nascondo splashscreen * 2 - recupero il tiledeskToken e lo salvo in chat manager * 3 - carico in d * @param user */ goOnLine = () => { this.isOnline = true; this.logger.info('initialize FROM [APP-COMP] - [APP-COMP] - GO ONLINE isOnline ', this.isOnline); clearTimeout(this.timeModalLogin); const tiledeskToken = this.tiledeskAuthService.getTiledeskToken(); const currentUser = this.tiledeskAuthService.getCurrentUser(); // this.logger.printDebug('APP-COMP - goOnLine****', currentUser); this.logger.log('[APP-COMP] - goOnLine****', currentUser); this.chatManager.setTiledeskToken(tiledeskToken); this.chatManager.setCurrentUser(currentUser); // ---------------------------------------------- // PUSH NOTIFICATIONS // ---------------------------------------------- const pushEngine = this.appConfigProvider.getConfig().pushEngine if (currentUser) { if (pushEngine && pushEngine !== 'none') { this.notificationsService.getNotificationPermissionAndSaveToken(currentUser.uid); } this.presenceService.setPresence(currentUser.uid); this.initConversationsHandler(currentUser.uid); this.initArchivedConversationsHandler(currentUser.uid); } this.checkPlatform(); try { this.logger.debug('[APP-COMP] ************** closeModal', this.authModal); if (this.authModal) { this.closeModal(); } } catch (err) { this.logger.error('[APP-COMP] -> error:', err); } this.chatManager.startApp(); } goOffLine = () => { this.logger.log('[APP-COMP] ************** goOffLine:', this.authModal); this.isOnline = false; // this.conversationsHandlerService.conversations = []; this.chatManager.setTiledeskToken(null); this.chatManager.setCurrentUser(null); this.chatManager.goOffLine(); this.router.navigateByUrl('conversation-detail/'); //redirect to basePage const that = this; clearTimeout(this.timeModalLogin); this.timeModalLogin = setTimeout(() => { if (!this.hadBeenCalledOpenModal) { this.authModal = this.presentModal('goOffLine'); this.hadBeenCalledOpenModal = true } }, 1000); // this.unsubscribe$.next(); // this.unsubscribe$.complete(); } /**------- AUTHENTICATION FUNCTIONS --> END <--- +*/ /***************************************************+*/ /** */ setLanguage() { this.translate.setDefaultLang('en'); this.translate.use('en'); this.logger.debug('[APP-COMP] navigator.language: ', navigator.language); let language; if (navigator.language.indexOf('-') !== -1) { language = navigator.language.substring(0, navigator.language.indexOf('-')); } else if (navigator.language.indexOf('_') !== -1) { language = navigator.language.substring(0, navigator.language.indexOf('_')); } else { language = navigator.language; } this.translate.use(language); } checkPlatform() { this.logger.debug('[APP-COMP] checkPlatform'); // let pageUrl = ''; // try { // const pathPage = this.route.snapshot.firstChild.routeConfig.path; // this.route.snapshot.firstChild.url.forEach(element => { // pageUrl += '/' + element.path; // }); // } catch (error) { // this.logger.debug('error', error); // } // this.logger.debug('checkPlatform pathPage: ', pageUrl); // if (!pageUrl || pageUrl === '') { // pageUrl = '/conversations-list'; // } if (checkPlatformIsMobile()) { this.platformIs = PLATFORM_MOBILE; const IDConv = this.route.snapshot.firstChild.paramMap.get('IDConv'); this.logger.log('[APP-COMP] PLATFORM_MOBILE2 navigateByUrl', PLATFORM_MOBILE, this.route.snapshot); if (!IDConv) { this.router.navigateByUrl('conversations-list') } // this.router.navigateByUrl(pageUrl); // this.navService.setRoot(ConversationListPage, {}); } else { this.platformIs = PLATFORM_DESKTOP; this.logger.log('[APP-COMP] PLATFORM_DESKTOP ', this.navService); this.navService.setRoot(ConversationListPage, {}); const IDConv = this.route.snapshot.firstChild.paramMap.get('IDConv'); const FullNameConv = this.route.snapshot.firstChild.paramMap.get('FullNameConv'); const Convtype = this.route.snapshot.firstChild.paramMap.get('Convtype'); let pageUrl = 'conversation-detail/' if (IDConv && FullNameConv) { pageUrl += IDConv + '/' + FullNameConv + '/' + Convtype } this.router.navigateByUrl(pageUrl); // const DASHBOARD_URL = this.appConfigProvider.getConfig().DASHBOARD_URL; // createExternalSidebar(this.renderer, DASHBOARD_URL); // // FOR REALTIME TESTING // createExternalSidebar(this.renderer, 'http://localhost:4204'); } } /** */ // showNavbar() { // let TEMP = location.search.split('navBar=')[1]; // if (TEMP) { this.isNavBar = TEMP.split('&')[0]; } // } /** */ hideAlert() { this.logger.debug('[APP-COMP] hideAlert'); this.notificationsEnabled = true; } private initAudio() { // SET AUDIO this.audio = new Audio(); this.audio.src = URL_SOUND_LIST_CONVERSATION; this.audio.load(); } private manageTabNotification() { if (!this.isTabVisible) { // TAB IS HIDDEN --> manage title and SOUND let badgeNewConverstionNumber = this.conversationsHandlerService.countIsNew() badgeNewConverstionNumber > 0 ? badgeNewConverstionNumber : badgeNewConverstionNumber = 1 document.title = "(" + badgeNewConverstionNumber + ") " + this.tabTitle clearInterval(this.setIntervalTime) const that = this this.setIntervalTime = setInterval(function () { if (document.title.charAt(0) === '(') { document.title = that.tabTitle } else { document.title = "(" + badgeNewConverstionNumber + ") " + that.tabTitle; } }, 1000); this.soundMessage() } } soundMessage() { const that = this; // this.audio = new Audio(); // // this.audio.src = '/assets/sounds/pling.mp3'; // this.audio.src = URL_SOUND_LIST_CONVERSATION; // this.audio.load(); this.logger.debug('[APP-COMP] conversation play', this.audio); clearTimeout(this.setTimeoutSound); this.setTimeoutSound = setTimeout(function () { that.audio.play().then(() => { that.logger.debug('[APP-COMP] ****** soundMessage played *****'); }).catch((error: any) => { that.logger.debug('[APP-COMP] ***soundMessage error*', error); }); }, 1000); } /**---------------- SOUND FUNCTIONS --> END <--- +*/ /***************************************************+*/ // BEGIN SUBSCRIPTIONS // /** .pipe( takeUntil(this.unsubscribe$) ) */ initSubscriptions() { this.logger.log('initialize FROM [APP-COMP] - initSubscriptions'); this.messagingAuthService.BSAuthStateChanged .pipe(takeUntil(this.unsubscribe$)) .pipe(filter((state) => state !== null)) .subscribe((state: any) => { this.logger.info('initialize FROM [APP-COMP] - [APP-COMP] ***** BSAuthStateChanged state', state); this.logger.info('initialize FROM [APP-COMP] - [APP-COMP] ***** BSAuthStateChanged isOnline', this.isOnline); if (state && state === AUTH_STATE_ONLINE) { const user = this.tiledeskAuthService.getCurrentUser(); if (this.isOnline === false) { this.goOnLine(); } } else if (state === AUTH_STATE_OFFLINE) { // that.goOffLine(); this.authenticate() //se c'è un tiledeskToken salvato, allora aspetta, altrimenti vai offline } }, error => { this.logger.error('initialize FROM [APP-COMP] - [APP-COMP] ***** BSAuthStateChanged * error * ', error) }, () => { this.logger.log('initialize FROM [APP-COMP] - [APP-COMP] ***** BSAuthStateChanged *** complete *** ') }); this.events.subscribe('uidConvSelected:changed', this.subscribeChangedConversationSelected); this.events.subscribe('profileInfoButtonClick:logout', this.subscribeProfileInfoButtonLogOut); this.conversationsHandlerService.conversationAdded.subscribe((conversation: ConversationModel) => { // this.logger.log('[APP-COMP] ***** conversationsAdded *****', conversation); // that.conversationsChanged(conversations); if (conversation && conversation.is_new === true) { this.manageTabNotification() } }); this.conversationsHandlerService.conversationChanged.subscribe((conversation: ConversationModel) => { this.logger.log('[APP-COMP] ***** subscribeConversationChanged conversation: ', conversation); const currentUser = JSON.parse(this.appStorageService.getItem('currentUser')); this.logger.log('[APP-COMP] ***** subscribeConversationChanged current_user: ', currentUser); if (currentUser) { this.logger.log('[APP-COMP] ***** subscribeConversationChanged current_user uid: ', currentUser.uid); if (conversation && conversation.sender !== currentUser.uid) { this.manageTabNotification(); } } }); } /** * ::: subscribeChangedConversationSelected ::: * evento richiamato quando si seleziona un utente nell'elenco degli user * apro dettaglio conversazione */ subscribeChangedConversationSelected = (user: UserModel, type: string) => { this.logger.info('[APP-COMP] subscribeUidConvSelectedChanged navigateByUrl', user, type); // this.router.navigateByUrl('conversation-detail/' + user.uid + '?conversationWithFullname=' + user.fullname); this.router.navigateByUrl('conversation-detail/' + user.uid + '/' + user.fullname + '/' + type); } subscribeProfileInfoButtonLogOut = (hasClickedLogout) => { this.logger.log('[APP-COMP] FIREBASE-NOTIFICATION >>>> subscribeProfileInfoButtonLogOut '); // if (hasClickedLogout === true) { // this.removePresenceAndLogout() // } if (hasClickedLogout === true) { // ---------------------------------------------- // PUSH NOTIFICATIONS // ---------------------------------------------- const that = this; const pushEngine = this.appConfigProvider.getConfig().pushEngine if (pushEngine && pushEngine !== 'none') { this.notificationsService.removeNotificationsInstance(function (res) { that.logger.log('[APP-COMP] FIREBASE-NOTIFICATION >>>> removeNotificationsInstance > CALLBACK RES', res); if (res === 'success') { that.removePresenceAndLogout(); } else { that.removePresenceAndLogout(); // that.presentToast(); } }) } } } private async presentModal(calledby): Promise<any> { this.logger.log('[APP-COMP] presentModal calledby', calledby, '- hadBeenCalledOpenModal: ', this.hadBeenCalledOpenModal); const attributes = { tenant: this.tenant, enableBackdropDismiss: false }; const modal: HTMLIonModalElement = await this.modalController.create({ component: LoginPage, componentProps: attributes, swipeToClose: false, backdropDismiss: false }); modal.onDidDismiss().then((detail: any) => { this.hadBeenCalledOpenModal = false this.logger.log('[APP-COMP] presentModal onDidDismiss detail.data ', detail.data); // this.checkPlatform(); if (detail !== null) { // this.logger.debug('The result: CHIUDI!!!!!', detail.data); } }); // await modal.present(); // modal.onDidDismiss().then((detail: any) => { // this.logger.debug('The result: CHIUDI!!!!!', detail.data); // // this.checkPlatform(); // if (detail !== null) { // // this.logger.debug('The result: CHIUDI!!!!!', detail.data); // } // }); return await modal.present(); } private async closeModal() { this.logger.debug('[APP-COMP] closeModal', this.modalController); this.logger.debug('[APP-COMP] closeModal .getTop()', this.modalController.getTop()); await this.modalController.getTop(); this.modalController.dismiss({ confirmed: true }); } // listenToLogoutEvent() { // this.events.subscribe('profileInfoButtonClick:logout', (hasclickedlogout) => { // this.logger.debug('[APP-COMP] hasclickedlogout', hasclickedlogout); // if (hasclickedlogout === true) { // // ---------------------------------------------- // // PUSH NOTIFICATIONS // // ---------------------------------------------- // const that = this; // const pushEngine = this.appConfigProvider.getConfig().pushEngine // if( pushEngine && pushEngine !== 'none'){ // this.notificationsService.removeNotificationsInstance(function (res) { // that.logger.debug('[APP-COMP] FIREBASE-NOTIFICATION >>>> removeNotificationsInstance > CALLBACK RES', res); // if (res === 'success') { // that.removePresenceAndLogout(); // } else { // that.removePresenceAndLogout(); // that.presentToast(); // } // }) // } // } // }); // } async presentToast() { const toast = await this.toastController.create({ message: this.toastMsgErrorWhileUnsubscribingFromNotifications, duration: 2000 }); toast.present(); } removePresenceAndLogout() { this.logger.debug('[APP-COMP] FIREBASE-NOTIFICATION >>>> calling removePresenceAndLogout'); this.presenceService.removePresence(); this.tiledeskAuthService.logOut() this.messagingAuthService.logout() } private initConversationsHandler(userId: string) { const keys = ['YOU']; const translationMap = this.translateService.translateLanguage(keys); this.logger.log('[APP-COMP] initConversationsHandler ------------->', userId, this.tenant); // 1 - init chatConversationsHandler and archviedConversationsHandler this.conversationsHandlerService.initialize(this.tenant, userId, translationMap); // this.subscribeToConvs() this.conversationsHandlerService.subscribeToConversations(() => { this.logger.log('[APP-COMP] - CONVS - INIT CONV') const conversations = this.conversationsHandlerService.conversations; this.logger.info('initialize FROM [APP-COMP] - [APP-COMP]-CONVS - INIT CONV CONVS', conversations) // this.logger.printDebug('SubscribeToConversations (convs-list-page) - conversations') if (!conversations || conversations.length === 0) { // that.showPlaceholder = true; this.logger.debug('[APP-COMP]-CONVS - INIT CONV CONVS 2', conversations) this.events.publish('appcompSubscribeToConvs:loadingIsActive', false); } }); } private initArchivedConversationsHandler(userId: string) { const keys = ['YOU']; const translationMap = this.translateService.translateLanguage(keys); this.logger.debug('[APP-COMP] initArchivedConversationsHandler ------------->', userId, this.tenant); // 1 - init archviedConversationsHandler this.archivedConversationsHandlerService.initialize(this.tenant, userId, translationMap); } // BEGIN RESIZE FUNCTIONS // @HostListener('window:resize', ['$event']) onResize(event: any) { const that = this; // this.logger.debug('this.doitResize)', this.doitResize) clearTimeout(this.doitResize); this.doitResize = setTimeout(() => { let platformIsNow = PLATFORM_DESKTOP; if (checkPlatformIsMobile()) { platformIsNow = PLATFORM_MOBILE; } if (!this.platformIs || this.platformIs === '') { this.platformIs = platformIsNow; } this.logger.debug('[APP-COMP] onResize width::::', window.innerWidth); this.logger.debug('[APP-COMP] onResize width:::: platformIsNow', platformIsNow); this.logger.debug('[APP-COMP] onResize width:::: platformIsNow this.platformIs', this.platformIs); if (platformIsNow !== this.platformIs) { window.location.reload(); } }, 500); } // END RESIZE FUNCTIONS // @HostListener('document:visibilitychange', []) visibilitychange() { // this.logger.debug("document TITLE", document.hidden, document.title); if (document.hidden) { this.isTabVisible = false } else { // TAB IS ACTIVE --> restore title and DO NOT SOUND clearInterval(this.setIntervalTime) this.isTabVisible = true; document.title = this.tabTitle; } } // Storage event not firing: This won't work on the same page that is making the changes // https://stackoverflow.com/questions/35865481/storage-event-not-firing // https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event @HostListener('window:storage', ['$event']) onStorageChanged(event: any) { // console.log('[APP-COMP] - onStorageChanged event ', event) if (event.key !== 'chat_sv5__tiledeskToken') { return; } if (this.appStorageService.getItem('tiledeskToken') === null) { this.logger.log('[APP-COMP] - onStorageChanged tiledeskToken is null - RUN LOGOUT') this.tiledeskAuthService.logOut() this.messagingAuthService.logout(); this.events.publish('profileInfoButtonClick:logout', true); this.isOnline = false; } else { const currentUser = this.tiledeskAuthService.getCurrentUser(); if (!currentUser && this.appStorageService.getItem('tiledeskToken') !== null) { this.logger.log('[APP-COMP] - onStorageChanged currentUser', currentUser) // console.log('[APP-COMP] - onStorageChanged wentOnline 2', this.wentOnline) this.initializeApp('onstoragechanged'); } } } }
the_stack
import React, { lazy, Suspense } from 'react'; import CssBaseline from '@material-ui/core/CssBaseline'; import { ThemeProvider as MuiThemeProvider, StylesProvider, } from '@material-ui/core/styles'; import { BrowserRouter, Route, Redirect, Switch } from 'react-router-dom'; import { ThemeProvider as ScThemeProvider } from 'styled-components'; import LocationPage from 'screens/LocationPage'; import Embed from 'screens/Embed/Embed'; import VaccinationPhases from 'screens/internal/VaccinationPhases/VaccinationPhases'; import Footer from 'components/Footer'; import ScrollToTop from 'components/ScrollToTop'; import theme from 'assets/theme'; import { getFeedbackSurveyUrl } from 'components/Banner'; import ExternalRedirect from 'components/ExternalRedirect'; import HandleRedirectTo from 'components/HandleRedirectTo/HandleRedirectTo'; import PageviewTracker, { trackEvent, EventAction, EventCategory, } from 'components/Analytics'; import { SuspenseFallback, ErrorBoundary } from 'components/LazyLoading'; import HomePage from 'screens/HomePage/HomePage'; /* We dynamically import the following components on initial visit to their respective routes: */ const About = lazy(() => import('screens/About/About')); const Landing = lazy(() => import('screens/Learn/Landing/Landing')); const MetricExplainer = lazy(() => import('screens/Learn/MetricExplainer')); const Faq = lazy(() => import('screens/Learn/Faq/Faq')); const Glossary = lazy(() => import('screens/Learn/Glossary/Glossary')); const CaseStudies = lazy(() => import('screens/Learn/CaseStudies/CaseStudies')); const Explained = lazy(() => import('screens/Learn/Explained')); const Alerts = lazy(() => import('screens/Learn/Alerts/Alerts')); const DataApi = lazy(() => import('screens/DataApi/DataApi')); const Terms = lazy(() => import('screens/Terms/Terms')); const Privacy = lazy(() => import('screens/Terms/Privacy')); const Donate = lazy(() => import('screens/Donate/Donate')); const DeepDivesRedirect = lazy(() => import('screens/Learn/Articles/DeepDivesRouter'), ); const CompareSnapshots = lazy(() => import('screens/internal/CompareSnapshots/CompareSnapshots'), ); const AllStates = lazy(() => import('screens/internal/AllStates/AllStates')); const ExportImage = lazy(() => import('screens/internal/ShareImage/ChartExportImage'), ); const ShareImage = lazy(() => import('screens/internal/ShareImage/ShareImage')); const AlertUnsubscribe = lazy(() => import('screens/AlertUnsubscribe/AlertUnsubscribe'), ); const AfterSubscribe = lazy(() => import('screens/Subscriptions/AfterSubscribe'), ); const AfterUnsubscribe = lazy(() => import('screens/Subscriptions/AfterUnsubscribe'), ); export default function App() { return ( <MuiThemeProvider theme={theme}> <ScThemeProvider theme={theme}> <StylesProvider injectFirst> <CssBaseline /> <BrowserRouter> <PageviewTracker /> <ScrollToTop /> <ErrorBoundary> <Suspense fallback={<SuspenseFallback />}> <Switch> <Route exact path="/" component={HomePage} /> <Route exact path="/alert_signup" component={HomePage} /> <Route exact path="/compare/:sharedComponentId?" component={HomePage} /> <Route exact path="/explore/:sharedComponentId?" component={HomePage} /> <Route exact path="/alert_unsubscribe" component={AlertUnsubscribe} /> <Route exact path="/after_subscribe" component={AfterSubscribe} /> <Route exact path="/after_unsubscribe" component={AfterUnsubscribe} /> <Route exact path="/donate" component={Donate} /> <Route exact path="/us/:stateId" component={LocationPage} /> <Route exact path="/us/:stateId/county/:countyId" component={LocationPage} /> <Route exact path="/us/metro/:metroAreaUrlSegment" component={LocationPage} /> <Route exact path="/us/metro/:metroAreaUrlSegment/chart/:chartId" component={LocationPage} /> <Route exact path="/us/metro/:metroAreaUrlSegment/compare/:sharedComponentId?" component={LocationPage} /> <Route exact path="/us/metro/:metroAreaUrlSegment/explore/:sharedComponentId?" component={LocationPage} /> <Route exact path="/us/metro/:metroAreaUrlSegment/recommendations" component={LocationPage} /> <Route exact path="/us/:stateId/chart/:chartId" component={LocationPage} /> <Route exact path="/us/:stateId/recommendations" component={LocationPage} /> <Route exact path="/us/:stateId/explore/:sharedComponentId?" component={LocationPage} /> <Route exact path="/us/:stateId/compare/:sharedComponentId?" component={LocationPage} /> <Route exact path="/us/:stateId/county/:countyId/chart/:chartId" component={LocationPage} /> <Route exact path="/us/:stateId/county/:countyId/recommendations" component={LocationPage} /> <Route exact path="/us/:stateId/county/:countyId/explore/:sharedComponentId?" component={LocationPage} /> <Route exact path="/us/:stateId/county/:countyId/compare/:sharedComponentId?" component={LocationPage} /> <Route exact path="/learn" component={Landing} /> {/* In case there is now an /explained link in the wild: */} <Redirect from="/explained" to="/learn" /> {/* Lazy loaded components: */} <Route exact path="/faq" component={Faq} /> <Route exact path="/glossary" component={Glossary} /> <Route path="/case-studies" component={CaseStudies} /> <Route path="/covid-explained" component={Explained} /> <Redirect from="/updates" to="/covid-explained" /> {/* TODO(pablo): Route every article */} <Route from="/deep-dives" component={DeepDivesRedirect} /> <Route path="/covid-risk-levels-metrics" component={MetricExplainer} /> <Route path="/about" component={About} /> <Route path="/research-rundown-archive" component={Alerts} /> <Redirect path="/subscribe" to="/research-rundown-archive" /> {/* /state/ routes are deprecated but still supported. */} <Redirect exact from="/state/:stateId" to="/us/:stateId" /> <Redirect exact from="/state/:stateId/county/:countyId" to="/us/:stateId/county/:countyId" /> <Route path="/data-api" component={DataApi} /> {/* Keeping the /resources URL active in case linked elsewhere */} <Redirect from="/resources" to="/data-api" /> <Redirect from="/tools" to="/data-api" /> <Redirect path="/contact" to="/about#contact-us" /> <Route path="/terms" component={Terms} /> <Route path="/privacy" component={Privacy} /> {/* Custom redirect to track clicks from the Daily download */} <Route path="/exposure-notifications-redirect"> <ExternalRedirect url={'https://g.co/ens'} onRedirect={trackExposureNotificationRedirect} /> </Route> {/* Embed routes */} <Route exact path="/embed/us" render={() => <Embed isNational />} /> <Route exact path="/embed/risk/us" render={() => <Embed isNational isRiskMap />} /> <Route exact path="/embed/us/:stateId" component={Embed} /> <Route exact path="/embed/us/:stateId/county/:countyId" component={Embed} /> {/* TODO: We might want to support non-embed fips-code URLs too for consistency? */} <Route exact path="/embed/us/county/:countyFipsId" component={Embed} /> <Route exact path="/embed/us/fips/:fipsCode" component={Embed} /> {/* /model and /contact are deprecated in favor of /faq */} <Redirect from="/model" to="/faq" /> {/** * This endpoint is to share the feedback survey link in social * media. We redirec them to Typeform with URL parameters to * track users through the survey, as well as their source. */} <Route path="/feedback-survey" component={() => ( <ExternalRedirect url={getFeedbackSurveyUrl('social')} /> )} /> {/** Internal endpoint that shows all the state charts. */} <Redirect from="/all" to="/internal/all" /> <Route path="/internal/all" component={AllStates} /> {/** Internal endpoint for comparing API snapshots. */} <Route path="/internal/compare" component={CompareSnapshots} /> {/** Internal endpoint for viewing all vaccination phase data **/} <Route exact path="/internal/vaccine-eligibility" component={VaccinationPhases} /> {/** Internal endpoints we use to generate the content that we want to screenshot for our social sharing images (OpenGraph / Twitter Card). */} <Route path="/internal/share-image/" component={ShareImage} /> {/** Internal endpoints we use to generate downloadable chart exports images. */} <Route path="/internal/export-image/" component={ExportImage} /> {/** Old blog.covidactnow.org URLs that we now redirect to the right places in Learn. */} <Redirect from="/covid-contact-tracing-reopening-warning-system" to="/learn" /> <Redirect from="/changes-to-how-we-assess-contact-tracing" to="/learn" /> <Redirect from="/types-of-covid-tests" to="/learn" /> <Redirect from="/covid-act-now-api-intervention-model" to="/data-api" /> <Redirect from="/export-covid-act-now-data-spreadsheet" to="/data-api" /> <Redirect from="/alerting-to-changes-in-covid-risk" to="/subscribe" /> <Redirect from="/covid-infection-rate" to="/covid-risk-levels-metrics#icu-capacity-used" /> <Redirect from="/what-is-covid-incidence" to="/covid-risk-levels-metrics#daily-new-cases" /> <Redirect from="/new-daily-covid-cases" to="/covid-risk-levels-metrics#daily-new-cases" /> <Redirect from="/old-hospitalization-projections" to="/covid-risk-levels-metrics#icu-capacity-used" /> <Redirect from="/daily-new-cases-explained" to="/covid-risk-levels-metrics#daily-new-cases" /> <Redirect from="/test-positivity-explained" to="/covid-risk-levels-metrics#positive-test-rate" /> <Redirect from="/icu-headroom-used-explained" to="/covid-risk-levels-metrics#icu-capacity-used" /> <Redirect from="/infection-rate-explained-2" to="/covid-risk-levels-metrics#infection-rate" /> <Redirect from="/covid-native-american-counties" to="/covid-explained/covid-spread-native-american" /> {/** Handle bad paths by redirecting to the root homepage. */} <Route path="/*"> <Redirect to="/" /> </Route> </Switch> </Suspense> </ErrorBoundary> {/** * NOTE: This needs to go after the Switch statement so that it overrides the * "Handle bad paths" logic above. */} <HandleRedirectTo /> <Footer /> </BrowserRouter> </StylesProvider> </ScThemeProvider> </MuiThemeProvider> ); } function trackExposureNotificationRedirect() { trackEvent( EventCategory.EXPOSURE_NOTIFICATIONS, EventAction.REDIRECT, 'Redirect', ); }
the_stack
import { IDomChangeEvent, INodeData } from '@secret-agent/interfaces/IDomChangeEvent'; import { IMouseEvent } from '@secret-agent/interfaces/IMouseEvent'; import { IFocusEvent } from '@secret-agent/interfaces/IFocusEvent'; import { IScrollEvent } from '@secret-agent/interfaces/IScrollEvent'; import { ILoadEvent } from '@secret-agent/interfaces/ILoadEvent'; enum DomActionType { newDocument = 0, location = 1, added = 2, removed = 3, text = 4, attribute = 5, property = 6, } const MutationRecordType = { attributes: 'attributes', childList: 'childList', characterData: 'characterData', }; // exporting a type is ok. Don't export variables or will blow up the page export type PageRecorderResultSet = [ IDomChangeEvent[], IMouseEvent[], IFocusEvent[], IScrollEvent[], ILoadEvent[], ]; const SHADOW_NODE_TYPE = 40; // @ts-ignore const eventsCallback = (window[runtimeFunction] as unknown) as (data: string) => void; // @ts-ignore delete window[runtimeFunction]; let lastUploadDate: Date; function upload(records: PageRecorderResultSet) { try { const total = records.reduce((tot, ent) => tot + ent.length, 0); if (total > 0) { eventsCallback(JSON.stringify(records)); } lastUploadDate = new Date(); return true; } catch (err) { // eslint-disable-next-line no-console console.log(`ERROR calling page recorder callback: ${String(err)}`, err); } return false; } let eventCounter = 0; function idx() { return (eventCounter += 1); } let isStarted = false; class PageEventsRecorder { private domChanges: IDomChangeEvent[] = []; private mouseEvents: IMouseEvent[] = []; private focusEvents: IFocusEvent[] = []; private scrollEvents: IScrollEvent[] = []; private loadEvents: ILoadEvent[] = []; private location = window.self.location.href; private isListeningForInteractionEvents = false; private propertyTrackingElements = new Map<Node, Map<string, string | boolean>>(); private stylesheets = new Map<HTMLStyleElement | HTMLLinkElement, string[]>(); private readonly observer: MutationObserver; constructor() { this.observer = new MutationObserver(this.onMutation.bind(this)); } public start() { if (isStarted || window.self.location.href === 'about:blank') { return; } isStarted = true; const stamp = new Date().getTime(); // preload with a document this.domChanges.push([ DomActionType.newDocument, { id: -1, textContent: window.self.location.href, }, stamp, idx(), ]); if (document) { this.domChanges.push([DomActionType.added, this.serializeNode(document), stamp, idx()]); } if (document && document.doctype) { this.domChanges.push([ DomActionType.added, this.serializeNode(document.doctype), stamp, idx(), ]); } const children = this.serializeChildren(document, new Map<Node, INodeData>()); this.observer.observe(document, { attributes: true, childList: true, subtree: true, characterData: true, }); for (const childData of children) { this.domChanges.push([DomActionType.added, childData, stamp, idx()]); } this.uploadChanges(); } public extractChanges(): PageRecorderResultSet { const changes = this.convertMutationsToChanges(this.observer.takeRecords()); this.domChanges.push(...changes); return this.pageResultset; } public flushAndReturnLists(): PageRecorderResultSet { const changes = recorder.extractChanges(); recorder.resetLists(); return changes; } public trackFocus(eventType: FocusType, focusEvent: FocusEvent) { const nodeId = NodeTracker.getNodeId(focusEvent.target as Node); const relatedNodeId = NodeTracker.getNodeId(focusEvent.relatedTarget as Node); const time = new Date().getTime(); const event = [eventType as any, nodeId, relatedNodeId, time] as IFocusEvent; this.focusEvents.push(event); this.getPropertyChanges(time, this.domChanges); } public trackMouse(eventType: MouseEventType, mouseEvent: MouseEvent) { const nodeId = NodeTracker.getNodeId(mouseEvent.target as Node); const relatedNodeId = NodeTracker.getNodeId(mouseEvent.relatedTarget as Node); const event = [ eventType, mouseEvent.pageX, mouseEvent.pageY, // might not want to do this - causes reflow mouseEvent.offsetX, mouseEvent.offsetY, mouseEvent.buttons, nodeId, relatedNodeId, new Date().getTime(), ] as IMouseEvent; this.mouseEvents.push(event); } public trackScroll(scrollX: number, scrollY: number) { this.scrollEvents.push([scrollX, scrollY, new Date().getTime()]); } public onLoadEvent(name: string) { this.start(); this.loadEvents.push([name, window.self.location.href, new Date().getTime()]); this.uploadChanges(); } public checkForAllPropertyChanges() { this.getPropertyChanges(new Date().getTime(), this.domChanges); } public get pageResultset(): PageRecorderResultSet { return [ [...this.domChanges], [...this.mouseEvents], [...this.focusEvents], [...this.scrollEvents], [...this.loadEvents], ]; } public resetLists() { this.domChanges.length = 0; this.mouseEvents.length = 0; this.focusEvents.length = 0; this.scrollEvents.length = 0; this.loadEvents.length = 0; } public disconnect() { this.extractChanges(); this.observer.disconnect(); this.uploadChanges(); } public uploadChanges() { if (upload(this.pageResultset)) { this.resetLists(); } } public listenToInteractionEvents() { if (this.isListeningForInteractionEvents) return; this.isListeningForInteractionEvents = true; for (const event of ['input', 'keydown', 'change']) { document.addEventListener(event, this.checkForAllPropertyChanges.bind(this), { capture: true, passive: true, }); } document.addEventListener('mousemove', e => this.trackMouse(MouseEventType.MOVE, e), { capture: true, passive: true, }); document.addEventListener('mousedown', e => this.trackMouse(MouseEventType.DOWN, e), { capture: true, passive: true, }); document.addEventListener('mouseup', e => this.trackMouse(MouseEventType.UP, e), { capture: true, passive: true, }); document.addEventListener('mouseover', e => this.trackMouse(MouseEventType.OVER, e), { capture: true, passive: true, }); document.addEventListener('mouseleave', e => this.trackMouse(MouseEventType.OUT, e), { capture: true, passive: true, }); document.addEventListener('focusin', e => this.trackFocus(FocusType.IN, e), { capture: true, passive: true, }); document.addEventListener('focusout', e => this.trackFocus(FocusType.OUT, e), { capture: true, passive: true, }); document.addEventListener('scroll', () => this.trackScroll(window.scrollX, window.scrollY), { capture: true, passive: true, }); } private getLocationChange(changeUnixTime: number, changes: IDomChangeEvent[]) { const timestamp = changeUnixTime || new Date().getTime(); const currentLocation = window.self.location.href; if (this.location !== currentLocation) { this.location = currentLocation; changes.push([ DomActionType.location, { id: -1, textContent: currentLocation }, timestamp, idx(), ]); } } private getPropertyChanges(changeUnixTime: number, changes: IDomChangeEvent[]) { for (const [input, propertyMap] of this.propertyTrackingElements) { for (const [propertyName, value] of propertyMap) { const newPropValue = input[propertyName]; if (newPropValue !== value) { const nodeId = NodeTracker.getNodeId(input); changes.push([ DomActionType.property, { id: nodeId, properties: { [propertyName]: newPropValue } }, changeUnixTime, idx(), ]); propertyMap.set(propertyName, newPropValue); } } } } private trackStylesheet(element: HTMLStyleElement) { if (!element || this.stylesheets.has(element)) return; if (!element.sheet) return; const shouldStoreCurrentStyleState = !!element.textContent; if (element.sheet instanceof CSSStyleSheet) { try { // if there's style text, record the current state const startingStyle = shouldStoreCurrentStyleState ? [...element.sheet.cssRules].map(x => x.cssText) : []; this.stylesheets.set(element, startingStyle); } catch (err) { // can't track cors stylesheet rules } } } private checkForStylesheetChanges(changeUnixTime: number, changes: IDomChangeEvent[]) { const timestamp = changeUnixTime || new Date().getTime(); for (const [style, current] of this.stylesheets) { if (!style.sheet || !style.isConnected) continue; const sheet = style.sheet as CSSStyleSheet; const newPropValue = [...sheet.cssRules].map(x => x.cssText); if (newPropValue.toString() !== current.toString()) { const nodeId = NodeTracker.getNodeId(style); changes.push([ DomActionType.property, { id: nodeId, properties: { 'sheet.cssRules': newPropValue } }, timestamp, idx(), ]); this.stylesheets.set(style, newPropValue); } } } private onMutation(mutations: MutationRecord[]) { const changes = this.convertMutationsToChanges(mutations); this.domChanges.push(...changes); } private convertMutationsToChanges(mutations: MutationRecord[]) { const changes: IDomChangeEvent[] = []; const stamp = new Date().getTime(); this.getLocationChange(stamp, changes); this.getPropertyChanges(stamp, changes); const addedNodeMap = new Map<Node, INodeData>(); const removedNodes = new Set<Node>(); for (const mutation of mutations) { const { type, target } = mutation; if (!NodeTracker.has(target)) { this.serializeHierarchy(target, changes, stamp, addedNodeMap); } if (type === MutationRecordType.childList) { let isFirstRemoved = true; for (let i = 0, length = mutation.removedNodes.length; i < length; i += 1) { const node = mutation.removedNodes[i]; removedNodes.add(node); if (!NodeTracker.has(node)) continue; const serial = this.serializeNode(node); serial.parentNodeId = NodeTracker.getNodeId(target); serial.previousSiblingId = NodeTracker.getNodeId( isFirstRemoved ? mutation.previousSibling : node.previousSibling, ); changes.push([DomActionType.removed, serial, stamp, idx()]); isFirstRemoved = false; } // A batch of changes includes changes in a set of nodes. // Since we're flattening, only the first one should be added after the mutation sibling. let isFirstAdded = true; for (let i = 0, length = mutation.addedNodes.length; i < length; i += 1) { const node = mutation.addedNodes[i]; const serial = this.serializeNode(node); serial.parentNodeId = NodeTracker.getNodeId(target); serial.previousSiblingId = NodeTracker.getNodeId( isFirstAdded ? mutation.previousSibling : node.previousSibling, ); isFirstAdded = false; // if we get a re-order of nodes, sometimes we'll remove nodes, and add them again if (addedNodeMap.has(node) && !removedNodes.has(node)) { const existing = addedNodeMap.get(node); if ( existing.previousSiblingId === serial.previousSiblingId && existing.parentNodeId === serial.parentNodeId ) { continue; } } addedNodeMap.set(node, serial); changes.push([DomActionType.added, serial, stamp, idx()]); } } if (type === MutationRecordType.attributes) { // don't store if (!NodeTracker.has(target)) { this.serializeHierarchy(target, changes, stamp, addedNodeMap); } const serial = addedNodeMap.get(target) || this.serializeNode(target); if (!serial.attributes) serial.attributes = {}; serial.attributes[mutation.attributeName] = (target as Element).getAttributeNS( mutation.attributeNamespace, mutation.attributeName, ); if (mutation.attributeNamespace && mutation.attributeNamespace !== '') { if (!serial.attributeNamespaces) serial.attributeNamespaces = {}; serial.attributeNamespaces[mutation.attributeName] = mutation.attributeNamespace; } // flatten changes if (!addedNodeMap.has(target)) { changes.push([DomActionType.attribute, serial, stamp, idx()]); } } if (type === MutationRecordType.characterData) { const textChange = this.serializeNode(target); textChange.textContent = target.textContent; changes.push([DomActionType.text, textChange, stamp, idx()]); } } for (const [node] of addedNodeMap) { // A batch of changes (setting innerHTML) will send nodes in a hierarchy instead of // individually so we need to extract child nodes into flat hierarchy const children = this.serializeChildren(node, addedNodeMap); for (const childData of children) { changes.push([DomActionType.added, childData, stamp, idx()]); } } this.checkForStylesheetChanges(stamp, changes); return changes; } private serializeHierarchy( node: Node, changes: IDomChangeEvent[], changeTime: number, addedNodeMap: Map<Node, INodeData>, ) { if (NodeTracker.has(node)) return this.serializeNode(node); const serial = this.serializeNode(node); serial.parentNodeId = NodeTracker.getNodeId(node.parentNode); if (!serial.parentNodeId && node.parentNode) { const parentSerial = this.serializeHierarchy( node.parentNode, changes, changeTime, addedNodeMap, ); serial.parentNodeId = parentSerial.id; } serial.previousSiblingId = NodeTracker.getNodeId(node.previousSibling); if (!serial.previousSiblingId && node.previousSibling) { const previous = this.serializeHierarchy( node.previousSibling, changes, changeTime, addedNodeMap, ); serial.previousSiblingId = previous.id; } changes.push([DomActionType.added, serial, changeTime, idx()]); addedNodeMap.set(node, serial); return serial; } private serializeChildren(node: Node, addedNodes: Map<Node, INodeData>) { const serialized: INodeData[] = []; for (const child of node.childNodes) { if (!NodeTracker.has(child)) { const serial = this.serializeNode(child); serial.parentNodeId = NodeTracker.getNodeId(child.parentElement ?? child.getRootNode()); serial.previousSiblingId = NodeTracker.getNodeId(child.previousSibling); addedNodes.set(child, serial); serialized.push(serial, ...this.serializeChildren(child, addedNodes)); } } for (const element of [node, ...node.childNodes] as Element[]) { if (element.tagName === 'STYLE') { this.trackStylesheet(element as HTMLStyleElement); } const shadowRoot = element.shadowRoot; if (shadowRoot && !NodeTracker.has(shadowRoot)) { const serial = this.serializeNode(shadowRoot); serial.parentNodeId = NodeTracker.getNodeId(element); serialized.push(serial, ...this.serializeChildren(shadowRoot, addedNodes)); this.observer.observe(shadowRoot, { attributes: true, childList: true, subtree: true, characterData: true, }); } } return serialized; } private serializeNode(node: Node): INodeData { if (node === null) { return undefined; } const id = NodeTracker.getNodeId(node); if (id !== undefined) { return { id }; } const data: INodeData = { nodeType: node.nodeType, id: NodeTracker.track(node), }; if (node instanceof ShadowRoot) { data.nodeType = SHADOW_NODE_TYPE; return data; } switch (data.nodeType) { case Node.COMMENT_NODE: case Node.TEXT_NODE: data.textContent = node.textContent; break; case Node.DOCUMENT_TYPE_NODE: data.textContent = new XMLSerializer().serializeToString(node); break; case Node.ELEMENT_NODE: const element = node as Element; data.tagName = element.tagName; if (element.namespaceURI && element.namespaceURI !== defaultNamespaceUri) { data.namespaceUri = element.namespaceURI; } if (element.attributes.length) { data.attributes = {}; for (let i = 0, length = element.attributes.length; i < length; i += 1) { const attr = element.attributes[i]; data.attributes[attr.name] = attr.value; if (attr.namespaceURI && attr.namespaceURI !== defaultNamespaceUri) { if (!data.attributeNamespaces) data.attributeNamespaces = {}; data.attributeNamespaces[attr.name] = attr.namespaceURI; } } } let propertyChecks: [string, string | boolean][]; for (const prop of propertiesToCheck) { if (prop in element) { if (!propertyChecks) propertyChecks = []; propertyChecks.push([prop, element[prop]]); } } if (propertyChecks) { const propsMap = new Map<string, string | boolean>(propertyChecks); this.propertyTrackingElements.set(node, propsMap); } break; } return data; } } const defaultNamespaceUri = 'http://www.w3.org/1999/xhtml'; const propertiesToCheck = ['value', 'selected', 'checked']; const recorder = new PageEventsRecorder(); // @ts-ignore window.extractDomChanges = () => recorder.extractChanges(); // @ts-ignore window.flushPageRecorder = () => recorder.flushAndReturnLists(); // @ts-ignore window.listenForInteractionEvents = () => recorder.listenToInteractionEvents(); const interval = setInterval(() => { if (!lastUploadDate || new Date().getTime() - lastUploadDate.getTime() > 1e3) { // if we haven't uploaded in 1 second, make sure nothing is pending requestAnimationFrame(() => recorder.uploadChanges()); } }, 500); window.addEventListener('DOMContentLoaded', () => { // force domContentLoaded to come first recorder.onLoadEvent('DOMContentLoaded'); }); window.addEventListener('load', () => recorder.onLoadEvent('load')); if (window.self.location?.href !== 'about:blank') { window.addEventListener('beforeunload', () => { clearInterval(interval); recorder.disconnect(); }); const paintObserver = new PerformanceObserver(entryList => { if (entryList.getEntriesByName('first-contentful-paint').length) { recorder.start(); paintObserver.disconnect(); } }); paintObserver.observe({ type: 'paint', buffered: true }); const contentStableObserver = new PerformanceObserver(() => { recorder.onLoadEvent('LargestContentfulPaint'); contentStableObserver.disconnect(); }); contentStableObserver.observe({ type: 'largest-contentful-paint', buffered: true }); } // need duplicate since this is a variable - not just a type enum MouseEventType { MOVE = 0, DOWN = 1, UP = 2, OVER = 3, OUT = 4, } enum FocusType { IN = 0, OUT = 1, }
the_stack
module Kiwi.GameObjects.Tilemap { /** * A TileMap handles the creation of TileMapLayers and the TileTypes that they use. * Since a TileMap isn't a Entity itself you cannot add it to the Stage inorder to render that it manages, * Instead you have to add each layer lies within it. This way you can have other GameObjects behind/in-front of layers. * * @class TileMap * @namespace Kiwi.GameObjects.Tilemap * @constructor * @param state {Kiwi.State} The state that this Tilemap is on. * @param [tileMapDataKey] {String} The Data key for the JSON you would like to use. * @param [atlas] {Kiwi.Textures.TextureAtlas} The texture atlas that you would like the tilemap layers to use. * @param [startingCell=0] {number} The number for the initial cell that the first TileType should use. See 'createFromFileStore' for more information. * @return {TileMap} */ export class TileMap { constructor(state: Kiwi.State, tileMapData?: any, atlas?: Kiwi.Textures.TextureAtlas, startingCell:number=0) { this.tileTypes = []; this.createTileType(-1); this.layers = []; this.state = state; this.game = state.game; if (tileMapData !== undefined && atlas !== undefined) { this.createFromFileStore(tileMapData, atlas, startingCell); } else if (tileMapData !== undefined || atlas !== undefined) { Kiwi.Log.warn('You must pass BOTH the TileMapDataKey and TextureAtlas inorder to create a TileMap from the File Store.', '#tilemap'); } } /** * The orientation of the tilemap. * Note: This value does not affect the individual layers. * * @property orientation * @type String * @public */ public orientation: string; /** * Is an Array containing all of the TileTypes that are available on the TileMap. * @property tileTypes * @type TileType[] * @public */ public tileTypes: TileType[]; /** * A list of all of the TileMapLayers that exist on the TileMap. * @property layers * @type TileMapLayerBase * @public */ public layers: TileMapLayer[]; /** * The state that this TileMap exists on. * @property state * @type Kiwi.State * @public */ public state: Kiwi.State; /** * The game that this TileMap is a part of. * @property game * @type Kiwi.Game * @public */ public game: Kiwi.Game; /** * The default width of a single tile that a TileMapLayer is told to have upon its creation. * @property tileWidth * @type Number * @default 0 * @public */ public tileWidth: number = 0; /** * The default height of a single tile that a TileMapLayer is told to have upon its creation. * @property tileHeight * @type Number * @default 0 * @public */ public tileHeight: number = 0; /** * The default width of all TileMapLayers when they are created. * This value is in Tiles. * @property width * @type Number * @default 0 * @public */ public width: number = 0; /** * The default height of all TileMapLayers when they are created. * This value is in Tiles. * @property height * @type Number * @default 0 * @public */ public height: number = 0; /** * The width of the tilemap in pixels. This value is READ ONLY. * @property widthInPixels * @type Number * @public */ public get widthInPixels(): number { return this.width * this.tileWidth; } /** * The height of the tilemap in pixels. This value is READ ONLY. * @property heightInPixels * @type Number * @public */ public get heightInPixels(): number { return this.height * this.tileHeight; } /** * Any properties that were found in the JSON during creation. * @property properties * @type Object * @public */ public properties: any = {}; /** * Creates new tilemap layers from a JSON file that you pass (has to be in the Tiled Format). * The texture atlas you pass is that one that each TileMapLayer found in the JSON will use, You can change the TextureAtlas afterwards. * New TileTypes will automatically be created. The number is based on the Tileset parameter of the JSON. * The cell used for new TileTypes will begin at 0 and increment each time a new TileType is created (and a cell exists). Otherwise new TileTypes will start will a cell of -1 (none). * @method createFromFileStore * @param tileMapData {Any} This can either * @param atlas {Kiwi.Textures.TextureAtlas} The texture atlas that you would like the tilemap layers to use. * @param [startingCell=0] {number} The number for the initial cell that the first TileType should use. If you pass -1 then no new TileTypes will be created. * @public */ public createFromFileStore(tileMapData: any, atlas: Kiwi.Textures.TextureAtlas, startingCell:number=0) { var json = null; if (Kiwi.Utils.Common.isString(atlas)) { atlas = this.state.textures[<any>atlas]; } //Does the JSON exist? switch (typeof tileMapData) { case 'string': if (this.game.fileStore.exists(tileMapData) == false) { Kiwi.Log.error('The JSON file you have told to use for a TileMap does not exist.', '#tilemap', '#json'); return false; } json = JSON.parse( this.game.fileStore.getFile(tileMapData).data ); break; case 'object': //Is it a KiwiJS file? if (tileMapData.isData && tileMapData.dataType === Kiwi.Files.File.JSON) { if ( Kiwi.Utils.Common.isString(tileMapData.parse) ) { json = JSON.parse(tileMapData.data); } else { json = tileMapData.data; } } else { json = tileMapData; } break; default: Kiwi.Log.error('The type of TileMapData passed could not be idenified. Please either pass a name of JSON file to use OR an object to be used.', '#tilemap'); } //Get the map information this.orientation = (json.orientation == undefined) ? ORTHOGONAL : json.orientation; this.tileWidth = (json.tilewidth == undefined) ? 32 : json.tilewidth; this.tileHeight = (json.tileheight == undefined) ? 32 : json.tileheight; this.width = json.width; this.height = json.height; //Add the properties for (var prop in json.properties) { this.properties[prop] = json.properties[prop]; } //Generate the Tiles needed. if (json.tilesets !== "undefined" && startingCell !== -1) this._generateTypesFromTileset(json.tilesets, atlas, startingCell); //Generate the layers we need for (var i = 0; i < json.layers.length; i++) { var layerData = json.layers[i]; //Check what type it is. switch (json.layers[i].type) { case "tilelayer": var w = (layerData.width !== undefined) ? layerData.width : this.width; var h = (layerData.height !== undefined) ? layerData.height : this.height; var layer = this.createNewLayer(layerData.name, atlas, layerData.data, w, h, layerData.x * this.tileWidth, layerData.y * this.tileHeight ); //Add the extra data... layer.visible = (layerData.visible == undefined) ? true : layerData.visible; layer.alpha = (layerData.opacity == undefined) ? 1 : layerData.opacity; if (layerData.properties !== undefined)layer.properties = layerData.properties; break; case "objectgroup": this.createNewObjectLayer(); break; case "imagelayer": this.createNewImageLayer(); break; } } } /** * Generates new TileTypes based upon the Tileset information that lies inside the Tiled JSON. * This is an INTERNAL method, which is used when the createFromFileStore method is executed. * @method _generateTypesFromTileset * @param tilesetData {Array} The tileset part of the JSON. * @param atlas {Kiwi.Textures.TextureAtlas} The Texture atlas which contains the cells that the new TileTypes will use. * @param startingCell {Number} The first cell number that would be used. * @private */ private _generateTypesFromTileset( tilesetData:any[], atlas:Kiwi.Textures.TextureAtlas, startingCell:number ) { //Loop through the tilesets for (var i = 0; i < tilesetData.length; i++) { var tileset = tilesetData[i]; //Tileset Information var m = tileset.margin; var s = tileset.spacing; var tw = tileset.tilewidth; var th = tileset.tileheight; var iw = tileset.imagewidth - m; var ih = tileset.imageheight - m; //Drawing offsets var offset = (tileset.tileoffset == undefined) ? { x: 0, y: 0 } : tileset.tileoffset; //Calculate how many tiles there are in this tileset and thus how many different tile type there can be. for (var y = m; y < ih; y += th) { for (var x = m; x < iw; x += tw) { //Does the cell exist? Then use that. var cell = (atlas.cells[startingCell] == undefined) ? -1 : startingCell ; var tileType = this.createTileType(cell); tileType.offset.x = offset.x; tileType.offset.y = offset.y; startingCell++; //Increase the cell to use by one. } } //Add tile properties for (var tp in tileset.tileproperties) { var tileType = this.tileTypes[(parseInt(tileset.firstgid) + parseInt(tp))]; tileType.properties = tileset.tileproperties[tp]; } } } /** * Method to set the default TileMap properties. Useful when wanting to create tilemaps programmatically. * @method setTo * @param tileWidth {Number} The width of a single tile. * @param tileHeight {Number} The height of a single tile. * @param width {Number} The width of the whole map. * @param height {Number} The height of the whole map. * @public */ public setTo(tileWidth: number, tileHeight: number, width: number, height: number) { this.tileWidth = tileWidth; this.tileHeight = tileHeight; this.width = width; this.height = height; } /** *----------------------- * Creation of Tile Types *----------------------- **/ /** * Generates a single new TileType. Returns the TileType that was generated. * @method createTileType * @param [cell=-1] {Number} The cell that is to be used. Default is -1 (which means none) * @return {TileType} The TileType generated. * @public */ public createTileType(cell:number = -1):TileType { var tileType = new TileType(this, this.tileTypes.length, cell); this.tileTypes.push(tileType); return tileType; } /** * Creates a new TileType for each cell that you pass. * @method createTileTypes * @param cells {Number[]} The cells that you want a new TileType created for. * @return {TileTypes[]} The TileTypes generated. * @public */ public createTileTypes(cells:number[]):TileType[] { var types = []; for (var i = 0; i < cells.length; i++) { types.push( this.createTileType( cells[i] ) ); } return types; } /** * Used to create a number of TileTypes based starting cell number and how many you want from there. * @method createTileTypesByRange * @param cellStart {Number} The starting number of the cell. * @param range {Number} How many cells (from the starting cell) should be created. * @return {TileTypes[]} The TileTypes generated. */ public createTileTypesByRange(cellStart: number, range: number): TileType[]{ var types = []; for (var i = cellStart; i <= cellStart + range; i++) { types.push( this.createTileType( i ) ); } return types; } /** *----------------------- * Cell Modifications *----------------------- **/ /** * Changes a single cellIndex that a TileType is to use when it is rendered. * @method setCell * @param type {number} The number of the TileType that is to change. * @param cell {number} The new cellIndex it should have. * @public */ public setCell(type: number, cell: number) { this.tileTypes[type].cellIndex = cell; } /** * Changes a range of cellIndexs for Tiles the same range of TileTypes. * @method setCellsByRange * @param typeStart {number} The starting TileType that is to be modified. * @param cellStart {number} The starting cellIndex that the first TileType should have. * @param range {number} How many times it should run. * @public */ public setCellsByRange(typeStart: number, cellStart: number, range: number) { for (var i = typeStart; i < typeStart + range; i++) { this.tileTypes[i].cellIndex = cellStart; cellStart++; } } /** *----------------------- * Creation of Tilemap Layers *----------------------- **/ /** * Creates a new TileMapLayer with the details that are provided. * If no width/height/tileWidth/tileHeight parameters are passed then the values will be what this TileMap has. * If no 'data' is provided then the map will be automatically filled with empty Types of Tiles. * Returns the new TileMapLayer that was created. * @method createNewLayer * @param name {String} Name of the TileMap. * @param atlas {Kiwi.Textures.TextureAtlas} The TextureAtlas that this layer should use. * @param data {Number[]} The tile information. * @param [w=this.width] {Number} The width of the whole tile map. In Tiles. * @param [h=this.height] {Number} The height of the whole tile map. In Tiles. * @param [x=0] {Number} The position of the tilemap on the x axis. In pixels. * @param [y=0] {Number} The position of the tilemap on the y axis. In pixels. * @param [tw=this.tileWidth] {Number} The width of a single tile. * @param [th=this.tileHeight] {Number} The height of a single tile. * @param [orientation] {String} The orientation of the tilemap. Defaults to the same as this TileMap. * @return {TileMapLayer} The TileMapLayer that was created. * @public */ public createNewLayer(name: string, atlas: Kiwi.Textures.TextureAtlas, data: number[] = [], w: number = this.width, h: number = this.height, x: number = 0, y: number = 0, tw: number = this.tileWidth, th: number = this.tileHeight, orientation: string=this.orientation): TileMapLayer { //Did the user provide enough data? if (data.length < w * h) { //No... So push empty cells instead var i = data.length - 1; while (++i < w * h) { data.push(0); } } //Create the new layer var layer: TileMapLayer; if (orientation == ISOMETRIC) { layer = new Kiwi.GameObjects.Tilemap.TileMapLayerIsometric(this, name, atlas, data, tw, th, x, y, w, h); } else { layer = new Kiwi.GameObjects.Tilemap.TileMapLayerOrthogonal(this, name, atlas, data, tw, th, x, y, w, h); } //Add the new layer to the array this.layers.push(layer); return layer; } /** * Eventually will create a new object layer. Currently does nothing. * @method createNewObjectLayer * @public */ public createNewObjectLayer() { Kiwi.Log.log("OBJECT GROUP layers are currently not supported.", '#tilemap'); } /** * Eventually will create a new image layer. Currently does nothing. * @method createNewObjectLayer * @public */ public createNewImageLayer() { Kiwi.Log.log("IMAGE layers are currently not supported.", '#tilemap'); } /** *----------------------- * TileMapLayer Management Functions *----------------------- **/ /** * Get a layer by the name that it was given upon creation. * Returns null if no layer with that name was found. * @method getLayerByName * @param name {String} Name of the layer you would like to select. * @return {TileMapLayer} Either the layer with the name passed, or null if no Layer with that name was found. * @public */ public getLayerByName(name: string): TileMapLayer { for (var i = 0; i < this.layers.length; i++) { if (this.layers[i].name == name) { return this.layers[i]; } } return null; } /** * Returns the layer with the number associated with it in the layers array. * @method getLayer * @param num {Number} Number of the Layer you would like to get. * @return {TileMapLayer} * @public */ public getLayer(num: number): TileMapLayer { return (this.layers[num] !== undefined) ? this.layers[num] : null; } /** * The type of object that it is. * @method objType * @return {String} "TileMap" * @public */ public objType() { return "TileMap"; } } export var ISOMETRIC: string = "isometric"; export var ORTHOGONAL: string = "orthogonal"; }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormCampaign_Response { interface tab_new_campaign_response_Sections { description: DevKit.Controls.Section; details: DevKit.Controls.Section; summary: DevKit.Controls.Section; } interface tab_new_campaign_response extends DevKit.Controls.ITab { Section: tab_new_campaign_response_Sections; } interface Tabs { new_campaign_response: tab_new_campaign_response; } interface Body { Tab: Tabs; /** Enter the account, contact, or lead that submitted the campaign response, if it was received from an existing prospect or customer. */ Customer: DevKit.Controls.Lookup; /** Type additional information to describe the campaign response, such as key discussion points or objectives. */ Description: DevKit.Controls.String; /** Choose the parent campaign so that the campaign's response rate is tracked correctly. */ RegardingObjectId: DevKit.Controls.Lookup; /** Select the type of response from the prospect or customer to indicate their interest in the campaign. */ ResponseCode: DevKit.Controls.OptionSet; /** Type a short description about the objective or primary topic of the campaign response. */ Subject: DevKit.Controls.String; } } class FormCampaign_Response extends DevKit.IForm { /** * DynamicsCrm.DevKit form Campaign_Response * @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 Campaign_Response */ Body: DevKit.FormCampaign_Response.Body; } class CampaignResponseApi { /** * DynamicsCrm.DevKit CampaignResponseApi * @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; /** For internal use only. */ ActivityAdditionalParams: DevKit.WebApi.StringValue; /** Unique identifier of the campaign response. */ ActivityId: DevKit.WebApi.GuidValue; /** Type the number of minutes spent on this activity. The duration is used in reporting. */ ActualDurationMinutes: DevKit.WebApi.IntegerValue; /** Enter the date when the campaign response was actually completed. */ ActualEnd_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the actual start date and time for the campaign response. */ ActualStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Type a category to identify the campaign response type, such as new business development or customer retention, to tie the campaign response to a business group or function. */ Category: DevKit.WebApi.StringValue; /** Select how the response was received, such as phone, letter, fax, or email. */ ChannelTypeCode: DevKit.WebApi.OptionSetValue; /** Shows how contact about the social activity originated, such as from Twitter or Facebook. This field is read-only. */ Community: DevKit.WebApi.OptionSetValue; /** Type the name of the company if the campaign response was received from a new prospect or customer. */ CompanyName: DevKit.WebApi.StringValue; /** Unique identifier of the user who created the activity. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the activity was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the activitypointer. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the delivery of the activity was last attempted. */ DeliveryLastAttemptedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Priority of delivery of the activity to the email server. */ DeliveryPriorityCode: DevKit.WebApi.OptionSetValue; /** Type additional information to describe the campaign response, such as key discussion points or objectives. */ Description: DevKit.WebApi.StringValue; /** Type the responder's email address. */ EMailAddress: DevKit.WebApi.StringValue; /** The message id of activity which is returned from Exchange Server. */ ExchangeItemId: DevKit.WebApi.StringValue; /** 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; /** Shows the web link of Activity of type email. */ ExchangeWebLink: DevKit.WebApi.StringValue; /** Type the responder's fax number. */ Fax: DevKit.WebApi.StringValue; /** Type the responder's first name if the campaign response was received from a new prospect or customer. */ FirstName: DevKit.WebApi.StringValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Type of instance of a recurring series. */ InstanceTypeCode: DevKit.WebApi.OptionSetValueReadonly; /** Specifies whether the campaign response was billed as part of resolving a case. */ IsBilled: DevKit.WebApi.BooleanValue; /** For internal use only. */ IsMapiPrivate: DevKit.WebApi.BooleanValue; /** Information regarding whether the activity is a regular activity type or event type. */ IsRegularActivity: DevKit.WebApi.BooleanValueReadonly; /** Specifies whether the campaign response is created by a workflow rule. */ IsWorkflowCreated: DevKit.WebApi.BooleanValue; /** Type the responder's last name if the campaign response was received from a new prospect or customer. */ LastName: DevKit.WebApi.StringValue; /** Contains the date and time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Left the voice mail */ LeftVoiceMail: DevKit.WebApi.BooleanValue; /** Unique identifier of user who last modified the activity. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when activity was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the activitypointer. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows how long, in minutes, that the record was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** Choose the phone call, email, fax, letter, or appointment activity that led the prospect or customer to respond to the campaign. */ originatingactivityid_appointment: DevKit.WebApi.LookupValue; /** Choose the phone call, email, fax, letter, or appointment activity that led the prospect or customer to respond to the campaign. */ originatingactivityid_email: DevKit.WebApi.LookupValue; /** Choose the phone call, email, fax, letter, or appointment activity that led the prospect or customer to respond to the campaign. */ originatingactivityid_fax: DevKit.WebApi.LookupValue; /** Choose the phone call, email, fax, letter, or appointment activity that led the prospect or customer to respond to the campaign. */ originatingactivityid_letter: DevKit.WebApi.LookupValue; /** Choose the phone call, email, fax, letter, or appointment activity that led the prospect or customer to respond to the campaign. */ originatingactivityid_phonecall: DevKit.WebApi.LookupValue; OriginatingActivityName: 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; /** Unique identifier of the business unit that owns the activity. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team that owns the activity. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user that owns the activity. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** For internal use only. */ PostponeActivityProcessingUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.WebApi.OptionSetValue; /** Unique identifier of the Process. */ ProcessId: DevKit.WebApi.GuidValue; /** Type a promotional code to track sales related to the campaign response or to allow the responder to redeem a discount offer. */ PromotionCodeName: DevKit.WebApi.StringValue; /** Enter the date when the campaign response was received. */ ReceivedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Choose the parent campaign so that the campaign's response rate is tracked correctly. */ regardingobjectid_bulkoperation_campaignresponse: DevKit.WebApi.LookupValue; /** Choose the parent campaign so that the campaign's response rate is tracked correctly. */ regardingobjectid_campaign_campaignresponse: DevKit.WebApi.LookupValue; /** Select the type of response from the prospect or customer to indicate their interest in the campaign. */ ResponseCode: DevKit.WebApi.OptionSetValue; /** Scheduled duration of the campaign response in minutes. */ ScheduledDurationMinutes: DevKit.WebApi.IntegerValueReadonly; /** Enter the expected due date and time for the activity to be completed to provide details about the timing of the campaign response. */ ScheduledEnd_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the expected start date and time for the activity to provide details about the timing of the campaign response. */ ScheduledStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Unique identifier of the mailbox associated with the sender of the email message. */ SenderMailboxId: DevKit.WebApi.LookupValueReadonly; /** Date and time when the activity was sent. */ SentOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Uniqueidentifier specifying the id of recurring series of an instance. */ SeriesId: DevKit.WebApi.GuidValueReadonly; /** Unique identifier for the associated service. */ ServiceId: DevKit.WebApi.LookupValue; /** Choose the service level agreement (SLA) that you want to apply to the case record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this case. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Shows the date and time by which the activities are sorted. */ SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the Stage. */ StageId: DevKit.WebApi.GuidValue; /** Shows whether the campaign response is open, closed, or canceled. Closed and canceled campaign responses are read-only and can't be edited. */ StateCode: DevKit.WebApi.OptionSetValue; /** Select the campaign response's status. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Type a subcategory to identify the campaign response type and relate the activity to a specific product, sales region, business group, or other function. */ Subcategory: DevKit.WebApi.StringValue; /** Type a short description about the objective or primary topic of the campaign response. */ Subject: DevKit.WebApi.StringValue; /** Type the responder's primary phone number. */ Telephone: DevKit.WebApi.StringValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** For internal use only. */ TraversedPath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version number of the activity. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** Type the phonetic spelling of the company name, if specified in Japanese, to make sure the name is pronounced correctly in phone calls and other communications. */ YomiCompanyName: DevKit.WebApi.StringValue; /** Type the phonetic spelling of the campaign responder's first name, if specified in Japanese, to make sure the name is pronounced correctly in phone calls and other communications. */ YomiFirstName: DevKit.WebApi.StringValue; /** Type the phonetic spelling of the campaign responder's last name, if specified in Japanese, to make sure the name is pronounced correctly in phone calls and other communications. */ YomiLastName: DevKit.WebApi.StringValue; /** The array of object that can cast object to ActivityPartyApi class */ ActivityParties: Array<any>; } } declare namespace OptionSet { namespace CampaignResponse { enum ChannelTypeCode { /** 5 */ Appointment, /** 1 */ Email, /** 3 */ Fax, /** 4 */ Letter, /** 6 */ Others, /** 2 */ Phone } enum Community { /** 5 */ Cortana, /** 6 */ Direct_Line, /** 8 */ Direct_Line_Speech, /** 9 */ Email, /** 1 */ Facebook, /** 10 */ GroupMe, /** 11 */ Kik, /** 3 */ Line, /** 7 */ Microsoft_Teams, /** 0 */ Other, /** 13 */ Skype, /** 14 */ Slack, /** 12 */ Telegram, /** 2 */ Twitter, /** 4 */ Wechat, /** 15 */ WhatsApp } enum DeliveryPriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum InstanceTypeCode { /** 0 */ Not_Recurring, /** 3 */ Recurring_Exception, /** 4 */ Recurring_Future_Exception, /** 2 */ Recurring_Instance, /** 1 */ Recurring_Master } enum PriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum ResponseCode { /** 3 */ Do_Not_Send_Marketing_Materials, /** 4 */ Error, /** 1 */ Interested, /** 2 */ Not_Interested } enum StateCode { /** 2 */ Canceled, /** 1 */ Closed, /** 0 */ Open } enum StatusCode { /** 3 */ Canceled, /** 2 */ Closed, /** 1 */ Open } 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':['Campaign Response'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { parseBinaryStructure, readBinaryFields, writeBinaryFields } from "./binary_table"; import { BroadcasterDatabase } from "./broadcaster_database"; import { Resources } from "./resource"; type NvramAccessId = "broadcaster_id" | // 事業者ごと(BSとCS) "original_network_id" | // ネットワークごと(地上波とCS) "affiliation_id"; // 系列ごと(地上波) type NvramPermission = "" | "r" | "rw"; type BroadcastType = "GR" | "BS" | "CS"; type NvramArea = { broadcastType: BroadcastType, // nvram://id;aaa/bbb/<block number> // ~~ここ prefixId: NvramAccessId | null, // nvram://aaa/bbb/<block number> // ~~~~~~~ここ prefix: string, startBlock: number, lastBlock: number, // 大きさ(バイト) size: number, // 固定領域 isFixed: boolean, // 事業者ごとに保存されるといった情報 // 共通であれば[] accessId: NvramAccessId[], // nvrams:// isSecure: boolean, permissions: { [broadcastType in BroadcastType]: NvramPermission }, }; const nvramAreas: NvramArea[] = [ // 地上波 // 地上デジタルテレビジョン放送事業者系列専用領域 { broadcastType: "GR", prefixId: "affiliation_id", prefix: "group", startBlock: 0, lastBlock: 63, size: 64, isFixed: true, accessId: ["affiliation_id"], permissions: { "GR": "rw", "BS": "rw", "CS": "", }, isSecure: false, }, // 地上デジタルテレビジョン放送事業者専用領域 { broadcastType: "GR", prefixId: null, prefix: "local", startBlock: 0, lastBlock: 63, size: 64, isFixed: true, accessId: ["original_network_id"], permissions: { "GR": "rw", "BS": "", "CS": "", }, isSecure: false, }, // 地上デジタルテレビジョン放送事業者専用放送通信共通領域 { broadcastType: "GR", prefixId: null, prefix: "local_web", startBlock: 0, lastBlock: 31, size: 64, isFixed: true, accessId: ["original_network_id"], permissions: { "GR": "rw", "BS": "", "CS": "", }, isSecure: false, }, // 地上デジタルテレビジョン放送事業者共通領域 { broadcastType: "GR", prefixId: null, prefix: "tr_common", startBlock: 0, lastBlock: 31, size: 64, isFixed: true, accessId: [], permissions: { "GR": "rw", "BS": "r", "CS": "", }, isSecure: false, }, // BS事業者共通領域 { broadcastType: "BS", prefixId: null, prefix: "common", startBlock: 0, lastBlock: 15, size: 64, isFixed: true, accessId: [], permissions: { "GR": "r", "BS": "rw", "CS": "", }, isSecure: false, }, // BS事業者専用領域 { broadcastType: "BS", prefixId: null, prefix: "~", startBlock: 0, lastBlock: 15, size: 64, isFixed: true, accessId: ["broadcaster_id"], permissions: { "GR": "", "BS": "rw", "CS": "rw", }, isSecure: false, }, // BS事業者専用領域 { broadcastType: "BS", prefixId: null, prefix: "~/ext", startBlock: 16, lastBlock: 63, size: 64, isFixed: true, accessId: ["broadcaster_id"], permissions: { "GR": "", "BS": "rw", "CS": "rw", }, isSecure: false, }, // BSデジタル放送事業者専用放送通信共通領域 { broadcastType: "BS", prefixId: null, prefix: "local_web", startBlock: 0, lastBlock: 31, size: 64, isFixed: true, accessId: ["broadcaster_id"], permissions: { "GR": "", "BS": "rw", "CS": "", }, isSecure: false, }, // 広帯域CSデジタル放送事業者共通領域 { broadcastType: "CS", prefixId: null, prefix: "cs_common", startBlock: 0, lastBlock: 31, size: 64, isFixed: true, accessId: [], permissions: { "GR": "r", "BS": "rw", "CS": "", }, isSecure: false, }, // 広帯域CSデジタル放送事業者専用領域 { broadcastType: "CS", prefixId: null, prefix: "~", startBlock: 0, lastBlock: 46, size: 64, isFixed: true, accessId: ["original_network_id", "broadcaster_id"], permissions: { "GR": "", "BS": "rw", "CS": "rw", }, isSecure: true, }, // 広帯域CSデジタル放送事業者専用放送通信共通領域 { broadcastType: "CS", prefixId: null, prefix: "local_web", startBlock: 0, lastBlock: 15, size: 64, isFixed: true, accessId: ["broadcaster_id"], permissions: { "GR": "", "BS": "", "CS": "rw", }, isSecure: false, }, ]; // nullは不明 type BroadcasterInfo = { affiliationId?: number[] | null, originalNetworkId?: number | null, broadcasterId?: number | null, broadcastType?: BroadcastType | null, serviceId?: number | null, }; type AccessInfo = { affiliationId?: number | null, originalNetworkId?: number | null, broadcasterId?: number | null, broadcastType?: BroadcastType | null, block?: number | null, }; export class NVRAM { resources: Resources; broadcasterDatabase: BroadcasterDatabase; prefix: string; constructor(resources: Resources, broadcasterDatabase: BroadcasterDatabase, prefix?: string) { this.resources = resources; this.broadcasterDatabase = broadcasterDatabase; this.prefix = prefix ?? "nvram_"; } private getBroadcasterInfo(): BroadcasterInfo { const bid = this.broadcasterDatabase.getBroadcasterId(this.resources.originalNetworkId, this.resources.serviceId); return { originalNetworkId: this.resources.originalNetworkId, affiliationId: this.broadcasterDatabase.getAffiliationIdList(this.resources.originalNetworkId, bid), broadcasterId: bid, serviceId: this.resources.serviceId, }; } private findNvramArea(url: string, broadcasterInfo: BroadcasterInfo): [AccessInfo, NvramArea] | null { const match = url.match(/^nvrams?:\/\/((?<affiliationId>[0-9a-fA-F]{2});)?(?<prefix>.+)\/(?<block>\d+)$/); if (!match?.groups) { return null; } const isSecure = url.startsWith("nvrams://"); let affiliationId: number | null = parseInt(match?.groups.affiliationId, 16); if (!Number.isFinite(affiliationId)) { affiliationId = null; } const prefix = match?.groups.prefix; const block = parseInt(match?.groups.block) ?? -1; for (const area of nvramAreas) { if (prefix === area.prefix && area.isSecure === isSecure) { if (area.startBlock <= block && area.lastBlock >= block) { return [ { block, affiliationId, originalNetworkId: broadcasterInfo.originalNetworkId, broadcasterId: broadcasterInfo.broadcasterId, broadcastType: broadcasterInfo.broadcastType }, area ]; } } } return null; } private getLocalStorageKey(broadcasterInfo: BroadcasterInfo, accessInfo: AccessInfo, nvramArea: NvramArea): string | null { const params = new URLSearchParams(); for (const a of nvramArea.accessId) { if (a === "affiliation_id") { if (broadcasterInfo.affiliationId == null) { console.error("affiliationId == null!"); params.append("affiliation_id", String(accessInfo.affiliationId)); } else if (broadcasterInfo.affiliationId.includes(accessInfo.affiliationId!)) { params.append("affiliation_id", String(accessInfo.affiliationId)); } else { console.error("permission denied (affiliationId)", broadcasterInfo.affiliationId, accessInfo.affiliationId); return null; } } else if (a === "broadcaster_id") { if (accessInfo.broadcasterId == null) { console.error("broadcasterId == null!"); params.append("broadcaster_id", "null"); } else { params.append("broadcaster_id", String(accessInfo.broadcasterId)); } } else if (a === "original_network_id") { if (accessInfo.originalNetworkId == null) { console.error("originalNetworkId == null!"); params.append("original_network_id", "null"); } else { params.append("original_network_id", String(accessInfo.originalNetworkId)); } } } params.append("prefix", nvramArea.prefix); if (accessInfo.block != null) { params.append("block", String(accessInfo.block)); } if (nvramArea.isSecure) { params.append("secure", "true"); const key = `${broadcasterInfo.originalNetworkId}.${broadcasterInfo.broadcasterId}`; const blockPermission = this.providerAreaPermission.get(key); if (blockPermission == null) { console.error("permission not set (nvrams)"); return null; } if (accessInfo.block != null) { const allowedServiceId = blockPermission.serviceIdList[accessInfo.block]; if (allowedServiceId !== 0xffff && allowedServiceId !== broadcasterInfo.serviceId) { console.error("permission denied (nvrams serviceId)", allowedServiceId, broadcasterInfo.serviceId); return null; } } } return params.toString(); } private readNVRAM(uri: string): Uint8Array | null { let strg: string | null; let isFixed: boolean; let size: number; if (uri === "nvram://receiverinfo/zipcode") { strg = localStorage.getItem(this.prefix + "prefix=receiverinfo%2Fzipcode"); isFixed = true; size = 7; } else if (uri === "nvram://receiverinfo/prefecture") { strg = localStorage.getItem(this.prefix + "prefix=receiverinfo%2Fprefecture"); if (strg == null || strg.length === 0) { strg = window.btoa(String.fromCharCode(255)); } isFixed = true; size = 1; } else if (uri === "nvram://receiverinfo/regioncode") { strg = localStorage.getItem(this.prefix + "prefix=receiverinfo%2Fregioncode"); if (strg == null || strg.length === 0) { strg = window.btoa(String.fromCharCode(0) + String.fromCharCode(0)); } isFixed = true; size = 2; } else { const binfo = this.getBroadcasterInfo(); const result = this.findNvramArea(uri, binfo); if (!result) { console.error("readNVRAM: findNvramArea failed", uri); return null; } const [id, area] = result; const k = this.getLocalStorageKey(binfo, id, area); if (!k) { console.error("readNVRAM: access denied", uri); return null; } strg = localStorage.getItem(this.prefix + k); if (strg != null && area.isSecure) { const serviceId = Number.parseInt(strg.split(",")[0]); // 更新時に異なるs_idの時はブロック内データを初期化(内部動作)? if (serviceId !== 0xffff && serviceId !== binfo.serviceId) { strg = ""; } else { strg = strg.split(",")[1] ?? ""; } } isFixed = area.isFixed; size = area.size; } if (!strg) { return new Uint8Array(isFixed ? size : 0); } const a = Uint8Array.from(window.atob(strg), c => c.charCodeAt(0)); if (isFixed) { if (a.length > size) { return a.subarray(0, size); } else if (a.length < size) { const fixed = new Uint8Array(size); fixed.set(a); return fixed; } } return a; } private writeNVRAM(uri: string, data: Uint8Array, force: boolean): number { // 書き込めない (TR-B14 第二分冊 5.2.7 表5-2参照) if (uri === "nvram://receiverinfo/prefecture") { if (!force) { return NaN; } localStorage.setItem(this.prefix + "prefix=receiverinfo%2Fprefecture", window.btoa(String.fromCharCode(...data).substring(0, 1))); return data.length; } else if (uri === "nvram://receiverinfo/regioncode") { if (!force) { return NaN; } localStorage.setItem(this.prefix + "prefix=receiverinfo%2Fregioncode", window.btoa(String.fromCharCode(...data).substring(0, 2))); return data.length; // 書き込める (TR-B14 第二分冊 5.2.7 表5-2参照) } else if (uri === "nvram://receiverinfo/zipcode") { localStorage.setItem(this.prefix + "prefix=receiverinfo%2Fzipcode", window.btoa(String.fromCharCode(...data).substring(0, 7))); return data.length; } const binfo = this.getBroadcasterInfo(); const result = this.findNvramArea(uri, binfo); if (!result) { console.error("writeNVRAM: findNvramArea failed", uri); return NaN; } const [id, area] = result; if (area.isFixed) { if (data.length > area.size) { console.error("writeNVRAM: too large data", uri, data.length, area); return NaN; } } const k = this.getLocalStorageKey(binfo, id, area); if (!k) { console.error("writeNVRAM: access denied", uri); return NaN; } if (area.isSecure && id.block != null) { const key = `${binfo.originalNetworkId}.${binfo.broadcasterId}`; const blockPermission = this.providerAreaPermission.get(key); const allowedServiceId = blockPermission?.serviceIdList[id.block]; localStorage.setItem(this.prefix + k, allowedServiceId + "," + window.btoa(String.fromCharCode(...data))); } else { localStorage.setItem(this.prefix + k, window.btoa(String.fromCharCode(...data))); } return data.length; } public readPersistentArray(filename: string, structure: string): any[] | null { if (!filename?.startsWith("nvram://")) { return null; } const fields = parseBinaryStructure(structure); if (!fields) { return null; } const a = this.readNVRAM(filename); if (!a) { return null; } let [result, _] = readBinaryFields(a, fields); return result; } public writePersistentArray(filename: string, structure: string, data: any[], period?: Date, force?: boolean): number { if (!filename?.startsWith("nvram://")) { return NaN; } const fields = parseBinaryStructure(structure); if (!fields) { return NaN; } if (fields.length > data.length) { console.error("writePersistentArray: fields.length > data.length"); return NaN; } let bin = writeBinaryFields(data, fields); return this.writeNVRAM(filename, bin, force ?? false); } // key: <original_network_id>.<broadcaster_id> // value: <service_id> private providerAreaPermission = new Map<string, { lastUpdated: number, serviceIdList: number[] }>(); public cspSetAccessInfoToProviderArea(data: Uint8Array): boolean { const structure = parseBinaryStructure("S:1V,U:2B")!; const binfo = this.getBroadcasterInfo(); if (binfo.originalNetworkId == null || binfo.broadcasterId == null) { return false; } const key = `${binfo.originalNetworkId}.${binfo.broadcasterId}`; let off = 0; let update: string | undefined; let serviceIdList: number[] = []; while (off < data.length) { const [result, readBits] = readBinaryFields(data.subarray(off), structure); if (off === 0) { update = result[0] as string; } serviceIdList.push(result[1] as number); off += readBits / 8; } if (serviceIdList.length < 47) { return false; } if (update?.length !== 12) { return false; } const year = Number.parseInt(update.substring(0, 4)); const month = Number.parseInt(update.substring(4, 6)); const day = Number.parseInt(update.substring(6, 8)); const hour = Number.parseInt(update.substring(8, 10)); const minute = Number.parseInt(update.substring(10, 12)); const date = new Date(year, month - 1, day, hour, minute); const time = date.getTime(); const tz = date.getTimezoneOffset() * 60 * 1000; const jst = 9 * 60 * 60 * 1000; const updateTime = time - tz - jst; const currentTime = this.resources.currentTimeUnixMillis ?? new Date().getTime(); if (currentTime < updateTime) { return false; } // 保存しておいた方がいいけど結局毎回SetAccessInfoToProviderArea呼ばれるのでそこまで重要ではない this.providerAreaPermission.set(key, { serviceIdList, lastUpdated: updateTime }); return true; } public readPersistentArrayWithAccessCheck(filename: string, structure: string): any[] | null { if (!filename?.startsWith("nvrams://")) { return null; } const fields = parseBinaryStructure(structure); if (!fields) { return null; } const a = this.readNVRAM(filename); if (!a) { return null; } let [result, _] = readBinaryFields(a, fields); return result; } public writePersistentArrayWithAccessCheck(filename: string, structure: string, data: any[], period?: Date): number { if (!filename?.startsWith("nvrams://")) { return NaN; } const fields = parseBinaryStructure(structure); if (!fields) { return NaN; } if (fields.length > data.length) { console.error("writePersistentArrayWithAccessCheck: fields.length > data.length"); return NaN; } let bin = writeBinaryFields(data, fields); return this.writeNVRAM(filename, bin, false); } public checkAccessInfoOfPersistentArray(uri: string): number { if (uri === "nvram://receiverinfo/zipcode") { return 2; } else if (uri === "nvram://receiverinfo/regioncode") { return 1; } else if (uri === "nvram://receiverinfo/prefecture") { return 1; } else { const binfo = this.getBroadcasterInfo(); const result = this.findNvramArea(uri, binfo); if (!result) { return NaN; } const [id, area] = result; const k = this.getLocalStorageKey(binfo, id, area); if (!k) { return 0; } return 2; // FIXME 読み書き判定(broadcastType) } } }
the_stack
import * as React from "react"; import * as Utility from "../Utility"; import { AppState } from "../States/AppState"; import * as $ from "jquery"; import { BrowserRouter as Router, Route, Link, withRouter, } from "react-router-dom"; import { match } from "react-router"; import { RouteComponent } from "./RouteComponent"; import { UbbEditor } from "./UbbEditor"; import { Constants } from "./Constant"; import store from "../Store"; import * as ErrorActions from "../Actions/Error"; import { Vote, props as VoteProps } from "./EditVoteIput"; import ReactMde, { ReactMdeTypes, ReactMdeCommands, } from "@cc98/hell-react-mde"; import * as Showdown from "showdown"; import CustomCommand from "./react-mde/imageUploaderCommand"; import { Button, Modal, Form, DatePicker, TimePicker, Select, Input, Radio, } from "antd"; import * as moment from "moment"; const { MonthPicker, RangePicker } = DatePicker; const { Option } = Select; const { TextArea } = Input; class EditForm extends RouteComponent< { history; form }, { topicInfo; boardName; tags; ready; mode; content; title; postInfo; tag1; tag2; fetchState; boardId; type; masters: string[]; voteInfo: VoteProps["voteInfo"]; mdeState; commands; notice; houseTmpVisible; /** 发帖版面的匿名状态,包括不可匿名,可选匿名和强制匿名 */ anonymousState; /** 编辑帖子是否为匿名 */ isAnonymous; }, { mode: string; id: number } > { converter: Showdown.Converter; constructor(props) { super(props); this.update = this.update.bind(this); this.changeEditor = this.changeEditor.bind(this); this.editUBB = this.editUBB.bind(this); this.changeAcademicType = this.changeAcademicType.bind(this); this.changeActivityType = this.changeActivityType.bind(this); this.changeNormalType = this.changeNormalType.bind(this); this.onVoteInfoChange = this.onVoteInfoChange.bind(this); this.converter = new Showdown.Converter({ tables: true, simplifiedAutoLink: true, }); this.state = { masters: [], tags: [], boardName: "", ready: false, mode: 0, content: "", title: "", postInfo: { floor: 0, title: "", content: "", contentType: 0 }, tag1: "", tag2: "", fetchState: "ok", boardId: 1, type: 0, topicInfo: {}, voteInfo: { voteItems: ["", ""], expiredDays: 0, maxVoteCount: 0, needVote: false, }, mdeState: "", commands: [], notice: true, houseTmpVisible: false, anonymousState: 0, isAnonymous: false, }; } async componentDidMount() { const mode = this.match.params.mode; const id = this.match.params.id; const token = await Utility.getToken(); const headers = new Headers(); headers.append("Authorization", token); let url, response, data, tags; CustomCommand.editor = this; const getCommands: () => ReactMdeTypes.CommandGroup[] = () => [ { commands: [CustomCommand] }, ]; const defaultCommands = ReactMdeCommands.getDefaultCommands(); const myCommands = defaultCommands.concat(getCommands()); myCommands[1].commands.length = 3; this.setState({ commands: myCommands }); switch (mode) { case "postTopic": case "postVoteTopic": url = `/Board/${id}`; response = await Utility.cc98Fetch(url, { headers }); data = await response.json(); const boardName = data.name; const anonymousState = data.anonymousState; //获取标签 tags = await Utility.getBoardTag(id); this.setState({ boardName: boardName, tags: tags, boardId: id, masters: data.boardMasters, anonymousState: anonymousState, }); break; case "edit": url = `/post/${id}/original`; response = await Utility.cc98Fetch(url, { headers }); if (response.status === 403) { this.setState({ fetchState: "not allowed" }); } data = await response.json(); const topicInfo = await Utility.getTopicInfo(data.topicId); let tag1Name = await Utility.getTagNamebyId(topicInfo.tag1); if (!tag1Name) tag1Name = ""; let tag2Name = await Utility.getTagNamebyId(topicInfo.tag2); if (!tag2Name) tag2Name = ""; let type = topicInfo.type; tags = await Utility.getBoardTag(data.boardId); Utility.setLocalStorage("contentCache", data.content); const cache = Utility.getLocalStorage("contentCache"); console.log("cache after saving = " + cache); //console.log(tags); url = `/Board/${data.boardId}`; response = await Utility.cc98Fetch(url, { headers }); let masters = (await response.json()).boardMasters; if ( Utility.getLocalStorage("userInfo") && !( Utility.isMaster(masters) || (Utility.getLocalStorage("userInfo").userTitleIds || []).indexOf( 91 ) !== -1 ) && type === 1 ) { type = 0; } const boardName1 = await Utility.getBoardName(data.boardId); if (data.contentType === 0) { this.setState({ masters, postInfo: data, content: data.content, title: data.title, boardName: boardName1, boardId: data.boardId, type: type, tags: tags, topicInfo: topicInfo, tag1: tag1Name, tag2: tag2Name, mode: 0, notice: topicInfo.notifyPoster, isAnonymous: data.isAnonymous, }); } else this.setState({ masters, postInfo: data, content: data.content, title: data.title, boardName: boardName1, boardId: data.boardId, type: type, tags: tags, topicInfo: topicInfo, tag1: tag1Name, tag2: tag2Name, mode: 1, mdeState: data.content, notice: topicInfo.notifyPoster, isAnonymous: data.isAnonymous, }); break; } } handleValueChange = (value) => { this.setState({ mdeState: value }); }; changeNormalType() { this.setState({ type: 0 }); } changeAcademicType() { this.setState({ type: 2 }); } changeActivityType() { this.setState({ type: 1 }); } ready() { this.setState({ ready: true }); } changeEditor() { if (!confirm("切换编辑器会丢失您之前的编辑内容,确定要切换吗?")) { return; } if (this.state.mode === 0) { console.log("change mode to 1"); this.setState({ mode: 1 }); } else { console.log("change mode to 2"); this.setState({ mode: 0 }); } } update(value) { this.setState({ content: value }); } /** 发送markdown主题 */ sendMdTopic = async (isAnonymous: boolean) => { //投票帖禁止匿名 let _isAnonymous = isAnonymous; if (this.match.params.mode === "postVoteTopic") { _isAnonymous = false; // 投票内容发布前检查合法性 const info = Vote.isFormIllegal(this.state.voteInfo); if (info) { alert(info); return null; } } //检查标题 if (this.state.title == "") { alert("请输入标题!"); } else { try { let tag1Id, tag2Id; let url = `/board/${this.match.params.id}/topic`; let c = this.state.mdeState; let content; const type = this.state.type; tag1Id = await Utility.getTagIdbyName(this.state.tag1); tag2Id = await Utility.getTagIdbyName(this.state.tag2); if (tag1Id && !tag2Id) { content = { content: c, contentType: 1, title: this.state.title, tag1: tag1Id, type: this.state.type, notifyPoster: this.state.notice, isAnonymous: _isAnonymous, }; } else if (tag2Id) { content = { content: c, contentType: 1, title: this.state.title, tag1: tag1Id, tag2: tag2Id, type: this.state.type, notifyPoster: this.state.notice, isAnonymous: _isAnonymous, }; } else { content = { content: c, contentType: 1, title: this.state.title, type: this.state.type, notifyPoster: this.state.notice, isAnonymous: _isAnonymous, }; } if (this.match.params.mode === "postVoteTopic") { // 投票内容 content = { ...content, isVote: true, voteInfo: this.state.voteInfo, }; } let contentJson = JSON.stringify(content); let token = await Utility.getToken(); let myHeaders = new Headers(); myHeaders.append("Authorization", token); myHeaders.append("Content-Type", "application/json"); let mes = await Utility.cc98Fetch(url, { method: "POST", headers: myHeaders, body: contentJson, }); if (mes.status === 402) { alert("请输入内容"); } if (mes.status === 400) { alert("你的财富值余额不足,在本版面发表匿名主题需要10000财富值"); } // testEditor.setMarkdown(""); const topicId = await mes.text(); //根据返回的topicid,发送@信息 const atUsers = Utility.atHanderler(c); //如果存在合法的@,则发送@信息,否则不发送,直接跳转至所发帖子 if (atUsers) { const tempData = await Utility.getTopicContent(Number(topicId), 1); const firstFloor = tempData[0]; const postId = firstFloor.id; const atUsersJSON = JSON.stringify(atUsers); const url2 = `/notification/at?topicid=${topicId}&postid=${postId}`; let myHeaders2 = new Headers(); myHeaders2.append("Content-Type", "application/json"); myHeaders2.append("Authorization", token); let response2 = await Utility.cc98Fetch(url2, { method: "POST", headers: myHeaders2, body: atUsersJSON, }); } Utility.removeLocalStorage("contentCache"); this.props.history.push(`/topic/${topicId}`); } catch (e) { console.log(e); } } }; /** 发送ubb主题 */ sendUbbTopic = async (isAnonymous: boolean) => { //投票帖禁止匿名 let _isAnonymous = isAnonymous; if (this.match.params.mode === "postVoteTopic") { _isAnonymous = false; //投票内容发布前检查合法性 const info = Vote.isFormIllegal(this.state.voteInfo); if (info) { alert(info); return null; } } //检查标题 if (this.state.title == "") { alert("请输入标题!"); } else { const url = `/board/${this.match.params.id}/topic`; let content; let tag1Id, tag2Id; //console.log(this.state); tag1Id = await Utility.getTagIdbyName(this.state.tag1); tag2Id = await Utility.getTagIdbyName(this.state.tag2); if (tag1Id && !tag2Id) { content = { content: this.state.content, contentType: 0, title: this.state.title, tag1: tag1Id, type: this.state.type, notifyPoster: this.state.notice, isAnonymous: _isAnonymous, }; } else if (tag2Id) { content = { content: this.state.content, contentType: 0, title: this.state.title, tag1: tag1Id, tag2: tag2Id, type: this.state.type, notifyPoster: this.state.notice, isAnonymous: _isAnonymous, }; } else { content = { content: this.state.content, contentType: 0, title: this.state.title, type: this.state.type, notifyPoster: this.state.notice, isAnonymous: _isAnonymous, }; } if (this.match.params.mode === "postVoteTopic") { // 投票内容 content = { ...content, isVote: true, voteInfo: this.state.voteInfo, }; } const contentJson = JSON.stringify(content); const token = await Utility.getToken(); let myHeaders = new Headers(); myHeaders.append("Authorization", token); myHeaders.append("Content-Type", "application/json"); let response = await Utility.cc98Fetch(url, { method: "POST", headers: myHeaders, body: contentJson, }); //发帖成功,api返回topicid const topicId = await response.text(); console.log("topicid=" + topicId); if (topicId === "cannot_post_in_this_board") store.dispatch(ErrorActions.throwError("CannotPost")); else { //根据返回的topicid,发送@信息 const atUsers = Utility.atHanderler(this.state.content); //如果存在合法的@,则发送@信息,否则不发送,直接跳转至所发帖子 if (atUsers) { const tempData = await Utility.getTopicContent(Number(topicId), 1); const firstFloor = tempData[0]; const postId = firstFloor.id; const atUsersJSON = JSON.stringify(atUsers); const url2 = `/notification/at?topicid=${topicId}&postid=${postId}`; let myHeaders2 = new Headers(); myHeaders2.append("Content-Type", "application/json"); myHeaders2.append("Authorization", token); let response2 = await Utility.cc98Fetch(url2, { method: "POST", headers: myHeaders2, body: atUsersJSON, }); } Utility.removeLocalStorage("contentCache"); this.props.history.push(`/topic/${topicId}`); } } }; sendOnymousUbbTopic = () => { this.sendUbbTopic(false); }; sendAnonymousUbbTopic = () => { this.sendUbbTopic(true); }; sendOnymousMdTopic = () => { this.sendMdTopic(false); }; sendAnonymousMdTopic = () => { this.sendMdTopic(true); }; /** 编辑ubb帖子 */ async editUBB() { const url = `/post/${this.match.params.id}`; let tag1Id, tag2Id, content; //console.log(this.state); tag1Id = await Utility.getTagIdbyName(this.state.tag1); tag2Id = await Utility.getTagIdbyName(this.state.tag2); if (tag1Id && !tag2Id) { content = { content: this.state.content, contentType: 0, title: this.state.title, tag1: tag1Id, type: this.state.type, notifyPoster: this.state.notice, }; } else if (tag2Id) { content = { content: this.state.content, contentType: 0, title: this.state.title, tag1: tag1Id, tag2: tag2Id, type: this.state.type, notifyPoster: this.state.notice, }; } else { content = { content: this.state.content, contentType: 0, title: this.state.title, type: this.state.type, notifyPoster: this.state.notice, }; } const body = JSON.stringify(content); const token = await Utility.getToken(); const headers = await Utility.formAuthorizeHeader(); headers.append("Content-Type", "application/json"); const response = await Utility.cc98Fetch(url, { method: "PUT", headers, body, }); const floor = this.state.postInfo.floor; const pageFloor = floor % 10 === 0 ? 10 : floor % 10; const page = floor % 10 === 0 ? floor / 10 : (floor - (floor % 10)) / 10 + 1; Utility.removeLocalStorage("contentCache"); const redirectUrl = `/topic/${this.state.postInfo.topicId}/${page}#${pageFloor}`; this.props.history.push(redirectUrl); } /** 编辑markdown帖子 */ async editMd() { const url = `/post/${this.match.params.id}`; let c = this.state.mdeState; let content, tag1Id, tag2Id; tag1Id = await Utility.getTagIdbyName(this.state.tag1); tag2Id = await Utility.getTagIdbyName(this.state.tag2); if (tag1Id && !tag2Id) { tag1Id = await Utility.getTagIdbyName(this.state.tag1); content = { content: c, contentType: 1, title: this.state.title, tag1: tag1Id, type: this.state.type, notifyPoster: this.state.notice, }; } else if (tag2Id) { content = { content: c, contentType: 1, title: this.state.title, tag1: tag1Id, tag2: tag2Id, type: this.state.type, notifyPoster: this.state.notice, }; } else { content = { content: c, contentType: 1, title: this.state.title, type: this.state.type, notifyPoster: this.state.notice, }; } const body = JSON.stringify(content); const token = await Utility.getToken(); const headers = await Utility.formAuthorizeHeader(); headers.append("Content-Type", "application/json"); const response = await Utility.cc98Fetch(url, { method: "PUT", headers, body, }); const floor = this.state.postInfo.floor; const pageFloor = floor % 10 === 0 ? 10 : floor % 10; const page = floor % 10 === 0 ? floor / 10 : (floor - (floor % 10)) / 10 + 1; const redirectUrl = `/topic/${this.state.postInfo.topicId}/${page}#${pageFloor}`; Utility.removeLocalStorage("contentCache"); this.props.history.push(redirectUrl); } onTitleChange(title, tag1, tag2) { //console.log("handle change"); //console.log("tag1=" + tag1); if (title != "") this.setState({ title: title, tag1: tag1, tag2: tag2 }); else this.setState({ tag1: tag1, tag2: tag2 }); } onUbbChange(content) { this.setState({ content: content }); } onVoteInfoChange(voteInfo: VoteProps["voteInfo"]) { this.setState({ voteInfo }); } setValue = (v) => { this.setState({ mdeState: this.state.mdeState + v }, () => { this.setState({ mdeState: this.state.mdeState }); }); }; notNotice = async () => { this.setState({ notice: !this.state.notice }); }; showModal = () => { this.setState({ houseTmpVisible: true, }); }; handleOk = (e) => { console.log(e); this.setState({ houseTmpVisible: false, }); }; handleCancel = (e) => { console.log(e); this.setState({ houseTmpVisible: false, }); }; handleTmpForm = (e) => { console.log("===="); console.log(e); console.log(e.validDate[0]); console.log(); const content = `[table] [tr][th]序号[/th][th]信息项[/th][th]描述[/th][/tr] [tr][td]01[/td][td]有效日期[/td][td]${moment(e.validDate[0]).format( "YYYY-MM-DD" )}-${moment(e.validDate[1]).format("YYYY-MM-DD")}[/td][/tr] [tr][td]02[/td][td]类型[/td][td]${e.type || ""}[/td][/tr] [tr][td]03[/td][td]地区[/td][td]${e.district || ""}[/td][/tr] [tr][td]04[/td][td]小区名称[/td][td]${e.neighborhood || ""}[/td][/tr] [tr][td]05[/td][td]详细地址[/td][td]${e.address || ""}[/td][/tr] [tr][td]06[/td][td]联系方式[/td][td]${e.contact || ""}[/td][/tr] [tr][td]07[/td][td]价格[/td][td]${e.price || ""}[/td][/tr] [tr][td]08[/td][td]租期[/td][td]${e.rentDays || ""}[/td][/tr] [tr][td]09[/td][td]房户类型[/td][td]${e.houseType || ""}[/td][/tr] [tr][td]10[/td][td]出租户型[/td][td]${e.rentType || ""}[/td][/tr] [tr][td]11[/td][td]出租面积[/td][td]${e.area || ""}[/td][/tr] [tr][td]12[/td][td]可租期限[/td][td]${e.range || ""}[/td][/tr] [tr][td]13[/td][td]付款方式[/td][td]${e.paymentType || ""}[/td][/tr] [tr][td]14[/td][td]是否为隔间[/td][td]${e.isSingleRoom || ""}[/td][/tr] [tr][td]15[/td][td]独立电表[/td][td]${e.isElectricIsolated || ""}[/td][/tr] [tr][td]16[/td][td]水电缴费[/td][td]${e.waterElecValue || ""}[/td][/tr] [tr][td]17[/td][td]日常卫生[/td][td]${e.cleaning || ""}[/td][/tr] [tr][td]18[/td][td]维修物业[/td][td]${e.repairing || ""}[/td][/tr] [tr][td]19[/td][td]网络带宽[/td][td]${e.networking || ""}[/td][/tr] [tr][td]20[/td][td]退租方式[/td][td]${e.checkout || ""}[/td][/tr] [tr][td]21[/td][td]其他描述[/td][td]${e.otherDescriptions || ""}[/td][/tr] [tr][td]22[/td][td]其他要求[/td][td]${e.otherDemands || ""}[/td][/tr] [/table]`; this.setState({ content: content + "\n\n" + this.state.content, houseTmpVisible: false, }); }; render() { const contentCache = Utility.getLocalStorage("contentCache"); const mode = this.match.params.mode; const id = this.match.params.id; const url = `/board/${this.state.boardId}`; let editor; let titleInput = null; //发主题或发投票模式 if (mode === "postTopic" || mode === "postVoteTopic") { titleInput = ( <InputTitle boardId={id} tags={this.state.tags} onChange={this.onTitleChange.bind(this)} title={this.state.postInfo.title} tag1={0} tag2={0} /> ); //查询财富值余额 let wealth; try { wealth = Utility.getLocalStorage("userInfo").wealth; } catch (e) { wealth = "查询财富值余额失败,请前往个人中心查看"; } //根据版面匿名状态显示相应的按钮 let ubbButtons; let mdButtons; if (this.state.anonymousState === 0 || mode === "postVoteTopic") { ubbButtons = ( <div className="row" style={{ justifyContent: "center" }}> <button id="post-topic-button" onClick={this.sendOnymousUbbTopic} className="button blue" > 发帖 </button> </div> ); mdButtons = ( <div className="row" style={{ justifyContent: "center" }}> <button id="post-topic-button" onClick={this.sendOnymousMdTopic} className="button blue" > 发帖 </button> </div> ); } else if (this.state.anonymousState === 1) { ubbButtons = ( <div className="row" style={{ justifyContent: "center" }}> <button id="post-topic-button-anonymous" onClick={this.sendAnonymousUbbTopic} className="button grey" > 匿名发帖 </button> </div> ); mdButtons = ( <div className="row" style={{ justifyContent: "center" }}> <button id="post-topic-button-anonymous" onClick={this.sendAnonymousMdTopic} className="button grey" > 匿名发帖 </button> </div> ); } else if (this.state.anonymousState === 2) { ubbButtons = ( <div style={{ display: "flex", flexDirection: "column", alignItems: "center", }} > <div> <button id="post-topic-button" onClick={this.sendOnymousUbbTopic} className="button blue" > 发帖 </button> <button id="post-topic-button-anonymous" onClick={this.sendAnonymousUbbTopic} className="button grey" > 匿名发帖 </button> </div> <p> 在本版面匿名发主题每次需消耗10000财富值。你当前的财富值余额为: {wealth} </p> </div> ); mdButtons = ( <div style={{ display: "flex", flexDirection: "column", alignItems: "center", }} > <div> <button id="post-topic-button" onClick={this.sendOnymousMdTopic} className="button blue" > 发帖 </button> <button id="post-topic-button-anonymous" onClick={this.sendAnonymousMdTopic} className="button grey" > 匿名发帖 </button> </div> <p> 在本版面匿名发主题每次需消耗10000财富值。你当前的财富值余额为: {wealth} </p> </div> ); } if (this.state.mode === 0) { editor = ( <div> <div className="createTopicContent"> <div className="createTopicListName">主题内容</div> <div id="post-topic-changeMode" onClick={this.changeEditor} className="hiddenImage" style={{ width: "12rem", marginTop: "0rem" }} > 切换到Markdown编辑器 </div> </div> <UbbEditor update={this.update} value={this.state.content} option={{ height: 20, submit: this.sendOnymousUbbTopic }} /> {ubbButtons} </div> ); } else { editor = ( <div style={{ display: "flex", flexDirection: "column" }}> <div className="createTopicContent"> <div className="createTopicListName">主题内容</div> <div id="post-topic-changeMode" onClick={this.changeEditor} className="hiddenImage" style={{ width: "12rem", marginTop: "0rem" }} > 切换到UBB编辑器 </div> </div> <ReactMde value={this.state.mdeState} onChange={this.handleValueChange} generateMarkdownPreview={(markdown) => Promise.resolve(this.converter.makeHtml(markdown)) } commands={this.state.commands} minEditorHeight={330} maxEditorHeight={500} buttonContentOptions={{ iconProvider: (name) => { console.log(name); if (name === "heading") return <i className={`fa fa-header`} />; return <i className={`fa fa-${name}`} />; }, }} /> {mdButtons} </div> ); } } //编辑模式 else if (mode === "edit") { if (this.state.mode === 0) { editor = ( <div> <div className="createTopicContent"> <div className="createTopicListName">主题内容</div> <div id="post-topic-changeMode" onClick={this.changeEditor} className="hiddenImage" style={{ width: "12rem", marginTop: "0rem" }} > 切换到Markdown编辑器 </div> </div> <UbbEditor update={this.update} value={this.state.content} option={{ submit: this.editUBB.bind(this) }} /> <div className="row" style={{ justifyContent: "center" }}> <button id="post-topic-button" onClick={this.editUBB} className="button blue" > 编辑 </button> </div> </div> ); } else if (this.state.mode === 1) { editor = ( <div style={{ display: "flex", flexDirection: "column" }}> <div className="createTopicContent"> <div className="createTopicListName">主题内容</div> <div id="post-topic-changeMode" onClick={this.changeEditor} className="hiddenImage" style={{ width: "12rem", marginTop: "0rem" }} > 切换到UBB编辑器 </div> </div> <ReactMde value={this.state.mdeState} onChange={this.handleValueChange} generateMarkdownPreview={(markdown) => Promise.resolve(this.converter.makeHtml(markdown)) } commands={this.state.commands} minEditorHeight={330} maxEditorHeight={500} buttonContentOptions={{ iconProvider: (name) => { console.log(name); if (name === "heading") return <i className={`fa fa-header`} />; return <i className={`fa fa-${name}`} />; }, }} /> <div id="post-topic-button" onClick={this.editMd.bind(this)} className="button blue" > 编辑 </div> </div> ); } if (this.state.postInfo.floor === 1) { titleInput = ( <InputTitle boardId={id} tags={this.state.tags} onChange={this.onTitleChange.bind(this)} title={this.state.postInfo.title} tag1={this.state.topicInfo.tag1} tag2={this.state.topicInfo.tag2} /> ); } } console.log("默认type:" + this.state.type); let topicType = ( <div className="createTopicType"> <div className="createTopicListName">发帖类型</div> <input type="radio" name="type" value="普通" onClick={this.changeNormalType} checked={this.state.type === 0 ? true : false} />{" "} 普通 <input type="radio" name="type" value="学术信息" onClick={this.changeAcademicType} checked={this.state.type === 2 ? true : false} />{" "} 学术信息 <div style={{ color: "rgb(255,0,0)" }}> (活动帖和学术帖请选择正确的发帖类型) </div> </div> ); console.log(Utility.isMaster(this.state.masters)); // issue #38 普通用户不显示校园活动 if ( Utility.getLocalStorage("userInfo") && (Utility.isMaster(this.state.masters) || (Utility.getLocalStorage("userInfo").userTitleIds || []).indexOf(91) !== -1) ) { topicType = ( <div className="createTopicType"> <div className="createTopicListName">发帖类型</div> <input type="radio" name="type" value="普通" onClick={this.changeNormalType} checked={this.state.type === 0 ? true : false} />{" "} 普通 <input type="radio" name="type" value="学术信息" onClick={this.changeAcademicType} checked={this.state.type === 2 ? true : false} />{" "} 学术信息 <input type="radio" name="type" value="校园活动" onClick={this.changeActivityType} checked={this.state.type === 1 ? true : false} />{" "} 校园活动 <div style={{ color: "rgb(255,0,0)" }}> (活动帖和学术帖请选择正确的发帖类型) </div> </div> ); } // 开启消息提醒 let noticeOption = ( <div className="createTopicType"> <div className="createTopicListName">高级选项</div> <input style={{ marginLeft: "5px" }} type="checkbox" name="option" value="notNotice" onClick={this.notNotice} checked={this.state.notice} />{" "} 接收消息提醒 </div> ); if (this.state.postInfo.floor !== 1 && mode === "edit") { topicType = null; noticeOption = null; } // 住房信息模板 let houseTemplate = null; if (Number(this.state.boardId) === 515) { houseTemplate = ( <> <div style={{ marginBottom: "15px" }}> <Button style={{ width: "150px" }} type="primary" size="default" onClick={this.showModal} > 住房信息模板 </Button> <span style={{ color: "red", marginLeft: "10px" }}> (出租、合租、转租、出售等已有房源必填) </span> </div> <Tmp visible={this.state.houseTmpVisible} submit={this.handleTmpForm} /> </> ); } return ( <div className="createTopic"> <Category url={url} boardName={this.state.boardName} mode={mode} /> {titleInput} {topicType} {noticeOption} {houseTemplate} {mode === "postVoteTopic" ? ( <Vote voteInfo={this.state.voteInfo} onVoteInfoChange={this.onVoteInfoChange} /> ) : null} {editor} </div> ); } } /** * 编辑界面的导航器组件 */ export class Category extends React.Component< { url: string; boardName: string; mode: string }, { url: string; boardName: string } > { constructor(props) { super(props); this.state = { url: "", boardName: "", }; } //在子组件中,this.props的值不会自动更新,每当父组件的传值发生变化时,需要在子组件的的componentWillReceiveProps中去手动更新 componentWillReceiveProps(nextProps) { this.setState({ url: nextProps.url, boardName: nextProps.boardName, }); } render() { let categoryText: string; if (this.props.mode === "postTopic") categoryText = "发表主题"; else if (this.props.mode === "edit") categoryText = "编辑主题"; else if (this.props.mode === "postVoteTopic") categoryText = "发表投票主题"; return ( <div className="row" style={{ alignItems: "baseline", justifyContent: "flex-start", color: "grey", fontSize: "0.75rem", marginBottom: "1rem", }} > <Link style={{ color: "grey", fontSize: "1rem", marginRight: "0.5rem" }} to={"/"} > 首页 </Link> <i className="fa fa-chevron-right"></i> <Link style={{ color: "grey", fontSize: "1rem", marginLeft: "0.5rem", marginRight: "0.5rem", }} to={this.state.url} > {this.state.boardName} </Link> <i className="fa fa-chevron-right"></i> <div style={{ color: "grey", fontSize: "1rem", marginLeft: "0.5rem", marginRight: "0.5rem", }} > {categoryText} </div> </div> ); } } /** * 编辑界面的标签 * 用于特定版面的发主题/编辑主题 * TODO:尚未完成 */ export class Tags extends React.Component<{}, {}> { constructor(props) { super(props); this.state = {}; } render() { return <div></div>; } } /** * 编辑界面的标题 * 用于发主题/编辑主题 * TODO:尚未完成 */ export class InputTitle extends React.Component< { boardId; onChange; tags; title; tag1; tag2 }, { title: string; tags; tag1; tag2; hasEvent: boolean } > { constructor(props) { super(props); this.handleTagChange = this.handleTagChange.bind(this); this.handleTitleChange = this.handleTitleChange.bind(this); this.generateTagOption = this.generateTagOption.bind(this); this.state = { title: this.props.title, tags: this.props.tags, tag1: "", tag2: "", hasEvent: false, }; } handleTitleChange(event) { let tag1, tag2; if (this.state.tags.length === 0) { this.props.onChange(event.target.value, "", ""); this.setState({ title: event.target.value }); } else if (this.state.tags.length === 1) { tag1 = $(".tagBoxSelect").text(); this.props.onChange(event.target.value, tag1, ""); this.setState({ title: event.target.value }); } else { tag1 = $(".tagBoxSelect").text(); tag2 = $(".tagBoxSelect1").text(); this.props.onChange(event.target.value, tag1, tag2); this.setState({ title: event.target.value }); } } handleTagChange() { const tag1 = $(".tagBoxSelect").text(); const tag2 = $(".tagBoxSelect1").text(); //console.log("tagtext"); //console.log($(".tagBoxSelect").text()); this.props.onChange("", tag1, tag2); } componentWillReceiveProps(newProps) { if (newProps.title && !this.state.title) this.setState({ title: newProps.title, tags: newProps.tags }); else this.setState({ tags: newProps.tags }); } componentDidMount() { //如果有默认tags就绑定事件 if (this.state.tags.length > 0) { this.bindEvent(); } } componentDidUpdate() { //如果没绑定过事件则绑定事件 if (!this.state.hasEvent) { this.bindEvent(); } } bindEvent = async () => { const tagBoxSelect = $(".tagBoxSelect"); //获取不到元素的时候不绑定事件 if (tagBoxSelect.length === 0) { return; } else { //获取到则标记已绑定过事件 this.setState({ hasEvent: true, }); } const downArrow = $(".downArrow"); const tagBoxSub = $(".tagBoxSub"); const tagBoxLi = tagBoxSub.find("li"); $(document).click(function () { tagBoxSub.css("display", "none"); }); tagBoxSelect.click(function () { //console.log("click1"); if (tagBoxSub.css("display") === "block") tagBoxSub.css("display", "none"); else tagBoxSub.css("display", "block"); return false; //阻止事件冒泡 }); downArrow.click(function () { if (tagBoxSub.css("display") === "block") tagBoxSub.css("display", "none"); else tagBoxSub.css("display", "block"); return false; //阻止事件冒泡 }); /*在一个对象上触发某类事件(比如单击onclick事件),如果此对象定义了此事件的处理程序,那么此事件就会调用这个处理程序, 如果没有定义此事件处理程序或者事件返回true,那么这个事件会向这个对象的父级对象传播,从里到外,直至它被处理(父级对象所有同类事件都将被激活), 或者它到达了对象层次的最顶层,即document对象(有些浏览器是window)。*/ tagBoxLi.click(function () { tagBoxSelect.text($(this).text()); }); tagBoxLi.mouseover(function () { this.className = "hover"; }); tagBoxLi.mouseout(function () { this.className = ""; }); const tagBoxSelect1 = $(".tagBoxSelect1"); const downArrow1 = $(".downArrow1"); const tagBoxSub1 = $(".tagBoxSub1"); const tagBoxLi1 = tagBoxSub1.find("li"); $(document).click(function () { tagBoxSub1.css("display", "none"); }); tagBoxSelect1.click(function () { if (tagBoxSub1.css("display") === "block") tagBoxSub1.css("display", "none"); else tagBoxSub1.css("display", "block"); return false; //阻止事件冒泡 }); downArrow1.click(function () { if (tagBoxSub1.css("display") === "block") tagBoxSub1.css("display", "none"); else tagBoxSub1.css("display", "block"); return false; //阻止事件冒泡 }); /*在一个对象上触发某类事件(比如单击onclick事件),如果此对象定义了此事件的处理程序,那么此事件就会调用这个处理程序, 如果没有定义此事件处理程序或者事件返回true,那么这个事件会向这个对象的父级对象传播,从里到外,直至它被处理(父级对象所有同类事件都将被激活), 或者它到达了对象层次的最顶层,即document对象(有些浏览器是window)。*/ tagBoxLi1.click(function () { tagBoxSelect1.text($(this).text()); }); tagBoxLi1.mouseover(function () { this.className = "hover"; }); tagBoxLi1.mouseout(function () { this.className = ""; }); let tag1 = "", tag2 = ""; if (this.props.tag1 !== 0) { tag1 = await Utility.getTagNamebyId(this.props.tag1); } if (this.props.tag2 !== 0) { tag2 = await Utility.getTagNamebyId(this.props.tag2); } if (this.props.title && !this.state.title) this.setState({ title: this.props.title, tags: this.props.tags, tag1: tag1, tag2: tag2, }); else this.setState({ tags: this.props.tags, tag1: tag1, tag2: tag2 }); }; generateTagOption(item) { return <li onClick={this.handleTagChange}>{item.name}</li>; } render() { let drop1 = null; let drop2 = null; if (this.state.tags.length > 0) drop1 = ( <ul className="tagBoxSub"> {this.state.tags[0].tags.map(this.generateTagOption)} </ul> ); if (this.state.tags.length === 2) drop2 = ( <ul className="tagBoxSub1"> {this.state.tags[1].tags.map(this.generateTagOption)} </ul> ); let tagInfo = null; if (this.state.tags.length === 2) { let defaultTag1 = this.state.tags[0].tags[0].name; let defaultTag2 = this.state.tags[1].tags[0].name; if (this.state.tag1) defaultTag1 = this.state.tag1; if (this.state.tag2) defaultTag2 = this.state.tag2; tagInfo = ( <div className="row"> <div className="row"> <div className="tagBoxSelect">{defaultTag1}</div> <div className="downArrow"> <img src="/static/images/downArrow.png" width="12" height="12" /> </div> {drop1} </div> <div className="row"> <div className="tagBoxSelect1">{defaultTag2}</div> <div className="downArrow1"> <img src="/static/images/downArrow.png" width="12" height="12" /> </div> {drop2} </div> </div> ); } else if (this.state.tags.length == 1) { let defaultTag1 = this.state.tags[0].tags[0].name; if (this.state.tag1) defaultTag1 = this.state.tag1; tagInfo = ( <div className="row"> <div className="tagBoxSelect">{defaultTag1}</div> <div className="downArrow"> <img src="/static/images/downArrow.png" width="12" height="12" /> </div> {drop1} </div> ); } return ( <div className="createTopicTitle"> <div className="createTopicListName">主题标题</div> {tagInfo} <input value={this.state.title} placeholder="请输入新主题的标题" onChange={this.handleTitleChange.bind(this)} /> </div> ); } } /** * 编辑界面的选项 * 用于发主题/编辑主题 * 所有版面仅管理员可以设置仅楼主可见 * TODO:尚未完成 */ export class Options extends React.Component<{}, {}> { constructor(props) { super(props); this.state = {}; } render() { return ( <div className="createTopicOption"> <div className="createTopicListName">选项</div> <input type="radio" checked={true} name="option" value="all" /> 回复所有人可见 <input type="radio" name="option" value="host" /> 回复仅楼主可见 <input type="radio" name="option" value="special" /> 回复仅特定用户可见 </div> ); } } class TmpForm extends React.Component<any, any> { state = { elecRadio: "", waterElecRadio: "", elecValue: "", waterElecValue: "", visible: this.props.visible, }; componentWillReceiveProps(newProps) { // if(newProps.visible !== this.props.visible){ this.setState({ visible: newProps.visible }); //} } onWaterElecChange = (e) => { this.setState({ waterElecRadio: e.target.value, }); }; onElecChange = (e) => { this.setState({ elecRadio: e.target.value, }); }; onHandleSubmit = (e) => { e.preventDefault(); const ref: any = this.refs.tmpForm; this.props.form.validateFields((err, values) => { if (!err) { console.log("Received values of form: ", values); if (this.state.elecRadio === "其他") values.isElectricIsolated = this.state.elecValue; if (this.state.waterElecRadio === "其他") values.waterElecValue = this.state.waterElecValue; this.props.submit(values); this.setState({ visible: false }); } }); }; onCancel = () => { this.setState({ visible: false }); }; render() { const { getFieldDecorator } = this.props.form; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 8 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 16 }, }, }; const rangeConfig = { rules: [ { type: "array", required: true, message: "Please select time!" }, ], }; return ( <Modal title="住房信息模板" visible={this.state.visible} onOk={this.onHandleSubmit} onCancel={this.onCancel} > <Form ref="tmpForm" style={{ maxHeight: "500px", overflowY: "scroll" }} {...formItemLayout} onSubmit={this.onHandleSubmit} > <Form.Item label="有效时间"> {getFieldDecorator( "validDate", rangeConfig )( <RangePicker renderExtraFooter={() => "不能大于2周,到期可编辑"} /> )} </Form.Item> <Form.Item label="类型" hasFeedback> {getFieldDecorator("type", { rules: [{ required: true, message: "请选择类型!" }], })( <Select placeholder="请选择类型"> <Option value="整租">整租</Option> <Option value="合租">合租</Option> <Option value="转租">转租</Option> <Option value="出售">出售</Option> <Option value="其他">其他</Option> </Select> )} </Form.Item> <Form.Item label="地区"> {getFieldDecorator("district", { // rules: [{ required: true, message: "请输入地区!" }] })( <Input placeholder="例如:紫金港 / 玉泉 / 文一西路xx路交叉口处 / 上海的xx路附近" /> )} </Form.Item> <Form.Item label="小区名称"> {getFieldDecorator("neighborhood", { // rules: [{ required: true, message: "请输入小区名称!" }] })(<Input placeholder="例如:港湾家园" />)} </Form.Item> <Form.Item label="详细地址"> {getFieldDecorator("address", { // rules: [{ required: true, message: "请输入详细地址!" }] })(<Input placeholder="例如:余杭塘路866号港湾家园X幢X单元X号" />)} </Form.Item> <Form.Item label="联系方式"> {getFieldDecorator("contact", { // rules: [{ required: true, message: "请输入联系方式!" }] })( <Input placeholder="例如:张房东 电话18888888888 / 李女士 微信1234abc" /> )} </Form.Item> <Form.Item label="价格"> {getFieldDecorator("price", { // rules: [{ required: true, message: "请输入价格!" }] })(<Input placeholder="例如:2000元/月" />)} </Form.Item> <Form.Item label="租期"> {getFieldDecorator("rentDays", { // rules: [{ required: true, message: "请输入租期!" }] })(<Input placeholder="例如:6个月起租" />)} </Form.Item> <Form.Item label="房户类型"> {getFieldDecorator("houseType", { // rules: [{ required: true, message: "请输入房户类型!" }] })( <Input placeholder="例如:4室0厅1阳1卫1厨(指包括要出租的房间数量,加上公用的区域,私用的不算入)" /> )} </Form.Item> <Form.Item label="出租类型"> {getFieldDecorator("rentType", { // rules: [{ required: true, message: "请输入出租类型!" }] })( <Input placeholder="(指本次出租的房间)例如: 单间(独卫带阳台)/ 单间(独卫)/ 单间 " /> )} </Form.Item> <Form.Item label="出租面积"> {getFieldDecorator("area", { // rules: [{ required: true, message: "请输入出租面积!" }] })(<Input placeholder="(指本次出租的房间)例如:20平米" />)} </Form.Item> <Form.Item label="可租期限"> {getFieldDecorator("range", { // rules: [{ required: true, message: "请输入可租期限!" }] })( <Input placeholder="例如:到2017年11月7日 / 长期 (指合约可以签到什么时候)" /> )} </Form.Item> <Form.Item label="付款方式"> {getFieldDecorator("paymentType", { // rules: [{ required: true, message: "请输入付款方式!" }] })(<Input placeholder=" 例如:押1付1 / 押1付2" />)} </Form.Item> <Form.Item label="是否为隔间"> {getFieldDecorator("isSingleRoom", { rules: [{ required: true, message: "请输入是否为隔间!" }], })( <Radio.Group> <Radio value="是">是</Radio> <Radio value="否">否</Radio> </Radio.Group> )} </Form.Item> <Form.Item label="独立电表"> {getFieldDecorator("isElectricIsolated", { rules: [{ required: true, message: "请输入电表方式!" }], })( <Radio.Group onChange={this.onElecChange}> <Radio value="是">是</Radio> <Radio value="否">否</Radio> <Radio value="空调独立电表">空调独立电表</Radio> <Radio value="其他"> 其他 {this.state.elecRadio === "其他" ? ( <Input onChange={(e) => this.setState({ elecValue: e.target.value }) } style={{ width: 100, marginLeft: 10 }} /> ) : null} </Radio> </Radio.Group> )} </Form.Item> <Form.Item label="水电缴费"> {getFieldDecorator("waterElecValue", { rules: [{ required: true, message: "请输入水电缴费!" }], })( <Radio.Group onChange={this.onWaterElecChange}> <Radio value="每月一付">每月一付</Radio> <Radio value="每季一付">每季一付</Radio> <Radio value="退租结算">退租结算</Radio> <Radio value="其他"> 其他 {this.state.elecRadio === "其他" ? ( <Input onChange={(e) => this.setState({ waterElecValue: e.target.value }) } style={{ width: 100, marginLeft: 10 }} /> ) : null} </Radio> </Radio.Group> )} </Form.Item> <Form.Item label="日常卫生"> {getFieldDecorator("cleaning", { // rules: [{ required: true, message: "请输入日常卫生!" }] })(<Input placeholder="例如:自理 / 每周1次" />)} </Form.Item> <Form.Item label="维修物业"> {getFieldDecorator("repairing", { // rules: [{ required: true, message: "请输入维修物业!" }] })(<Input placeholder="例如:合租统一由房东承担、整租自行商议" />)} </Form.Item> <Form.Item label="网络带宽"> {getFieldDecorator("networking", { // rules: [{ required: true, message: "请输入网络带宽!" }] })(<Input placeholder="例如:有,电信20M宽带 / 无,自理" />)} </Form.Item> <Form.Item label="退租方式"> {getFieldDecorator("checkout", { // rules: [{ required: true, message: "请输入退租方式!" }] })(<Input placeholder="例如:合同到期,退还钥匙取回全额押金" />)} </Form.Item> <Form.Item label="其他描述"> {getFieldDecorator("otherDescriptions", { rules: [{ required: false }], })( <TextArea rows={4} placeholder="此处添加任何合适的描述,可以包括家具设备、地理优势、水电网物业详细、入住情况、朝向等相关信息描述" /> )} </Form.Item> <Form.Item label="其他要求"> {getFieldDecorator("otherDemands", { rules: [{ required: false }], })( <TextArea rows={4} placeholder="例如:无 / 由于XXX原因,希望找一个男生/女生/上班族/不接受情侣/……" /> )} </Form.Item> <Form.Item> 图片请点击下方编辑器的图片上传按钮上传,其他未尽内容请在下方编辑器输入。 </Form.Item> </Form> </Modal> ); } } export const Tmp = Form.create()(TmpForm); export const ShowEdit = withRouter(EditForm);
the_stack
import { Vector2Like } from "@here/harp-geoutils"; import { assert } from "@here/harp-utils"; import * as THREE from "three"; import { MAX_FOV_RAD, MIN_FOV_RAD } from "./FovCalculation"; // In centered projections the principal point is at NDC origin, splitting vertical and horizontal // fovs in two equal halves. function isCenteredProjection(principalPoint: Vector2Like): boolean { return principalPoint.x === 0 && principalPoint.y === 0; } /** * Computes the fov on the positive side of NDC x or y dimension (i.e. either right or top fov). * @param focalLength - Focal length in pixels. It must be larger than 0. * @param ppOffset - Principal point NDC offset either in y or x dimension. * @param viewportSide - Viewport height or width in pixels, must be same dimension as ppOffset. * @returns side fov in radians. */ function computePosSideFov(focalLength: number, ppOffset: number, viewportSide: number): number { // see diagram in computeFocalLengthFromFov(). assert(focalLength > 0, "Focal length must be larger than 0"); return Math.atan(((1 - ppOffset) * viewportSide * 0.5) / focalLength); } /** * Computes the vertical or horizontal fov. * @param focalLength - Focal length in pixels. It must be larger than 0. * @param ppOffset - Principal point NDC offset in y (vertical fov) or x dimension (horizontal fov). * @param viewportSide - Viewport height or width in pixels, must be same dimension as ppOffset. * @returns vertical or horizontal fov in radians. */ function computeFov(focalLength: number, ppOffset: number, viewportSide: number): number { assert(focalLength > 0, "Focal length must be larger than 0"); // For uncentered fov, compute the two fov sides separately. The fov on the negative NDC // side is computed in the same way as that for the positive side but flipping the offset sign. return ppOffset === 0 ? 2 * Math.atan((0.5 * viewportSide) / focalLength) : computePosSideFov(focalLength, ppOffset, viewportSide) + computePosSideFov(focalLength, -ppOffset, viewportSide); } /** * For off-center projections, fovs are asymmetric. In that case, the camera saves some of the side * fovs to save some computations. All values are in radians. */ interface Fovs { top: number; right: number; horizontal: number; // left = horizontal - right. } function getFovs(camera: THREE.PerspectiveCamera): Fovs | undefined { return camera.userData.fovs; } /** * Saves camera vertical fov and focal length. For off-center projections, saves side fovs as well. */ function setCameraParams( camera: THREE.PerspectiveCamera, ppalPoint: Vector2Like, focalLength: number, viewportHeight: number, verticalFov: number ): void { const viewportWidth = viewportHeight * camera.aspect; let hFov = computeFov(focalLength, ppalPoint.x, viewportWidth); if (hFov < MIN_FOV_RAD || hFov > MAX_FOV_RAD) { // Invalid horizontal fov, clamp and compute again focal length and vertical fov. hFov = THREE.MathUtils.clamp(hFov, MIN_FOV_RAD, MAX_FOV_RAD); const focalLength = computeFocalLengthFromFov(hFov, viewportWidth, ppalPoint.x); verticalFov = computeFov(focalLength, ppalPoint.y, viewportHeight); } camera.fov = THREE.MathUtils.radToDeg(verticalFov); if (isCenteredProjection(ppalPoint)) { delete camera.userData.fovs; } else { const width = viewportHeight * camera.aspect; camera.userData.fovs = { top: computePosSideFov(focalLength, ppalPoint.y, viewportHeight), right: computePosSideFov(focalLength, ppalPoint.x, width), horizontal: hFov } as Fovs; } camera.userData.focalLength = focalLength; } /** * Computes a camera's focal length from vertical fov and viewport height or horizontal fov and * viewport width. * @beta * * @param fov - Vertical or horizontal field of view in radians. * @param viewportSide - Viewport height if fov is vertical, otherwise viewport width. * @param ppOffset - Principal point offset in y direction if fov is vertical, * otherwise in x direction. * @returns focal length in pixels. */ function computeFocalLengthFromFov(fov: number, viewportSide: number, ppOffset: number): number { // C <- Projection center // /|-_ // / | -_ pfov = fov along positive NDC side (tfov or rfov) // / | -_ nfov = fov along negative NDC side (bfov or lfov) // / | -_ // / | -_ // /pfov | nfov -_ // / | -_ // / | -_ // a / |focal length(f) -_ b // / | -_ // / | Principal point -_ // / | / (pp) -_ // A/____________P________________________-_B Viewport // <------------><------------------------> // (1-ppOff)*s/2 (1+ppOff)*s/2 // <--------------------------------------> // s = viewportSide (height or width) // // Diagram of fov splitting (potentially asymmetric) along a viewport side (height or width). // For viewport height, fov is split into top (tfov) and bottom (bfov) fovs. For width, it's // split into right fov (rfov) and left fov (lfov). // Case 1. Symmetric fov split. Principal point is centered (centered projection): const halfSide = viewportSide / 2; const ppCentered = ppOffset === 0; if (ppCentered) { return halfSide / Math.tan(fov / 2); } // Case 2. Asymmetric fov split. Off-center perspective projection: const eps = 1e-6; const ppOffsetSq = ppOffset ** 2; if (Math.abs(fov - Math.PI / 2) < eps) { // Case 2a. Special case for (close to) right angle fov, tangent approaches infinity: // 3 right triangles: ACB, APC, BPC. Use pythagorean theorem on each to get 3 equations: // a^2 = f^2 + (1-ppOff)*s/2 // b^2 = f^2 + (1+ppOff)*s/2 // h^2 = a^2 + b^2 // Substitute a^2 and b^2 in third equation and solve for f to get: // f = (s/2) * sqrt(1-ppOff^2) return halfSide * Math.sqrt(1 - ppOffsetSq); } // Case 2b. General asymmetric fov case: // (1) tan(pfov) = (1-ppOff)*s / (2*f) // (2) tan(nfov) = (1+ppOff)*s / (2*f) // Use formula for the tan of the sum of two angles: // (3) tan(fov) = tan(pfov+nfov) = (tan(pfov) + tan(nfov)) / (1 - (tan(pfov) * tan(nfov))) // Substitute (1) and (2) in (3) and solve for f to get a quadratic equation: // 4*(tan(fov))^2 - 4*s*f - tan(fov)(1-ppOff^2)*s^2 = 0 , solving for f: // f = (s/2) * (1 +/- sqrt(1 + tan(fov)(1-ppOff^2)^2)) / tan(fov) // ppOff (principal point offset) is in [-1,1], so there's two real solutions (radicant is >=1) // and we choose the positive solution on each case: // a) tan(fov) > 0, fov in (0,pi/2) -> f = (s/2) * (1 + sqrt(1 + tan(fov)^2(1-ppOff^2))) / tan(fov) // b) tan(fov) < 0, fov in (pi/2,pi) -> f = (s/2) * (1 - sqrt(1 + tan(fov)^2(1-ppOff^2))) / tan(fov) const tanFov = Math.tan(fov); const sign = Math.sign(tanFov); const sqrt = Math.sqrt(1 + tanFov ** 2 * (1 - ppOffsetSq)); const f = (halfSide * (1 + sign * sqrt)) / tanFov; assert(f >= 0, "Focal length must be larger than 0"); return f; } export namespace CameraUtils { /** * Returns the camera's focal length. * @beta * * @param camera - The camera. * @returns The focal length in pixels or `undefined` if not set. */ export function getFocalLength(camera: THREE.PerspectiveCamera): number | undefined { return camera.userData?.focalLength; } /** * Sets a camera's focal length. * @remarks The camera's vertical fov will be updated to achieve the given viewport height. * @beta * * @param camera * @param focalLength - Focal length in pixels. It must be larger than 0. * @param viewportHeight - Viewport height in pixels, used to compute vertical fov. * @returns The new camera's focal length in pixels. */ export function setFocalLength( camera: THREE.PerspectiveCamera, focalLength: number, viewportHeight: number ): number { const ppalPoint = getPrincipalPoint(camera); const vFov = computeFov(focalLength, ppalPoint.y, viewportHeight); if (vFov < MIN_FOV_RAD || vFov > MAX_FOV_RAD) { // Invalid vertical fov, clamp and compute again focal length. setVerticalFov(camera, vFov, viewportHeight); } else { setCameraParams(camera, ppalPoint, focalLength, viewportHeight, vFov); } // focal length might change in setCameraParams due to horizontal fov restrictions. return getFocalLength(camera)!; } /** * Returns the camera's vertical field of view. * @param camera - The camera. * @returns The vertical fov in radians. */ export function getVerticalFov(camera: THREE.PerspectiveCamera): number { return THREE.MathUtils.degToRad(camera.fov); } /** * Sets a camera's vertical fov. * @remarks The camera's focal length will be updated to achieve the given viewport height. * @beta * * @param camera * @param verticalFov - Vertical field of view in radians. It'll be clamped to * [{@link MIN_FOV_RAD}, {@link MAX_FOV_RAD}]. * @param viewportHeight - Viewport height in pixels, used to compute focal length. * @returns The new camera's vertical fov in radians. */ export function setVerticalFov( camera: THREE.PerspectiveCamera, verticalFov: number, viewportHeight: number ): number { verticalFov = THREE.MathUtils.clamp(verticalFov, MIN_FOV_RAD, MAX_FOV_RAD); const ppalPoint = getPrincipalPoint(camera); const focalLength = computeFocalLengthFromFov(verticalFov, viewportHeight, ppalPoint.y); setCameraParams(camera, ppalPoint, focalLength, viewportHeight, verticalFov); // vertical fov might change in setCameraParams due to horizontal fov restrictions. return getVerticalFov(camera); } /** * Calculates object's screen size based on the focal length and it's camera distance. * @beta * * @param focalLength - Focal length in pixels (see {@link setVerticalFov}) * @param distance - Object distance in world space. * @param worldSize - Object size in world space. * @return object size in screen space. */ export function convertWorldToScreenSize( focalLength: number, distance: number, worldSize: number ): number { return (focalLength * worldSize) / distance; } /** * Calculates object's world size based on the focal length and it's camera distance. * @beta * * @param focalLength - Focal length in pixels (see {@link setVerticalFov}) * @param distance - Object distance in world space. * @param screenSize - Object size in screen space. * @return object size in world space. */ export function convertScreenToWorldSize( focalLength: number, distance: number, screenSize: number ): number { return (distance * screenSize) / focalLength; } /** * Returns the camera's principal point (intersection of principal ray and image plane) * in NDC coordinates. * @beta * @see https://en.wikipedia.org/wiki/Pinhole_camera_model * @remarks This point coincides with the principal vanishing point. By default it's located at * the image center (NDC coords [0,0]), and the resulting projection is centered or symmetric. * But it may be offset (@see THREE.PerspectiveCamera.setViewOffset) for some use cases such as * multiview setups (e.g. stereoscopic rendering), resulting in an asymmetric perspective * projection. * @param camera - The camera. * @param result - Optional vector where the principal point coordinates will be copied. * @returns A vector containing the principal point NDC coordinates. */ export function getPrincipalPoint( camera: THREE.PerspectiveCamera, result: Vector2Like = new THREE.Vector2() ): Vector2Like { result.x = -camera.projectionMatrix.elements[8]; result.y = -camera.projectionMatrix.elements[9]; return result; } /** * Sets the camera's principal point (intersection of principal ray and image plane) * in NDC coordinates. * @beta * @see {@link getPrincipalPoint} * @param camera - The camera. * @param ndcCoords - The principal point's NDC coordinates, each coordinate can have values in * the open interval (-1,1). */ export function setPrincipalPoint(camera: THREE.PerspectiveCamera, ndcCoords: Vector2Like) { // We only need to set to proper elements in the projection matrix: // camera.projectionMatrix.elements[8] = -ndcCoords.x // camera.projectionMatrix.elements[9] = -ndcCoords.y // However, this can't be done directly, otherwise it'd be overwritten on the next call to // camera.updateProjectionMatrix(). The only way to set the principal point is through a // THREE.js camera method for multi-view setup, see: // https://threejs.org/docs/#api/en/cameras/PerspectiveCamera.setViewOffset const height = 1; const width = camera.aspect; // Principal point splits fov in two angles that must be strictly less than 90 degrees // (each one belongs to a right triangle). Setting the principal point at the edges (-1 or // 1) would make it impossible to achieve an fov >= 90. Thus, clamp the principal point // coordinates to values slightly smaller than 1. const maxNdcCoord = 1 - 1e-6; camera.setViewOffset( width, height, (-THREE.MathUtils.clamp(ndcCoords.x, -maxNdcCoord, maxNdcCoord) * width) / 2, (THREE.MathUtils.clamp(ndcCoords.y, -maxNdcCoord, maxNdcCoord) * height) / 2, width, height ); } /** * Returns the camera's horizontal field of view. * @param camera - The camera. * @returns The horizontal fov in radians. */ export function getHorizontalFov(camera: THREE.PerspectiveCamera): number { // If horizontal fov is not stored in camera, assume centered projection and compute // it from the vertical fov. return ( getFovs(camera)?.horizontal ?? 2 * Math.atan(Math.tan(THREE.MathUtils.degToRad(camera.fov) / 2) * camera.aspect) ); } /** * Returns top fov angle for a given perspective camera. * @beta * @remarks In symmetric projections, the principal point coincides with the image center, and * the vertical and horizontal FOVs are each split at that point in two equal halves. * However, in asymmetric projections the principal point is not at the image center, and thus * each fov is split unevenly in two parts: * * Symmetric projection Asymmetric projection * ------------------------- -------------------------- * | ^ | | ^ | * | | | | |tFov | * | |tFov | | lFov v rFov | * | | | |<----->x<-------------->| * | lFov v rFov | | ppal ^ point | * |<--------->x<--------->| | | o | * | ppal point=img center | | | img center | * | ^ | | | | * | |bFov | | |bFov | * | | | | | | * | v | | v | * ------------------------- -------------------------- * * @param camera - The camera. * @returns The top fov angle in radians. */ export function getTopFov(camera: THREE.PerspectiveCamera): number { return getFovs(camera)?.top ?? THREE.MathUtils.degToRad(camera.fov / 2); } /** * Returns bottom fov angle for a given perspective camera. * @see {@link CameraUtils.getTopFov} * @beta * @param camera - The camera. * @returns The bottom fov angle in radians. */ export function getBottomFov(camera: THREE.PerspectiveCamera): number { return THREE.MathUtils.degToRad(camera.fov) - getTopFov(camera); } /** * Returns right fov angle for a given perspective camera. * @see {@link CameraUtils.getTopFov} * @beta * @param camera - The camera. * @returns The right fov angle in radians. */ export function getRightFov(camera: THREE.PerspectiveCamera): number { return getFovs(camera)?.right ?? getHorizontalFov(camera) / 2; } /** * Returns left fov angle for a given perspective camera. * @see {@link CameraUtils.getTopFov} * @beta * @param camera - The camera. * @returns The left fov angle in radians. */ export function getLeftFov(camera: THREE.PerspectiveCamera): number { return getFovs(camera)?.right !== undefined ? getHorizontalFov(camera) - getRightFov(camera) : getHorizontalFov(camera) / 2; } }
the_stack
import { App, PluginSettingTab, Setting, sanitizeHTMLToDom, RequestUrlParam, requestUrl } from "obsidian"; import { EntryDoc, LOG_LEVEL, RemoteDBSettings } from "./lib/src/types"; import { path2id, id2path } from "./utils"; import { NewNotice, runWithLock } from "./lib/src/utils"; import { Logger } from "./lib/src/logger"; import { checkSyncInfo, connectRemoteCouchDBWithSetting } from "./utils_couchdb"; import { testCrypt } from "./lib/src/e2ee_v2"; import ObsidianLiveSyncPlugin from "./main"; export class ObsidianLiveSyncSettingTab extends PluginSettingTab { plugin: ObsidianLiveSyncPlugin; constructor(app: App, plugin: ObsidianLiveSyncPlugin) { super(app, plugin); this.plugin = plugin; } async testConnection(): Promise<void> { // const db = await connectRemoteCouchDB( // this.plugin.settings.couchDB_URI + (this.plugin.settings.couchDB_DBNAME == "" ? "" : "/" + this.plugin.settings.couchDB_DBNAME), // { // username: this.plugin.settings.couchDB_USER, // password: this.plugin.settings.couchDB_PASSWORD, // }, // this.plugin.settings.disableRequestURI, // this.plugin.settings.encrypt ? this.plugin.settings.passphrase : this.plugin.settings.encrypt // ); const db = await connectRemoteCouchDBWithSetting(this.plugin.settings, this.plugin.localDatabase.isMobile); if (typeof db === "string") { this.plugin.addLog(`could not connect to ${this.plugin.settings.couchDB_URI} : ${this.plugin.settings.couchDB_DBNAME} \n(${db})`, LOG_LEVEL.NOTICE); return; } this.plugin.addLog(`Connected to ${db.info.db_name}`, LOG_LEVEL.NOTICE); } display(): void { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h2", { text: "Settings for Self-hosted LiveSync." }); const w = containerEl.createDiv(""); const screenElements: { [key: string]: HTMLElement[] } = {}; const addScreenElement = (key: string, element: HTMLElement) => { if (!(key in screenElements)) { screenElements[key] = []; } screenElements[key].push(element); }; w.addClass("sls-setting-menu"); w.innerHTML = ` <label class='sls-setting-label selected'><input type='radio' name='disp' value='0' class='sls-setting-tab' checked><div class='sls-setting-menu-btn'>🛰️</div></label> <label class='sls-setting-label'><input type='radio' name='disp' value='10' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>📦</div></label> <label class='sls-setting-label'><input type='radio' name='disp' value='20' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>⚙️</div></label> <label class='sls-setting-label'><input type='radio' name='disp' value='30' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>🔁</div></label> <label class='sls-setting-label'><input type='radio' name='disp' value='40' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>🔧</div></label> <label class='sls-setting-label'><input type='radio' name='disp' value='50' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>🧰</div></label> <label class='sls-setting-label'><input type='radio' name='disp' value='60' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>🔌</div></label> <label class='sls-setting-label'><input type='radio' name='disp' value='70' class='sls-setting-tab' ><div class='sls-setting-menu-btn'>🚑</div></label> `; const menutabs = w.querySelectorAll(".sls-setting-label"); const changeDisplay = (screen: string) => { for (const k in screenElements) { if (k == screen) { screenElements[k].forEach((element) => element.removeClass("setting-collapsed")); } else { screenElements[k].forEach((element) => element.addClass("setting-collapsed")); } } }; menutabs.forEach((element) => { const e = element.querySelector(".sls-setting-tab"); if (!e) return; e.addEventListener("change", (event) => { menutabs.forEach((element) => element.removeClass("selected")); changeDisplay((event.currentTarget as HTMLInputElement).value); element.addClass("selected"); }); }); const containerRemoteDatabaseEl = containerEl.createDiv(); containerRemoteDatabaseEl.createEl("h3", { text: "Remote Database configuration" }); const syncWarn = containerRemoteDatabaseEl.createEl("div", { text: `These settings are kept locked while automatic synchronization options are enabled. Disable these options in the "Sync Settings" tab to unlock.` }); syncWarn.addClass("op-warn-info"); syncWarn.addClass("sls-hidden"); const isAnySyncEnabled = (): boolean => { if (this.plugin.settings.liveSync) return true; if (this.plugin.settings.periodicReplication) return true; if (this.plugin.settings.syncOnFileOpen) return true; if (this.plugin.settings.syncOnSave) return true; if (this.plugin.settings.syncOnStart) return true; if (this.plugin.localDatabase.syncStatus == "CONNECTED") return true; if (this.plugin.localDatabase.syncStatus == "PAUSED") return true; return false; }; const applyDisplayEnabled = () => { if (isAnySyncEnabled()) { dbsettings.forEach((e) => { e.setDisabled(true).setTooltip("When any sync is enabled, It cound't be changed."); }); syncWarn.removeClass("sls-hidden"); } else { dbsettings.forEach((e) => { e.setDisabled(false).setTooltip(""); }); syncWarn.addClass("sls-hidden"); } if (this.plugin.settings.liveSync) { syncNonLive.forEach((e) => { e.setDisabled(true).setTooltip(""); }); syncLive.forEach((e) => { e.setDisabled(false).setTooltip(""); }); } else if (this.plugin.settings.syncOnFileOpen || this.plugin.settings.syncOnSave || this.plugin.settings.syncOnStart || this.plugin.settings.periodicReplication) { syncNonLive.forEach((e) => { e.setDisabled(false).setTooltip(""); }); syncLive.forEach((e) => { e.setDisabled(true).setTooltip(""); }); } else { syncNonLive.forEach((e) => { e.setDisabled(false).setTooltip(""); }); syncLive.forEach((e) => { e.setDisabled(false).setTooltip(""); }); } }; const dbsettings: Setting[] = []; dbsettings.push( new Setting(containerRemoteDatabaseEl).setName("URI").addText((text) => text .setPlaceholder("https://........") .setValue(this.plugin.settings.couchDB_URI) .onChange(async (value) => { this.plugin.settings.couchDB_URI = value; await this.plugin.saveSettings(); }) ), new Setting(containerRemoteDatabaseEl) .setName("Username") .setDesc("username") .addText((text) => text .setPlaceholder("") .setValue(this.plugin.settings.couchDB_USER) .onChange(async (value) => { this.plugin.settings.couchDB_USER = value; await this.plugin.saveSettings(); }) ), new Setting(containerRemoteDatabaseEl) .setName("Password") .setDesc("password") .addText((text) => { text.setPlaceholder("") .setValue(this.plugin.settings.couchDB_PASSWORD) .onChange(async (value) => { this.plugin.settings.couchDB_PASSWORD = value; await this.plugin.saveSettings(); }); text.inputEl.setAttribute("type", "password"); }), new Setting(containerRemoteDatabaseEl).setName("Database name").addText((text) => text .setPlaceholder("") .setValue(this.plugin.settings.couchDB_DBNAME) .onChange(async (value) => { this.plugin.settings.couchDB_DBNAME = value; await this.plugin.saveSettings(); }) ) // new Setting(containerRemoteDatabaseEl) // .setDesc("This feature is locked in mobile") // .setName("Use the old connecting method") // .addToggle((toggle) => { // toggle.setValue(this.plugin.settings.disableRequestURI).onChange(async (value) => { // this.plugin.settings.disableRequestURI = value; // await this.plugin.saveSettings(); // }); // toggle.setDisabled(this.plugin.isMobile); // return toggle; // }) ); new Setting(containerRemoteDatabaseEl) .setName("End to End Encryption") .setDesc("Encrypt contents on the remote database. If you use the plugins synchronizing feature, enabling this is recommend.") .addToggle((toggle) => toggle.setValue(this.plugin.settings.workingEncrypt).onChange(async (value) => { this.plugin.settings.workingEncrypt = value; phasspharase.setDisabled(!value); await this.plugin.saveSettings(); }) ); const phasspharase = new Setting(containerRemoteDatabaseEl) .setName("Passphrase") .setDesc("Encrypting passphrase") .addText((text) => { text.setPlaceholder("") .setValue(this.plugin.settings.workingPassphrase) .onChange(async (value) => { this.plugin.settings.workingPassphrase = value; await this.plugin.saveSettings(); }); text.inputEl.setAttribute("type", "password"); }); phasspharase.setDisabled(!this.plugin.settings.workingEncrypt); containerRemoteDatabaseEl.createEl("div", { text: "If you change the passphrase, rebuilding the remote database is required. Please press 'Apply and send'. Or, If you have configured it to connect to an existing database, click 'Just apply'.", }); const checkWorkingPassphrase = async (): Promise<boolean> => { const settingForCheck: RemoteDBSettings = { ...this.plugin.settings, encrypt: this.plugin.settings.workingEncrypt, passphrase: this.plugin.settings.workingPassphrase, }; console.dir(settingForCheck); const db = await connectRemoteCouchDBWithSetting(settingForCheck, this.plugin.localDatabase.isMobile); if (typeof db === "string") { Logger("Could not connect to the database.", LOG_LEVEL.NOTICE); return false; } else { if (await checkSyncInfo(db.db)) { // Logger("Database connected", LOG_LEVEL.NOTICE); return true; } else { Logger("Failed to read remote database", LOG_LEVEL.NOTICE); return false; } } }; const applyEncryption = async (sendToServer: boolean) => { if (this.plugin.settings.workingEncrypt && this.plugin.settings.workingPassphrase == "") { Logger("If you enable encryption, you have to set the passphrase", LOG_LEVEL.NOTICE); return; } if (this.plugin.settings.workingEncrypt && !(await testCrypt())) { Logger("WARNING! Your device would not support encryption.", LOG_LEVEL.NOTICE); return; } if (!(await checkWorkingPassphrase())) { return; } if (!this.plugin.settings.workingEncrypt) { this.plugin.settings.workingPassphrase = ""; } this.plugin.settings.liveSync = false; this.plugin.settings.periodicReplication = false; this.plugin.settings.syncOnSave = false; this.plugin.settings.syncOnStart = false; this.plugin.settings.syncOnFileOpen = false; this.plugin.settings.encrypt = this.plugin.settings.workingEncrypt; this.plugin.settings.passphrase = this.plugin.settings.workingPassphrase; await this.plugin.saveSettings(); // await this.plugin.resetLocalDatabase(); if (sendToServer) { await this.plugin.initializeDatabase(true); await this.plugin.markRemoteLocked(); await this.plugin.tryResetRemoteDatabase(); await this.plugin.markRemoteLocked(); await this.plugin.replicateAllToServer(true); } else { await this.plugin.markRemoteResolved(); await this.plugin.replicate(true); } }; new Setting(containerRemoteDatabaseEl) .setName("Apply") .setDesc("apply encryption settinngs, and re-initialize remote database") .addButton((button) => button .setButtonText("Apply and send") .setWarning() .setDisabled(false) .setClass("sls-btn-left") .onClick(async () => { await applyEncryption(true); }) ) .addButton((button) => button .setButtonText("Just apply") .setWarning() .setDisabled(false) .setClass("sls-btn-right") .onClick(async () => { await applyEncryption(false); }) ); new Setting(containerRemoteDatabaseEl) .setName("Test Database Connection") .setDesc("Open database connection. If the remote database is not found and you have the privilege to create a database, the database will be created.") .addButton((button) => button .setButtonText("Test") .setDisabled(false) .onClick(async () => { await this.testConnection(); }) ); new Setting(containerRemoteDatabaseEl) .setName("Check database configuration") // .setDesc("Open database connection. If the remote database is not found and you have the privilege to create a database, the database will be created.") .addButton((button) => button .setButtonText("Check") .setDisabled(false) .onClick(async () => { const checkConfig = async () => { try { const requestToCouchDB = async (baseUri: string, username: string, password: string, origin: string, key?: string, body?: string) => { const utf8str = String.fromCharCode.apply(null, new TextEncoder().encode(`${username}:${password}`)); const encoded = window.btoa(utf8str); const authHeader = "Basic " + encoded; // const origin = "capacitor://localhost"; const transformedHeaders: Record<string, string> = { authorization: authHeader, origin: origin }; const uri = `${baseUri}/_node/_local/_config${key ? "/" + key : ""}`; const requestParam: RequestUrlParam = { url: uri, method: body ? "PUT" : "GET", headers: transformedHeaders, contentType: "application/json", body: body ? JSON.stringify(body) : undefined, }; return await requestUrl(requestParam); }; const r = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, window.origin); Logger(JSON.stringify(r.json, null, 2)); const responseConfig = r.json; const emptyDiv = createDiv(); emptyDiv.innerHTML = "<span></span>"; checkResultDiv.replaceChildren(...[emptyDiv]); const addResult = (msg: string, classes?: string[]) => { const tmpDiv = createDiv(); tmpDiv.addClass("ob-btn-config-fix"); if (classes) { tmpDiv.addClasses(classes); } tmpDiv.innerHTML = `${msg}`; checkResultDiv.appendChild(tmpDiv); }; const addConfigFixButton = (title: string, key: string, value: string) => { const tmpDiv = createDiv(); tmpDiv.addClass("ob-btn-config-fix"); tmpDiv.innerHTML = `<label>${title}</label><button>Fix</button>`; const x = checkResultDiv.appendChild(tmpDiv); x.querySelector("button").addEventListener("click", async () => { console.dir({ key, value }); const res = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, undefined, key, value); console.dir(res); if (res.status == 200) { Logger(`${title} successfly updated`, LOG_LEVEL.NOTICE); checkResultDiv.removeChild(x); checkConfig(); } else { Logger(`${title} failed`, LOG_LEVEL.NOTICE); Logger(res.text); } }); }; addResult("---Notice---", ["ob-btn-config-head"]); addResult( "If the server configuration is not persistent (e.g., running on docker), the values set from here will also be volatile. Once you are able to connect, please reflect the settings in the server's local.ini.", ["ob-btn-config-info"] ); addResult("Your configuration is dumped to Log", ["ob-btn-config-info"]); addResult("--Config check--", ["ob-btn-config-head"]); // Admin check // for database creation and deletion if (!(this.plugin.settings.couchDB_USER in responseConfig.admins)) { addResult(`⚠ You do not have administrative privileges.`); } else { addResult("✔ You have administrative privileges."); } // HTTP user-authorization check if (responseConfig?.chttpd?.require_valid_user != "true") { addResult("❗ chttpd.require_valid_user looks like wrong."); addConfigFixButton("Set chttpd.require_valid_user = true", "chttpd/require_valid_user", "true"); } else { addResult("✔ chttpd.require_valid_user is ok."); } if (responseConfig?.chttpd_auth?.require_valid_user != "true") { addResult("❗ chttpd_auth.require_valid_user looks like wrong."); addConfigFixButton("Set chttpd_auth.require_valid_user = true", "chttpd_auth/require_valid_user", "true"); } else { addResult("✔ chttpd_auth.require_valid_user is ok."); } // HTTPD check // Check Authentication header if (!responseConfig?.httpd["WWW-Authenticate"]) { addResult("❗ httpd.WWW-Authenticate is missing"); addConfigFixButton("Set httpd.WWW-Authenticate", "httpd/WWW-Authenticate", 'Basic realm="couchdb"'); } else { addResult("✔ httpd.WWW-Authenticate is ok."); } if (responseConfig?.httpd?.enable_cors != "true") { addResult("❗ httpd.enable_cors is wrong"); addConfigFixButton("Set httpd.enable_cors", "httpd/enable_cors", "true"); } else { addResult("✔ httpd.enable_cors is ok."); } // CORS check // checking connectivity for mobile if (responseConfig?.cors?.credentials != "true") { addResult("❗ cors.credentials is wrong"); addConfigFixButton("Set cors.credentials", "cors/credentials", "true"); } else { addResult("✔ cors.credentials is ok."); } const ConfiguredOrigins = ((responseConfig?.cors?.origins ?? "") + "").split(","); if ( responseConfig?.cors?.origins == "*" || (ConfiguredOrigins.indexOf("app://obsidian.md") !== -1 && ConfiguredOrigins.indexOf("capacitor://localhost") !== -1 && ConfiguredOrigins.indexOf("http://localhost") !== -1) ) { addResult("✔ cors.origins is ok."); } else { addResult("❗ cors.origins is wrong"); addConfigFixButton("Set cors.origins", "cors/origins", "app://obsidian.md,capacitor://localhost,http://localhost"); } addResult("--Connection check--", ["ob-btn-config-head"]); addResult(`Current origin:${window.location.origin}`); // Request header check const origins = ["app://obsidian.md", "capacitor://localhost", "http://localhost"]; for (const org of origins) { const rr = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, org); const responseHeaders = Object.entries(rr.headers) .map((e) => { e[0] = (e[0] + "").toLowerCase(); return e; }) .reduce((obj, [key, val]) => { obj[key] = val; return obj; }, {}); addResult(`Origin check:${org}`); if (responseHeaders["access-control-allow-credentials"] != "true") { addResult("❗ CORS is not allowing credential"); } else { addResult("✔ CORS credential OK"); } if (responseHeaders["access-control-allow-origin"] != org) { addResult(`❗ CORS Origin is unmatched:${origin}->${responseHeaders["access-control-allow-origin"]}`); } else { addResult("✔ CORS origin OK"); } } addResult("--Done--", ["ob-btn-config-haed"]); addResult("If you have some trouble with Connection-check even though all Config-check has been passed, Please check your reverse proxy's configuration.", ["ob-btn-config-info"]); } catch (ex) { Logger(`Checking configration failed`); Logger(ex); } }; await checkConfig(); }) ); const checkResultDiv = containerRemoteDatabaseEl.createEl("div", { text: "", }); addScreenElement("0", containerRemoteDatabaseEl); const containerLocalDatabaseEl = containerEl.createDiv(); containerLocalDatabaseEl.createEl("h3", { text: "Local Database configuration" }); new Setting(containerLocalDatabaseEl) .setName("Batch database update") .setDesc("Delay all changes, save once before replication or opening another file.") .addToggle((toggle) => toggle.setValue(this.plugin.settings.batchSave).onChange(async (value) => { if (value && this.plugin.settings.liveSync) { Logger("LiveSync and Batch database update cannot be used at the same time.", LOG_LEVEL.NOTICE); toggle.setValue(false); return; } this.plugin.settings.batchSave = value; await this.plugin.saveSettings(); }) ); new Setting(containerLocalDatabaseEl) .setName("Auto Garbage Collection delay") .setDesc("(seconds), if you set zero, you have to run manually.") .addText((text) => { text.setPlaceholder("") .setValue(this.plugin.settings.gcDelay + "") .onChange(async (value) => { let v = Number(value); if (isNaN(v) || v > 5000) { v = 0; } this.plugin.settings.gcDelay = v; await this.plugin.saveSettings(); }); text.inputEl.setAttribute("type", "number"); }); new Setting(containerLocalDatabaseEl).setName("Manual Garbage Collect").addButton((button) => button .setButtonText("Collect now") .setDisabled(false) .onClick(async () => { await this.plugin.garbageCollect(); }) ); containerLocalDatabaseEl.createEl("div", { text: sanitizeHTMLToDom(`Advanced settings<br> Configuration of how LiveSync makes chunks from the file.`), }); new Setting(containerLocalDatabaseEl) .setName("Minimum chunk size") .setDesc("(letters), minimum chunk size.") .addText((text) => { text.setPlaceholder("") .setValue(this.plugin.settings.minimumChunkSize + "") .onChange(async (value) => { let v = Number(value); if (isNaN(v) || v < 10 || v > 1000) { v = 10; } this.plugin.settings.minimumChunkSize = v; await this.plugin.saveSettings(); }); text.inputEl.setAttribute("type", "number"); }); new Setting(containerLocalDatabaseEl) .setName("LongLine Threshold") .setDesc("(letters), If the line is longer than this, make the line to chunk") .addText((text) => { text.setPlaceholder("") .setValue(this.plugin.settings.longLineThreshold + "") .onChange(async (value) => { let v = Number(value); if (isNaN(v) || v < 10 || v > 1000) { v = 10; } this.plugin.settings.longLineThreshold = v; await this.plugin.saveSettings(); }); text.inputEl.setAttribute("type", "number"); }); addScreenElement("10", containerLocalDatabaseEl); const containerGeneralSettingsEl = containerEl.createDiv(); containerGeneralSettingsEl.createEl("h3", { text: "General Settings" }); new Setting(containerGeneralSettingsEl) .setName("Do not show low-priority Log") .setDesc("Reduce log infomations") .addToggle((toggle) => toggle.setValue(this.plugin.settings.lessInformationInLog).onChange(async (value) => { this.plugin.settings.lessInformationInLog = value; await this.plugin.saveSettings(); }) ); new Setting(containerGeneralSettingsEl) .setName("Verbose Log") .setDesc("Show verbose log ") .addToggle((toggle) => toggle.setValue(this.plugin.settings.showVerboseLog).onChange(async (value) => { this.plugin.settings.showVerboseLog = value; await this.plugin.saveSettings(); }) ); addScreenElement("20", containerGeneralSettingsEl); const containerSyncSettingEl = containerEl.createDiv(); containerSyncSettingEl.createEl("h3", { text: "Sync setting" }); if (this.plugin.settings.versionUpFlash != "") { const c = containerSyncSettingEl.createEl("div", { text: this.plugin.settings.versionUpFlash }); c.createEl("button", { text: "I got it and updated." }, (e) => { e.addClass("mod-cta"); e.addEventListener("click", async () => { this.plugin.settings.versionUpFlash = ""; await this.plugin.saveSettings(); applyDisplayEnabled(); c.remove(); }); }); c.addClass("op-warn"); } const syncLive: Setting[] = []; const syncNonLive: Setting[] = []; syncLive.push( new Setting(containerSyncSettingEl) .setName("LiveSync") .setDesc("Sync realtime") .addToggle((toggle) => toggle.setValue(this.plugin.settings.liveSync).onChange(async (value) => { if (value && this.plugin.settings.batchSave) { Logger("LiveSync and Batch database update cannot be used at the same time.", LOG_LEVEL.NOTICE); toggle.setValue(false); return; } this.plugin.settings.liveSync = value; // ps.setDisabled(value); await this.plugin.saveSettings(); applyDisplayEnabled(); await this.plugin.realizeSettingSyncMode(); }) ) ); syncNonLive.push( new Setting(containerSyncSettingEl) .setName("Periodic Sync") .setDesc("Sync periodically") .addToggle((toggle) => toggle.setValue(this.plugin.settings.periodicReplication).onChange(async (value) => { this.plugin.settings.periodicReplication = value; await this.plugin.saveSettings(); applyDisplayEnabled(); }) ), new Setting(containerSyncSettingEl) .setName("Periodic sync intreval") .setDesc("Interval (sec)") .addText((text) => { text.setPlaceholder("") .setValue(this.plugin.settings.periodicReplicationInterval + "") .onChange(async (value) => { let v = Number(value); if (isNaN(v) || v > 5000) { v = 0; } this.plugin.settings.periodicReplicationInterval = v; await this.plugin.saveSettings(); applyDisplayEnabled(); }); text.inputEl.setAttribute("type", "number"); }), new Setting(containerSyncSettingEl) .setName("Sync on Save") .setDesc("When you save file, sync automatically") .addToggle((toggle) => toggle.setValue(this.plugin.settings.syncOnSave).onChange(async (value) => { this.plugin.settings.syncOnSave = value; await this.plugin.saveSettings(); applyDisplayEnabled(); }) ), new Setting(containerSyncSettingEl) .setName("Sync on File Open") .setDesc("When you open file, sync automatically") .addToggle((toggle) => toggle.setValue(this.plugin.settings.syncOnFileOpen).onChange(async (value) => { this.plugin.settings.syncOnFileOpen = value; await this.plugin.saveSettings(); applyDisplayEnabled(); }) ), new Setting(containerSyncSettingEl) .setName("Sync on Start") .setDesc("Start synchronization on Obsidian started.") .addToggle((toggle) => toggle.setValue(this.plugin.settings.syncOnStart).onChange(async (value) => { this.plugin.settings.syncOnStart = value; await this.plugin.saveSettings(); applyDisplayEnabled(); }) ) ); new Setting(containerSyncSettingEl) .setName("Use Trash for deleted files") .setDesc("Do not delete files that deleted in remote, just move to trash.") .addToggle((toggle) => toggle.setValue(this.plugin.settings.trashInsteadDelete).onChange(async (value) => { this.plugin.settings.trashInsteadDelete = value; await this.plugin.saveSettings(); }) ); new Setting(containerSyncSettingEl) .setName("Do not delete empty folder") .setDesc("Normally, folder is deleted When the folder became empty by replication. enable this, leave it as is") .addToggle((toggle) => toggle.setValue(this.plugin.settings.doNotDeleteFolder).onChange(async (value) => { this.plugin.settings.doNotDeleteFolder = value; await this.plugin.saveSettings(); }) ); new Setting(containerSyncSettingEl) .setName("Use newer file if conflicted (beta)") .setDesc("Resolve conflicts by newer files automatically.") .addToggle((toggle) => toggle.setValue(this.plugin.settings.resolveConflictsByNewerFile).onChange(async (value) => { this.plugin.settings.resolveConflictsByNewerFile = value; await this.plugin.saveSettings(); }) ); // new Setting(containerSyncSettingEl) // .setName("Skip old files on sync") // .setDesc("Skip old incoming if incoming changes older than storage.") // .addToggle((toggle) => // toggle.setValue(this.plugin.settings.skipOlderFilesOnSync).onChange(async (value) => { // this.plugin.settings.skipOlderFilesOnSync = value; // await this.plugin.saveSettings(); // }) // ); new Setting(containerSyncSettingEl) .setName("Check conflict only on opening file.") .setDesc("Do not check conflict while replication") .addToggle((toggle) => toggle.setValue(this.plugin.settings.checkConflictOnlyOnOpen).onChange(async (value) => { this.plugin.settings.checkConflictOnlyOnOpen = value; await this.plugin.saveSettings(); }) ); containerSyncSettingEl.createEl("div", { text: sanitizeHTMLToDom(`Advanced settings<br> If you reached the payload size limit when using IBM Cloudant, please set batch size and batch limit to a lower value.`), }); new Setting(containerSyncSettingEl) .setName("Batch size") .setDesc("Number of change feed items to process at a time. Defaults to 250.") .addText((text) => { text.setPlaceholder("") .setValue(this.plugin.settings.batch_size + "") .onChange(async (value) => { let v = Number(value); if (isNaN(v) || v < 10) { v = 10; } this.plugin.settings.batch_size = v; await this.plugin.saveSettings(); }); text.inputEl.setAttribute("type", "number"); }); new Setting(containerSyncSettingEl) .setName("Batch limit") .setDesc("Number of batches to process at a time. Defaults to 40. This along with batch size controls how many docs are kept in memory at a time.") .addText((text) => { text.setPlaceholder("") .setValue(this.plugin.settings.batches_limit + "") .onChange(async (value) => { let v = Number(value); if (isNaN(v) || v < 10) { v = 10; } this.plugin.settings.batches_limit = v; await this.plugin.saveSettings(); }); text.inputEl.setAttribute("type", "number"); }); addScreenElement("30", containerSyncSettingEl); const containerMiscellaneousEl = containerEl.createDiv(); containerMiscellaneousEl.createEl("h3", { text: "Miscellaneous" }); new Setting(containerMiscellaneousEl) .setName("Show status inside editor") .setDesc("") .addToggle((toggle) => toggle.setValue(this.plugin.settings.showStatusOnEditor).onChange(async (value) => { this.plugin.settings.showStatusOnEditor = value; await this.plugin.saveSettings(); }) ); new Setting(containerMiscellaneousEl) .setName("Check integrity on saving") .setDesc("Check database integrity on saving to database") .addToggle((toggle) => toggle.setValue(this.plugin.settings.checkIntegrityOnSave).onChange(async (value) => { this.plugin.settings.checkIntegrityOnSave = value; await this.plugin.saveSettings(); }) ); let currentPrest = "NONE"; new Setting(containerMiscellaneousEl) .setName("Presets") .setDesc("Apply preset configuration") .addDropdown((dropdown) => dropdown .addOptions({ NONE: "", LIVESYNC: "LiveSync", PERIODIC: "Periodic w/ batch", DISABLE: "Disable all sync" }) .setValue(currentPrest) .onChange((value) => (currentPrest = value)) ) .addButton((button) => button .setButtonText("Apply") .setDisabled(false) .setCta() .onClick(async () => { if (currentPrest == "") { Logger("Select any preset.", LOG_LEVEL.NOTICE); return; } this.plugin.settings.batchSave = false; this.plugin.settings.liveSync = false; this.plugin.settings.periodicReplication = false; this.plugin.settings.syncOnSave = false; this.plugin.settings.syncOnStart = false; this.plugin.settings.syncOnFileOpen = false; if (currentPrest == "LIVESYNC") { this.plugin.settings.liveSync = true; Logger("Synchronization setting configured as LiveSync.", LOG_LEVEL.NOTICE); } else if (currentPrest == "PERIODIC") { this.plugin.settings.batchSave = true; this.plugin.settings.periodicReplication = true; this.plugin.settings.syncOnSave = false; this.plugin.settings.syncOnStart = true; this.plugin.settings.syncOnFileOpen = true; Logger("Synchronization setting configured as Periodic sync with batch database update.", LOG_LEVEL.NOTICE); } else { Logger("All synchronization disabled.", LOG_LEVEL.NOTICE); } this.plugin.saveSettings(); await this.plugin.realizeSettingSyncMode(); }) ); new Setting(containerMiscellaneousEl) .setName("Use history") .setDesc("Use history dialog (Restart required, auto compaction would be disabled, and more storage will be consumed)") .addToggle((toggle) => toggle.setValue(this.plugin.settings.useHistory).onChange(async (value) => { this.plugin.settings.useHistory = value; await this.plugin.saveSettings(); }) ); addScreenElement("40", containerMiscellaneousEl); const containerHatchEl = containerEl.createDiv(); containerHatchEl.createEl("h3", { text: "Hatch" }); if (this.plugin.localDatabase.remoteLockedAndDeviceNotAccepted) { const c = containerHatchEl.createEl("div", { text: "To prevent unwanted vault corruption, the remote database has been locked for synchronization, and this device was not marked as 'resolved'. it caused by some operations like this. re-initialized. Local database initialization should be required. please back your vault up, reset local database, and press 'Mark this device as resolved'. ", }); c.createEl("button", { text: "I'm ready, mark this device 'resolved'" }, (e) => { e.addClass("mod-warning"); e.addEventListener("click", async () => { await this.plugin.markRemoteResolved(); c.remove(); }); }); c.addClass("op-warn"); } else { if (this.plugin.localDatabase.remoteLocked) { const c = containerHatchEl.createEl("div", { text: "To prevent unwanted vault corruption, the remote database has been locked for synchronization. (This device is marked 'resolved') When all your devices are marked 'resolved', unlock the database.", }); c.createEl("button", { text: "I'm ready, unlock the database" }, (e) => { e.addClass("mod-warning"); e.addEventListener("click", async () => { await this.plugin.markRemoteUnlocked(); c.remove(); }); }); c.addClass("op-warn"); } } const hatchWarn = containerHatchEl.createEl("div", { text: `To stop the bootup sequence for fixing problems on databases, you can put redflag.md on top of your vault (Rebooting obsidian is required).` }); hatchWarn.addClass("op-warn-info"); const dropHistory = async (sendToServer: boolean) => { this.plugin.settings.liveSync = false; this.plugin.settings.periodicReplication = false; this.plugin.settings.syncOnSave = false; this.plugin.settings.syncOnStart = false; this.plugin.settings.syncOnFileOpen = false; await this.plugin.saveSettings(); applyDisplayEnabled(); await this.plugin.resetLocalDatabase(); if (sendToServer) { await this.plugin.initializeDatabase(true); await this.plugin.markRemoteLocked(); await this.plugin.tryResetRemoteDatabase(); await this.plugin.markRemoteLocked(); await this.plugin.replicateAllToServer(true); } else { await this.plugin.markRemoteResolved(); await this.plugin.replicate(true); } }; new Setting(containerHatchEl) .setName("Verify and repair all files") .setDesc("Verify and repair all files and update database without dropping history") .addButton((button) => button .setButtonText("Verify and repair") .setDisabled(false) .setWarning() .onClick(async () => { const files = this.app.vault.getFiles(); Logger("Verify and repair all files started", LOG_LEVEL.NOTICE); const notice = NewNotice("", 0); let i = 0; for (const file of files) { i++; Logger(`Update into ${file.path}`); notice.setMessage(`${i}/${files.length}\n${file.path}`); try { await this.plugin.updateIntoDB(file); } catch (ex) { Logger("could not update:"); Logger(ex); } } notice.hide(); Logger("done", LOG_LEVEL.NOTICE); }) ); new Setting(containerHatchEl) .setName("Sanity check") .setDesc("Verify") .addButton((button) => button .setButtonText("Sanity check") .setDisabled(false) .setWarning() .onClick(async () => { const notice = NewNotice("", 0); Logger(`Begin sanity check`, LOG_LEVEL.INFO); notice.setMessage(`Begin sanity check`); await runWithLock("sancheck", true, async () => { const db = this.plugin.localDatabase.localDatabase; const wf = await db.allDocs(); const filesDatabase = wf.rows.filter((e) => !e.id.startsWith("h:") && !e.id.startsWith("ps:") && e.id != "obsydian_livesync_version").map((e) => e.id); let count = 0; for (const id of filesDatabase) { count++; notice.setMessage(`${count}/${filesDatabase.length}\n${id2path(id)}`); const w = await db.get<EntryDoc>(id); if (!(await this.plugin.localDatabase.sanCheck(w))) { Logger(`The file ${id2path(id)} missing child(ren)`, LOG_LEVEL.NOTICE); } } }); notice.hide(); Logger(`Done`, LOG_LEVEL.NOTICE); // Logger("done", LOG_LEVEL.NOTICE); }) ); new Setting(containerHatchEl) .setName("Drop History") .setDesc("Initialize local and remote database, and send all or retrieve all again.") .addButton((button) => button .setButtonText("Drop and send") .setWarning() .setDisabled(false) .setClass("sls-btn-left") .onClick(async () => { await dropHistory(true); }) ) .addButton((button) => button .setButtonText("Drop and receive") .setWarning() .setDisabled(false) .setClass("sls-btn-right") .onClick(async () => { await dropHistory(false); }) ); new Setting(containerHatchEl) .setName("Lock remote database") .setDesc("Lock remote database for synchronize") .addButton((button) => button .setButtonText("Lock") .setDisabled(false) .setWarning() .onClick(async () => { await this.plugin.markRemoteLocked(); }) ); new Setting(containerHatchEl) .setName("Suspend file watching") .setDesc("if enables it, all file operations are ignored.") .addToggle((toggle) => toggle.setValue(this.plugin.settings.suspendFileWatching).onChange(async (value) => { this.plugin.settings.suspendFileWatching = value; await this.plugin.saveSettings(); }) ); containerHatchEl.createEl("div", { text: sanitizeHTMLToDom(`Advanced buttons<br> These buttons could break your database easily.`), }); new Setting(containerHatchEl) .setName("Reset remote database") .setDesc("Reset remote database, this affects only database. If you replicate again, remote database will restored by local database.") .addButton((button) => button .setButtonText("Reset") .setDisabled(false) .setWarning() .onClick(async () => { await this.plugin.tryResetRemoteDatabase(); }) ); new Setting(containerHatchEl) .setName("Reset local database") .setDesc("Reset local database, this affects only database. If you replicate again, local database will restored by remote database.") .addButton((button) => button .setButtonText("Reset") .setDisabled(false) .setWarning() .onClick(async () => { await this.plugin.resetLocalDatabase(); }) ); new Setting(containerHatchEl) .setName("Initialize local database again") .setDesc("WARNING: Reset local database and reconstruct by storage data. It affects local database, but if you replicate remote as is, remote data will be merged or corrupted.") .addButton((button) => button .setButtonText("INITIALIZE") .setWarning() .setDisabled(false) .onClick(async () => { await this.plugin.resetLocalDatabase(); await this.plugin.initializeDatabase(); }) ); new Setting(containerHatchEl) .setName("Drop old encrypted database") .setDesc("WARNING: Please use this button only when you have failed on converting old-style localdatabase at v0.10.0.") .addButton((button) => button .setButtonText("Drop") .setWarning() .setDisabled(false) .onClick(async () => { await this.plugin.resetLocalOldDatabase(); await this.plugin.initializeDatabase(); }) ); addScreenElement("50", containerHatchEl); // With great respect, thank you TfTHacker! // refered: https://github.com/TfTHacker/obsidian42-brat/blob/main/src/features/BetaPlugins.ts const containerPluginSettings = containerEl.createDiv(); containerPluginSettings.createEl("h3", { text: "Plugins and settings (beta)" }); const updateDisabledOfDeviceAndVaultName = () => { vaultName.setDisabled(this.plugin.settings.autoSweepPlugins || this.plugin.settings.autoSweepPluginsPeriodic); vaultName.setTooltip(this.plugin.settings.autoSweepPlugins || this.plugin.settings.autoSweepPluginsPeriodic ? "You could not change when you enabling auto scan." : ""); }; new Setting(containerPluginSettings).setName("Enable plugin synchronization").addToggle((toggle) => toggle.setValue(this.plugin.settings.usePluginSync).onChange(async (value) => { this.plugin.settings.usePluginSync = value; await this.plugin.saveSettings(); }) ); new Setting(containerPluginSettings) .setName("Scan plugins automatically") .setDesc("Scan plugins before replicating.") .addToggle((toggle) => toggle.setValue(this.plugin.settings.autoSweepPlugins).onChange(async (value) => { this.plugin.settings.autoSweepPlugins = value; updateDisabledOfDeviceAndVaultName(); await this.plugin.saveSettings(); }) ); new Setting(containerPluginSettings) .setName("Scan plugins periodically") .setDesc("Scan plugins each 1 minutes.") .addToggle((toggle) => toggle.setValue(this.plugin.settings.autoSweepPluginsPeriodic).onChange(async (value) => { this.plugin.settings.autoSweepPluginsPeriodic = value; updateDisabledOfDeviceAndVaultName(); await this.plugin.saveSettings(); }) ); new Setting(containerPluginSettings) .setName("Notify updates") .setDesc("Notify when any device has a newer plugin or its setting.") .addToggle((toggle) => toggle.setValue(this.plugin.settings.notifyPluginOrSettingUpdated).onChange(async (value) => { this.plugin.settings.notifyPluginOrSettingUpdated = value; await this.plugin.saveSettings(); }) ); const vaultName = new Setting(containerPluginSettings) .setName("Device and Vault name") .setDesc("") .addText((text) => { text.setPlaceholder("desktop-main") .setValue(this.plugin.deviceAndVaultName) .onChange(async (value) => { this.plugin.deviceAndVaultName = value; await this.plugin.saveSettings(); }); // text.inputEl.setAttribute("type", "password"); }); new Setting(containerPluginSettings) .setName("Open") .setDesc("Open the plugin dialog") .addButton((button) => { button .setButtonText("Open") .setDisabled(false) .onClick(() => { this.plugin.showPluginSyncModal(); }); }); updateDisabledOfDeviceAndVaultName(); addScreenElement("60", containerPluginSettings); const containerCorruptedDataEl = containerEl.createDiv(); containerCorruptedDataEl.createEl("h3", { text: "Corrupted or missing data" }); containerCorruptedDataEl.createEl("h4", { text: "Corrupted" }); if (Object.keys(this.plugin.localDatabase.corruptedEntries).length > 0) { const cx = containerCorruptedDataEl.createEl("div", { text: "If you have copy of these items on any device, simply edit once or twice. Or not, delete this. sorry.." }); for (const k in this.plugin.localDatabase.corruptedEntries) { const xx = cx.createEl("div", { text: `${k}` }); const ba = xx.createEl("button", { text: `Delete this` }, (e) => { e.addEventListener("click", async () => { await this.plugin.localDatabase.deleteDBEntry(k); xx.remove(); }); }); ba.addClass("mod-warning"); xx.createEl("button", { text: `Restore from file` }, (e) => { e.addEventListener("click", async () => { const f = await this.app.vault.getFiles().filter((e) => path2id(e.path) == k); if (f.length == 0) { Logger("Not found in vault", LOG_LEVEL.NOTICE); return; } await this.plugin.updateIntoDB(f[0]); xx.remove(); }); }); xx.addClass("mod-warning"); } } else { containerCorruptedDataEl.createEl("div", { text: "There is no corrupted data." }); } containerCorruptedDataEl.createEl("h4", { text: "Missing or waiting" }); if (Object.keys(this.plugin.queuedFiles).length > 0) { const cx = containerCorruptedDataEl.createEl("div", { text: "These files have missing or waiting chunks. Perhaps almost chunks will be found in a while after replication. But if there're no chunk, you have to restore database entry from existed file by hitting the button below.", }); const files = [...new Set([...this.plugin.queuedFiles.map((e) => e.entry._id)])]; for (const k of files) { const xx = cx.createEl("div", { text: `${id2path(k)}` }); const ba = xx.createEl("button", { text: `Delete this` }, (e) => { e.addEventListener("click", async () => { await this.plugin.localDatabase.deleteDBEntry(k); xx.remove(); }); }); ba.addClass("mod-warning"); xx.createEl("button", { text: `Restore from file` }, (e) => { e.addEventListener("click", async () => { const f = await this.app.vault.getFiles().filter((e) => path2id(e.path) == k); if (f.length == 0) { Logger("Not found in vault", LOG_LEVEL.NOTICE); return; } await this.plugin.updateIntoDB(f[0]); xx.remove(); }); }); xx.addClass("mod-warning"); } } else { containerCorruptedDataEl.createEl("div", { text: "There is no missing or waiting chunk." }); } applyDisplayEnabled(); addScreenElement("70", containerCorruptedDataEl); changeDisplay("0"); } }
the_stack
import { colors, fs, path, ts } from "../../deps.ts"; import { Asset, getAsset } from "../../graph.ts"; import { Logger } from "../../logger.ts"; import { addRelativePrefix, timestamp } from "../../_util.ts"; import { Chunk, Context, DependencyType, Export, Format, getFormat, Item, } from "../plugin.ts"; import { typescriptInjectDependenciesTranformer } from "./dependencies/inject_dependencies.ts"; import { extractIdentifiersFromSourceFile } from "./identifiers/extract_identifiers.ts"; import { createIdentifierMap, createImportIdentifierMap, defaultKeyword, getIdentifier, IdentifierMap, } from "./identifiers/_util.ts"; import { typescriptTransformDynamicImportTransformer } from "./transformers/dynamic_imports.ts"; import { typescriptTransformImportsExportsTransformer } from "./transformers/imports_exports.ts"; import { typescriptRemoveModifiersTransformer } from "./transformers/remove_modifiers.ts"; import { TypescriptPlugin } from "./typescript.ts"; import { topologicalSort } from "./_util.ts"; const { factory } = ts; const printer: ts.Printer = ts.createPrinter({ removeComments: false }); async function splitDependencyItems(dependencyItems: Item[], context: Context) { const { chunks, logger, bundler } = context; const importItemMap: Map<string, Item> = new Map(); const inlineItemMap: Map<string, Item> = new Map(); for (const dependencyItem of dependencyItems) { const { history } = dependencyItem; const input = history[0]; if ( chunks.some((chunk) => chunk.item.history[0] === input) ) { if (importItemMap.has(input)) continue; importItemMap.set(input, dependencyItem); logger.debug( colors.dim(`→`), colors.dim(`Import`), colors.dim(input), colors.dim( `{ ${DependencyType[dependencyItem.type]} }`, ), ); } else { if (inlineItemMap.has(input)) continue; inlineItemMap.set(input, dependencyItem); logger.debug( colors.dim(`→`), colors.dim(`Inline`), colors.dim(input), colors.dim( `{ ${DependencyType[dependencyItem.type]} }`, ), ); const chunk = await bundler.createChunk(dependencyItem, { ...context, logger: new Logger({ logLevel: logger.logLevel, quiet: true, }), }, dependencyItems); dependencyItems.push(...chunk.dependencyItems); } } return { importItems: [...importItemMap.values()], inlineItems: [...inlineItemMap.values()], }; } async function createUpdateItems( bundleInput: string, inlineItems: Item[], context: Context, ) { const { reload, bundler } = context; const updateItems: Item[] = []; for (const dependencyItem of inlineItems) { const { history } = dependencyItem; const input = history[0]; const needsReload = reload === true || Array.isArray(reload) && reload.includes(input); const dependencyNeedsUpdate = needsReload || !await bundler.hasCache(bundleInput, input, context); if (dependencyNeedsUpdate) { updateItems.push(dependencyItem); } } return updateItems; } /** * create iffe expressios from dependencyItems * ```ts * const mod = (async () => { * … * })(); * const mod1 = (async () => { * … * })(); * ``` */ async function createInlineSources( bundleItem: Item, inlineItems: Item[], updateItems: Item[], identifierMap: IdentifierMap, importIdentifierMap: IdentifierMap, context: Context, ) { const { graph, bundler } = context; const bundleInput = bundleItem.history[0]; const bundleAsset = getAsset(graph, bundleInput, bundleItem.type); const inlineSources: string[] = []; for (const inlineItem of inlineItems) { const { history } = inlineItem; const input = history[0]; if ( (Array.isArray(context.reload) && context.reload.includes(input)) || context.reload || updateItems.includes(inlineItem) || !await bundler.hasCache(bundleInput, input, context) ) { const source = await createInlineSource( bundleAsset, inlineItem, identifierMap, importIdentifierMap, context, ); inlineSources.push(source); } else { const source = await bundler.getCache(bundleInput, input, context); if (source === undefined) { throw Error(`cache file for input not found: '${input}'`); } inlineSources.push(source); } } return inlineSources; } /** * create iffe expression from dependencyItem * ```ts * const mod = (async () => { * … * })(); * ``` */ async function createInlineSource( bundleAsset: Asset, dependencyItem: Item, identifierMap: IdentifierMap, importIdentifierMap: IdentifierMap, context: Context, ) { const { graph, bundler, logger, importMap } = context; const bundleInput = bundleAsset.input; const bundleOutput = bundleAsset.output; const { history, type } = dependencyItem; const input = history[0]; const asset = getAsset(graph, input, type); const transformTime = performance.now(); let newSourceFile: ts.SourceFile | undefined; const format = getFormat(input); switch (format) { case Format.Script: { const sourceFile = await bundler.transformSource( bundleInput, dependencyItem, context, ) as ts.SourceFile; const { transformed } = ts.transform(sourceFile, [ typescriptTransformImportsExportsTransformer( importMap, importIdentifierMap, identifierMap, ), typescriptRemoveModifiersTransformer(), typescriptTransformDynamicImportTransformer(), typescriptInjectDependenciesTranformer( bundleOutput, dependencyItem, { graph, importMap }, ), ]); newSourceFile = transformed[0] as ts.SourceFile; const iifeNode = createIIFEExpression([ ...newSourceFile.statements, createReturnStatement(identifierMap, importIdentifierMap, asset.export), ]); switch (type) { case DependencyType.WebWorker: { break; } case DependencyType.Import: case DependencyType.DynamicImport: case DependencyType.Fetch: { let statmentNode: ts.ExportAssignment | ts.VariableStatement; if (input === bundleInput) { // default export (async () => { … })(); statmentNode = createDefaultExportAssignment(iifeNode); } else { const identifier = getIdentifier(importIdentifierMap, input); // const mod = (async () => { … })(); statmentNode = factory.createVariableStatement( undefined, factory.createVariableDeclarationList( [factory.createVariableDeclaration( factory.createIdentifier(identifier), undefined, undefined, iifeNode, )], ts.NodeFlags.Const, ), ); } newSourceFile = factory.createSourceFile( [statmentNode], factory.createToken(ts.SyntaxKind.EndOfFileToken), ts.NodeFlags.None, ); break; } } break; } case Format.Style: { const rootInput = history.length - 1; const source = await bundler.transformSource( /* get initial file to set corrent relative css paths */ history[rootInput], dependencyItem, context, ) as string; // `#a { … }` const sourceNode = factory .createNoSubstitutionTemplateLiteral( source, source, ); // const _default = `#a { … };` const statement: ts.Statement = factory.createVariableStatement( undefined, factory.createVariableDeclarationList( [factory.createVariableDeclaration( factory.createIdentifier(defaultIdentifier), undefined, undefined, sourceNode, )], ts.NodeFlags.Const, ), ); // (async () => { const _default = `#a { … }`; return { default: _default }; })(); const iifeExpression = createIIFEExpression([ statement, createReturnStatement(identifierMap, importIdentifierMap, { default: true, }), ]); const identifier = getIdentifier(importIdentifierMap, input); // const mod = (async () => { const _default = `#a { … }`; return { default: _default }; })(); const modStatement = factory.createVariableStatement( undefined, factory.createVariableDeclarationList( [factory.createVariableDeclaration( factory.createIdentifier(identifier), undefined, undefined, iifeExpression, )], ts.NodeFlags.Const, ), ); newSourceFile = factory.createSourceFile( [modStatement], factory.createToken(ts.SyntaxKind.EndOfFileToken), ts.NodeFlags.None, ); break; } case Format.Json: { let source = await bundler.transformSource( bundleInput, dependencyItem, context, ) as string; if (context.optimize) { source = JSON.stringify(JSON.parse(source)); } // `{ … }` const sourceNode = factory .createNoSubstitutionTemplateLiteral( source, source, ); // const _default = `{ … };` const statement: ts.Statement = factory.createVariableStatement( undefined, factory.createVariableDeclarationList( [factory.createVariableDeclaration( factory.createIdentifier(defaultIdentifier), undefined, undefined, sourceNode, )], ts.NodeFlags.Const, ), ); // (async () => { const _default = `{ … }`; return { default: _default }; })(); const iifeExpression = createIIFEExpression([ statement, createReturnStatement(identifierMap, importIdentifierMap, { default: true, }), ]); const identifier = getIdentifier(importIdentifierMap, input); // const mod = (async () => { const _default = `{ … }`; return { default: _default }; })(); const modStatement = factory.createVariableStatement( undefined, factory.createVariableDeclarationList( [factory.createVariableDeclaration( factory.createIdentifier(identifier), undefined, undefined, iifeExpression, )], ts.NodeFlags.Const, ), ); newSourceFile = factory.createSourceFile( [modStatement], factory.createToken(ts.SyntaxKind.EndOfFileToken), ts.NodeFlags.None, ); break; } } if (!newSourceFile) { throw new Error( `error during bundling '${bundleInput}': source file is invalid: '${input}'`, ); } logger.trace( colors.dim(`→`), "Transform", colors.dim(input), colors.dim(colors.italic(`(${timestamp(transformTime)})`)), ); const printTime = performance.now(); const source = printer.printFile(newSourceFile); const commentedSource = `/* ${input} */\n${source}`; logger.trace( colors.dim(`→`), "Print", colors.dim(input), colors.dim(colors.italic(`(${timestamp(printTime)})`)), ); await bundler.setCache( bundleInput, input, commentedSource, context, ); return commentedSource; } /** * create import statements from importItems * ```ts * import { … } from "./x.ts"; * import { … } from "./y.ts"; * ``` */ function createImportSources( bundleOutput: string, importItems: Item[], importIdentifierMap: IdentifierMap, context: Context, ) { const { graph } = context; const importNodes = importItems.map((importItem) => { const { history, type } = importItem; const input = history[0]; const identifier = getIdentifier(importIdentifierMap, input); const asset = getAsset(graph, input, type); const relativeOutput = addRelativePrefix( path.relative(path.dirname(bundleOutput), asset.output), ); return factory.createImportDeclaration( undefined, undefined, factory.createImportClause( false, factory.createIdentifier(identifier), undefined, ), factory.createStringLiteral(relativeOutput), ); }); const sourceFile = factory.createSourceFile( importNodes, ts.createToken(ts.SyntaxKind.EndOfFileToken), ts.NodeFlags.None, ); return printer.printFile(sourceFile); } /** * prepends * ```ts * export default … * ``` * to expression */ function createDefaultExportAssignment(expression: ts.Expression) { return factory.createExportAssignment( undefined, undefined, undefined, expression, ); } /** * create return statement * ```ts * return { … } * ``` */ const defaultIdentifier = "_default"; function createReturnStatement( identifierMap: IdentifierMap, importIdentifierMap: IdentifierMap, _export: Export, ) { const { specifiers, } = _export; const propertyAssignments = []; const propertySpecifierEntries: [string, string][] = []; if (_export.default) { propertySpecifierEntries.push([defaultKeyword, defaultIdentifier]); } if (specifiers) { propertySpecifierEntries.push(...Object.entries(specifiers)); } propertyAssignments.push( ...propertySpecifierEntries.map(([key, value]) => { if (identifierMap.has(value)) { value = identifierMap.get(value) as string; } if (key === value) { return factory.createShorthandPropertyAssignment( factory.createIdentifier(value), undefined, ); } else { return factory.createPropertyAssignment( factory.createIdentifier(key), factory.createIdentifier(value), ); } }), ); // add `...await mod` for namespaces if (_export.namespaces) { propertyAssignments.push(..._export.namespaces.map((dependency) => { const identifier = importIdentifierMap.get(dependency)!; return factory.createSpreadAssignment( factory.createAwaitExpression(factory.createIdentifier(identifier)), ); })); } return factory.createReturnStatement( factory.createObjectLiteralExpression( propertyAssignments, false, ), ); } /** * create iife expression * ```ts * (async () => { … })(); * ``` */ function createIIFEExpression( statements: ts.Statement[], ) { return factory.createCallExpression( factory.createParenthesizedExpression(factory.createArrowFunction( [factory.createModifier(ts.SyntaxKind.AsyncKeyword)], undefined, [], undefined, factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), factory.createBlock( statements, true, ), )), undefined, [], ); } function transpile( source: string, compilerOptions: Deno.CompilerOptions, ) { // const name = "/x.tsx"; // const { files, diagnostics } = await Deno.emit(name, { // sources: { // [name]: source, // }, // compilerOptions: { // target: "esnext", // module: "esnext", // strict: false, // ...compilerOptions, // }, // check: false, // }); // if (diagnostics.length) { // throw Error(diagnostics[0].messageText) // } // return files[`file://${name}.js`]; const tsCompilerOptions = ts.convertCompilerOptionsFromJson({ compilerOptions }, Deno.cwd()).options; return ts.transpile(source, { jsxFactory: "React.createElement", jsxFragmentFactory: "React.Fragment", jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext, ...tsCompilerOptions, }); } export class TypescriptTopLevelAwaitModulePlugin extends TypescriptPlugin { async createBundle(bundleChunk: Chunk, context: Context) { const { graph, bundler, logger } = context; const bundleItem = bundleChunk.item; const bundleInput = bundleItem.history[0]; const bundleAsset = getAsset(graph, bundleInput, bundleItem.type); bundler.logger.debug(colors.yellow("Bundle"), bundleInput); const dependencyItems = [...bundleChunk.dependencyItems]; // split dependency items into imports and inlines const { importItems, inlineItems } = await splitDependencyItems( dependencyItems, context, ); const importIdentifierMap = createImportIdentifierMap( graph, dependencyItems, ); // add bundleItem to be inlined inlineItems.push(bundleItem); // get all items that need an update const updateItems = await createUpdateItems( bundleInput, [...inlineItems, bundleItem], context, ); if (!updateItems.length && await fs.exists(bundleAsset.output)) { // return undefined if no update is needed return; } // sort inline items const sortedInlineItems = topologicalSort( inlineItems, graph, ); const blacklistIdentifiers = new Set( [ ...importIdentifierMap.values(), ], ); const identifiers: Set<string> = new Set(); // extract identifiers from all inlineItems await Promise.all(sortedInlineItems.map(async (dependencyItem) => { const sourceFile = await bundler.readSource( dependencyItem, context, ) as ts.SourceFile; extractIdentifiersFromSourceFile(sourceFile).forEach((identifier) => identifiers.add(identifier) ); })); const identifierMap = createIdentifierMap( identifiers, blacklistIdentifiers, new Map([[defaultKeyword, defaultIdentifier]]), ); const inlineSources = await createInlineSources( bundleItem, sortedInlineItems, updateItems, identifierMap, importIdentifierMap, context, ); const importSources = createImportSources( bundleAsset.output, importItems, importIdentifierMap, context, ); const moduleString = [importSources, inlineSources].join("\n"); const transpileTime = performance.now(); const transpiledSource = await transpile( moduleString, this.compilerOptions, ); logger.trace( colors.dim(`→`), "Transpile", colors.dim(bundleInput), colors.dim(colors.italic(`(${timestamp(transpileTime)})`)), ); return transpiledSource; } }
the_stack
import * as fsSyncer from 'fs-syncer' import * as typegen from '../src' import * as path from 'path' import {getHelper} from './helper' import './register-mock-serializer' export const {typegenOptions, logger, poolHelper: helper} = getHelper({__filename}) // todo: test two tables, where sql parser can't automatically tell which table the columns are from. beforeEach(async () => { jest.resetAllMocks() await helper.pool.query(helper.sql` create type test_enum as enum('aa', 'bb', 'cc'); create table test_table( id int primary key, n int, t text, t_nn text not null, cv varchar(1), arr text[], e test_enum, tz timestamptz, tz_nn timestamptz not null default now(), j json, jb jsonb, j_nn json not null, jb_nn jsonb not null ); comment on column test_table.t is 'Some custom comment on "t"'; `) }) test('write types', async () => { const syncer = fsSyncer.jestFixture({ targetState: { 'index.ts': ` import {sql} from 'slonik' export default [ sql\`select * from options_test.test_table\`, sql\`select id, t from test_table\`, sql\`select count(*) from test_table\`, sql\`select id as idalias, t as talias from test_table\`, sql\`select id from test_table where id = ${'${1}'} and n = ${'${2}'}\`, sql\`insert into test_table(id, j_nn, jb_nn) values (1, '{}', '{}')\`, sql\`update test_table set t = ''\`, sql\`insert into test_table(id, t_nn, j_nn, jb_nn) values (1, '', '{}', '{}') returning id, t\`, sql\`update test_table set t = '' returning id, t\`, sql\`insert into test_table as tt (id, j_nn, jb_nn) values (1, '{}', '{}') returning id, t\`, sql\`update test_table as tt set t = '' returning id, t\`, sql\`delete from test_table where t = '' returning id, t\`, sql\`select pg_advisory_lock(123)\`, sql\`select t1.id from test_table t1 join test_table t2 on t1.id = t2.n\`, sql\`select jb->'foo'->>'bar' from test_table\`, sql\`select n::numeric from test_table\`, sql\`select * from (values (1, 'one'), (2, 'two')) as vals (num, letter)\`, sql\`select t from (select id from test_table) t\`, sql\` select t as t_aliased1, t_nn as t_nn_aliased from test_table as tt1 where t_nn in ( select t_nn as t_aliased2 from test_table as tt2 where n = 1 ) \`, ] `, }, }) syncer.sync() await typegen.generate(typegenOptions(syncer.baseDir)) expect(syncer.yaml()).toMatchInlineSnapshot(` "--- index.ts: |- import {sql} from 'slonik' export default [ sql<queries.TestTable>\`select * from options_test.test_table\`, sql<queries.TestTable_id_t>\`select id, t from test_table\`, sql<queries.TestTable_count>\`select count(*) from test_table\`, sql<queries.TestTable_idalias_talias>\`select id as idalias, t as talias from test_table\`, sql<queries.TestTable_id>\`select id from test_table where id = \${1} and n = \${2}\`, sql<queries._void>\`insert into test_table(id, j_nn, jb_nn) values (1, '{}', '{}')\`, sql<queries._void>\`update test_table set t = ''\`, sql<queries.TestTable_id_t>\`insert into test_table(id, t_nn, j_nn, jb_nn) values (1, '', '{}', '{}') returning id, t\`, sql<queries.TestTable_id_t>\`update test_table set t = '' returning id, t\`, sql<queries.TestTable_id_t>\`insert into test_table as tt (id, j_nn, jb_nn) values (1, '{}', '{}') returning id, t\`, sql<queries.TestTable_id_t>\`update test_table as tt set t = '' returning id, t\`, sql<queries.TestTable_id_t>\`delete from test_table where t = '' returning id, t\`, sql<queries.PgAdvisoryLock>\`select pg_advisory_lock(123)\`, sql<queries.TestTable_id>\`select t1.id from test_table t1 join test_table t2 on t1.id = t2.n\`, sql<queries.Column>\`select jb->'foo'->>'bar' from test_table\`, sql<queries.TestTable_n>\`select n::numeric from test_table\`, sql<queries.Num_letter>\`select * from (values (1, 'one'), (2, 'two')) as vals (num, letter)\`, sql<queries.T>\`select t from (select id from test_table) t\`, sql<queries.TestTable_tAliased1_tNnAliased>\` select t as t_aliased1, t_nn as t_nn_aliased from test_table as tt1 where t_nn in ( select t_nn as t_aliased2 from test_table as tt2 where n = 1 ) \`, ] export declare namespace queries { // Generated by @slonik/typegen /** - query: \`select * from options_test.test_table\` */ export interface TestTable { /** column: \`options_test.test_table.id\`, not null: \`true\`, regtype: \`integer\` */ id: number /** column: \`options_test.test_table.n\`, regtype: \`integer\` */ n: number | null /** * Some custom comment on \\"t\\" * * column: \`options_test.test_table.t\`, regtype: \`text\` */ t: string | null /** column: \`options_test.test_table.t_nn\`, not null: \`true\`, regtype: \`text\` */ t_nn: string /** column: \`options_test.test_table.cv\`, regtype: \`character varying(1)\` */ cv: string | null /** column: \`options_test.test_table.arr\`, regtype: \`text[]\` */ arr: string[] | null /** column: \`options_test.test_table.e\`, regtype: \`test_enum\` */ e: ('aa' | 'bb' | 'cc') | null /** column: \`options_test.test_table.tz\`, regtype: \`timestamp with time zone\` */ tz: number | null /** column: \`options_test.test_table.tz_nn\`, not null: \`true\`, regtype: \`timestamp with time zone\` */ tz_nn: number /** column: \`options_test.test_table.j\`, regtype: \`json\` */ j: unknown /** column: \`options_test.test_table.jb\`, regtype: \`jsonb\` */ jb: unknown /** column: \`options_test.test_table.j_nn\`, not null: \`true\`, regtype: \`json\` */ j_nn: unknown /** column: \`options_test.test_table.jb_nn\`, not null: \`true\`, regtype: \`jsonb\` */ jb_nn: unknown } /** * queries: * - \`select id, t from test_table\` * - \`insert into test_table(id, t_nn, j_nn, jb_nn) values (1, '', '{}', '{}') returning id, t\` * - \`update test_table set t = '' returning id, t\` * - \`insert into test_table as tt (id, j_nn, jb_nn) values (1, '{}', '{}') returning id, t\` * - \`update test_table as tt set t = '' returning id, t\` * - \`delete from test_table where t = '' returning id, t\` */ export interface TestTable_id_t { /** column: \`options_test.test_table.id\`, not null: \`true\`, regtype: \`integer\` */ id: number /** * Some custom comment on \\"t\\" * * column: \`options_test.test_table.t\`, regtype: \`text\` */ t: string | null } /** - query: \`select count(*) from test_table\` */ export interface TestTable_count { /** not null: \`true\`, regtype: \`bigint\` */ count: number } /** - query: \`select id as idalias, t as talias from test_table\` */ export interface TestTable_idalias_talias { /** column: \`options_test.test_table.id\`, not null: \`true\`, regtype: \`integer\` */ idalias: number /** * Some custom comment on \\"t\\" * * column: \`options_test.test_table.t\`, regtype: \`text\` */ talias: string | null } /** * queries: * - \`select id from test_table where id = $1 and n = $2\` * - \`select t1.id from test_table t1 join test_table t2 on t1.id = t2.n\` */ export interface TestTable_id { /** column: \`options_test.test_table.id\`, not null: \`true\`, regtype: \`integer\` */ id: number } /** * queries: * - \`insert into test_table(id, j_nn, jb_nn) values (1, '{}', '{}')\` * - \`update test_table set t = ''\` */ export type _void = {} /** - query: \`select pg_advisory_lock(123)\` */ export interface PgAdvisoryLock { /** regtype: \`void\` */ pg_advisory_lock: void } /** - query: \`select jb->'foo'->>'bar' from test_table\` */ export interface Column { /** regtype: \`text\` */ '?column?': string | null } /** - query: \`select n::numeric from test_table\` */ export interface TestTable_n { /** regtype: \`numeric\` */ n: number | null } /** - query: \`select * from (values (1, 'one'), (2, 'two')) as vals (num, letter)\` */ export interface Num_letter { /** regtype: \`integer\` */ num: number | null /** regtype: \`text\` */ letter: string | null } /** - query: \`select t from (select id from test_table) t\` */ export interface T { /** regtype: \`record\` */ t: unknown } /** - query: \`select t as t_aliased1, t_nn as t_nn_ali... [truncated] ...ed2 from test_table as tt2 where n = 1 )\` */ export interface TestTable_tAliased1_tNnAliased { /** * Some custom comment on \\"t\\" * * column: \`options_test.test_table.t\`, regtype: \`text\` */ t_aliased1: string | null /** column: \`options_test.test_table.t_nn\`, not null: \`true\`, regtype: \`text\` */ t_nn_aliased: string } } " `) }) test('can write queries to separate file', async () => { const syncer = fsSyncer.jestFixture({ targetState: { 'a.ts': ` import {sql} from 'slonik' export default sql\`select 1 as a\` module queries { // this should be removed! } `, // this file has already imported its queries - need to make sure we don't end up with a double import statement 'b.ts': ` import {sql} from 'slonik' import * as queries from "./__sql__/b"; export default sql\`select 1 as a\` module queries { // this should be removed! } `, }, }) syncer.sync() await typegen.generate({ ...typegenOptions(syncer.baseDir), writeTypes: typegen.defaults.defaultWriteTypes({ queriesPathFromTS: filepath => path.join(path.dirname(filepath), '__sql__', path.basename(filepath)), }), }) expect(syncer.yaml()).toMatchInlineSnapshot(` "--- a.ts: |- import * as queries from './__sql__/a' import {sql} from 'slonik' export default sql<queries.A>\`select 1 as a\` b.ts: |- import {sql} from 'slonik' import * as queries from './__sql__/b' export default sql<queries.A>\`select 1 as a\` __sql__: a.ts: |- // Generated by @slonik/typegen /** - query: \`select 1 as a\` */ export interface A { /** regtype: \`integer\` */ a: number | null } b.ts: |- // Generated by @slonik/typegen /** - query: \`select 1 as a\` */ export interface A { /** regtype: \`integer\` */ a: number | null } " `) }) test('replaces existing queries module', async () => { const syncer = fsSyncer.jestFixture({ targetState: { 'index.ts': ` import {sql} from 'slonik' export default sql\`select 1 as a\` module queries { // this should be removed! } `, }, }) syncer.sync() await typegen.generate(typegenOptions(syncer.baseDir)) expect(syncer.yaml()).toMatchInlineSnapshot(` "--- index.ts: |- import {sql} from 'slonik' export default sql<queries.A>\`select 1 as a\` export declare namespace queries { // Generated by @slonik/typegen /** - query: \`select 1 as a\` */ export interface A { /** regtype: \`integer\` */ a: number | null } } " `) }) test('ignore irrelevant syntax', async () => { const syncer = fsSyncer.jestFixture({ targetState: { 'index.ts': ` import {sql} from 'slonik' export default () => { if (Math.random() > 0.5) { const otherTag: any = (val: any) => val return otherTag\`foo\` } if (Math.random() > 0.5) { const otherTag: any = {foo: (val: any) => val} return otherTag.foo\`bar\` } return sql\`select 1\` } `, }, }) syncer.sync() await typegen.generate(typegenOptions(syncer.baseDir)) expect(syncer.yaml()).toMatchInlineSnapshot(` "--- index.ts: |- import {sql} from 'slonik' export default () => { if (Math.random() > 0.5) { const otherTag: any = (val: any) => val return otherTag\`foo\` } if (Math.random() > 0.5) { const otherTag: any = {foo: (val: any) => val} return otherTag.foo\`bar\` } return sql<queries.Column>\`select 1\` } export declare namespace queries { // Generated by @slonik/typegen /** - query: \`select 1\` */ export interface Column { /** regtype: \`integer\` */ '?column?': number | null } } " `) }) test(`queries with syntax errors don't affect others`, async () => { const syncer = fsSyncer.jestFixture({ targetState: { 'index.ts': ` import {sql} from 'slonik' export default [ sql\`select id from options_test.test_table\`, // this should get a valid type sql\`this is a nonsense query which will cause an error\` ] `, }, }) syncer.sync() await typegen.generate(typegenOptions(syncer.baseDir)) expect(logger.warn).toHaveBeenCalledTimes(1) expect(logger.warn).toMatchInlineSnapshot(` - - >- [cwd]/packages/typegen/test/fixtures/options.test.ts/queries-with-syntax-errors-don-t-affect-others/index.ts:4 Describing query failed: AssertionError [ERR_ASSERTION]: Error running psql query. Query: "this is a nonsense query which will cause an error \\\\gdesc" Result: "psql:<stdin>:1: ERROR: syntax error at or near \\"this\\"\\nLINE 1: this is a nonsense query which will cause an error \\n ^" Error: Empty output received. `) expect(syncer.yaml()).toMatchInlineSnapshot(` "--- index.ts: |- import {sql} from 'slonik' export default [ sql<queries.TestTable>\`select id from options_test.test_table\`, // this should get a valid type sql\`this is a nonsense query which will cause an error\`, ] export declare namespace queries { // Generated by @slonik/typegen /** - query: \`select id from options_test.test_table\` */ export interface TestTable { /** column: \`options_test.test_table.id\`, not null: \`true\`, regtype: \`integer\` */ id: number } } " `) }) test('custom glob pattern', async () => { const syncer = fsSyncer.jestFixture({ targetState: { 'excluded.ts': ` import {sql} from 'slonik' export default sql\`select 0 as a\` `, 'included1.ts': ` import {sql} from 'slonik' export default sql\`select 1 as a\` `, 'included2.ts': ` import {sql} from 'slonik' export default sql\`select 2 as a\` `, }, }) syncer.sync() await typegen.generate({ ...typegenOptions(syncer.baseDir), glob: 'included*.ts', }) expect(syncer.yaml()).toMatchInlineSnapshot(` "--- excluded.ts: |- import {sql} from 'slonik' export default sql\`select 0 as a\` included1.ts: |- import {sql} from 'slonik' export default sql<queries.A>\`select 1 as a\` export declare namespace queries { // Generated by @slonik/typegen /** - query: \`select 1 as a\` */ export interface A { /** regtype: \`integer\` */ a: number | null } } included2.ts: |- import {sql} from 'slonik' export default sql<queries.A>\`select 2 as a\` export declare namespace queries { // Generated by @slonik/typegen /** - query: \`select 2 as a\` */ export interface A { /** regtype: \`integer\` */ a: number | null } } " `) })
the_stack
import { expect, preferencesTestSet, loadBackground, nextTick, Background, } from './setup'; preferencesTestSet.map(preferences => { describe(`preferences: ${JSON.stringify(preferences)}`, () => { describe('Multi-Account Containers Confirm Page reopening', () => { [false, true].map(macWasFaster => { ['first', 'last', 'firstrace', 'lastrace'].map(confirmPage => { describe(`variant: macWasFaster ${macWasFaster} / confirmPage ${confirmPage}`, () => { let bg: Background; beforeEach(async () => { bg = await loadBackground({ preferences }); }); describe('opening new tmptab', () => { beforeEach(async () => { await bg.helper.openNewTmpTab({ tabId: 1, createsTabId: 2, createsContainer: 'firefox-tmp1', }); await nextTick(); }); describe('and opening a mac assigned website with not "remember my choice"', () => { let originContainer = 'firefox-tmp1'; if (preferences.automaticMode.newTab === 'navigation') { originContainer = 'firefox-default'; } beforeEach(async () => { bg.browser.runtime.sendMessage.resolves({ userContextId: '1', neverAsk: false, }); const request = { requestId: 1, tabId: 2, createsTabId: 3, originContainer, url: 'http://example.com', macWasFaster, }; const confirmPageOptions = { tabId: 3, originContainer, targetContainer: 'firefox-container-1', url: 'http://example.com', macWasFaster, resetHistory: true, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const promises: any[] = []; switch (confirmPage) { case 'first': await bg.helper.openMacConfirmPage(confirmPageOptions); await bg.helper.request(request); break; case 'last': await bg.helper.request(request); await bg.helper.openMacConfirmPage(confirmPageOptions); break; case 'firstrace': promises.push( bg.helper.openMacConfirmPage(confirmPageOptions) ); promises.push(bg.helper.request(request)); break; case 'lastrace': promises.push(bg.helper.request(request)); promises.push( bg.helper.openMacConfirmPage(confirmPageOptions) ); break; } await Promise.all(promises); await nextTick(); }); it('should sometimes reopen the confirm page once', async () => { // TODO in fact, reopen *should never* be triggered since the tmpcontainer is clean // but if it gets reopened, then it should be reopened at most once if (bg.browser.tabs.create.callCount) { bg.browser.tabs.create.should.have.been.calledOnce; } else { bg.browser.tabs.create.should.not.have.been.called; } if (bg.browser.tabs.remove.callCount) { bg.browser.tabs.remove.should.have.been.calledOnce; } else { bg.browser.tabs.remove.should.not.have.been.called; } }); describe('follow up requests', () => { ['current', 'target'].map(macConfirmChoice => { describe(`variant: macConfirmChoice ${macConfirmChoice}`, () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any let results: any[]; beforeEach(async () => { let tabId, originContainer; switch (macConfirmChoice) { case 'current': tabId = 3; originContainer = 'firefox-tmp1'; break; case 'target': tabId = 4; originContainer = 'firefox-container-1'; } const request1 = bg.helper.request({ requestId: 2, tabId, originContainer, url: 'http://example.com', resetHistory: true, }); const request2 = bg.helper.request({ requestId: 2, tabId, originContainer, url: 'https://example.com', }); const request3 = bg.helper.request({ requestId: 3, tabId, originContainer, url: 'https://example.com', }); results = await Promise.all([ request1, request2, request3, ]); await nextTick(); }); it('should not be canceled', async () => { expect(results[0]).to.be.undefined; expect(results[1]).to.be.undefined; expect(results[2]).to.be.undefined; }); it('should not trigger reopening', async () => { bg.browser.tabs.create.should.not.have.been.called; bg.browser.tabs.remove.should.not.have.been.called; }); }); }); }); }); }); describe('navigating in a permanent container tab', () => { describe('and opening a mac assigned website with not "remember my choice"', () => { const originContainer = 'firefox-container-1'; beforeEach(async () => { bg.browser.runtime.sendMessage.resolves({ userContextId: '2', neverAsk: false, }); const request = { requestId: 1, tabId: 2, createsTabId: 3, originContainer, url: 'http://example.com', macWasFaster, }; const confirmPageOptions = { tabId: 3, originContainer, targetContainer: 'firefox-container-2', url: 'http://example.com', macWasFaster, resetHistory: true, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const promises: any[] = []; switch (confirmPage) { case 'first': await bg.helper.openMacConfirmPage(confirmPageOptions); await bg.helper.request(request); break; case 'last': await bg.helper.request(request); await bg.helper.openMacConfirmPage(confirmPageOptions); break; case 'firstrace': promises.push( bg.helper.openMacConfirmPage(confirmPageOptions) ); promises.push(bg.helper.request(request)); break; case 'lastrace': promises.push(bg.helper.request(request)); promises.push( bg.helper.openMacConfirmPage(confirmPageOptions) ); break; } await Promise.all(promises); await nextTick(); }); it('should not reopen the confirm page', async () => { bg.browser.tabs.create.should.not.have.been.called; bg.browser.tabs.remove.should.not.have.been.called; }); }); }); describe('opening new tmptab', () => { beforeEach(async () => { await bg.helper.openNewTmpTab({ tabId: 1, createsTabId: 2, createsContainer: 'firefox-tmp1', }); await nextTick(); }); describe('and opening a not mac assigned website', () => { const newTmpTabId = 2; beforeEach(async () => { await bg.helper.request({ requestId: 1, tabId: newTmpTabId, originContainer: 'firefox-tmp1', url: 'http://example.com', resetHistory: true, }); }); const clickPreferences: Array<{ click: { type: 'middle' | 'left' | 'ctrlleft'; action: 'always' | 'never'; }; }> = [ { click: { type: 'middle', action: 'never', }, }, { click: { type: 'middle', action: 'always', }, }, { click: { type: 'ctrlleft', action: 'never', }, }, { click: { type: 'ctrlleft', action: 'always', }, }, { click: { type: 'left', action: 'never', }, }, { click: { type: 'left', action: 'always', }, }, ]; clickPreferences.map(preferences => { describe(`preferences: ${JSON.stringify( preferences )}`, () => { describe('clicks on links in the loaded website that are mac assigned with not "remember my choice"', () => { beforeEach(async () => { bg.tmp.storage.local.preferences.isolation.global.mouseClick[ preferences.click.type ].action = preferences.click.action; bg.browser.runtime.sendMessage.resolves({ userContextId: '1', neverAsk: false, }); await bg.helper.mouseClickOnLink({ clickType: preferences.click.type, senderUrl: 'http://example.com', targetUrl: 'http://notexample.com', }); const request = { requestId: 2, originContainer: 'firefox-tmp1', url: 'http://notexample.com', macWasFaster, resetHistory: true, }; const confirmPageOptions = { tabId: 3, originContainer: 'firefox-tmp1', targetContainer: 'firefox-container-1', url: 'http://notexample.com', }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const promises: any[] = []; switch (confirmPage) { case 'first': await bg.helper.openMacConfirmPage( confirmPageOptions ); await bg.helper.request(request); break; case 'last': await bg.helper.request(request); await bg.helper.openMacConfirmPage( confirmPageOptions ); break; case 'firstrace': promises.push( bg.helper.openMacConfirmPage(confirmPageOptions) ); promises.push(bg.helper.request(request)); break; case 'lastrace': promises.push(bg.helper.request(request)); promises.push( bg.helper.openMacConfirmPage(confirmPageOptions) ); break; } await Promise.all(promises); await nextTick(); }); it('should do the right thing', async () => { switch (preferences.click.action) { case 'always': bg.browser.tabs.remove.should.have.been.calledOnce; bg.browser.tabs.create.should.have.been.calledOnce; break; case 'never': bg.browser.tabs.remove.should.not.have.been.called; bg.browser.tabs.create.should.not.have.been.called; } }); }); }); }); }); }); }); }); }); }); }); });
the_stack
import * as oauth1 from './strategies/oauth1' import * as oauth2 from './strategies/oauth2' import { authenticate, fetchAuthDetails } from './strategy' import { MiddlewareTestHarness } from '../../../../tests/utils' import { TAuthenticateRequest, EAuthType } from './types' import { RequestHandler } from 'express' import { TBackendRequestV4 } from '../../../types' // mport { MissingAuthId, CredentialsNotConfigured, InvalidAuthId } from './errors' jest.mock('../../clients/integrations') jest.mock('./strategies/api-key') jest.mock('./strategies/basic') jest.mock('./strategies/oauth1') jest.mock('./strategies/oauth2') describe('authenticate', () => { const testResponse = { test: 'response' } const setup = (authType: EAuthType) => new MiddlewareTestHarness({ configureRequest: (req: TAuthenticateRequest) => { req.integrationConfig = { authType } }, testMiddleware: authenticate }) const mockAuth = (test: MiddlewareTestHarness<TAuthenticateRequest>, middleware: RequestHandler) => { // mocked(middleware).mockImplementationOnce((req: TAuthenticateRequest, res: Response, next: NextFunction) => { // expect(req).toBe(test.req) // res.json(testResponse).end() // next() // }) } describe('when the authType is OAuth1', () => { it('passes through to the oauth1 authenticate middleware', async () => { const test = setup(EAuthType.OAuth1) mockAuth(test, oauth1.authenticate) await test .get() .expect(testResponse) .expect(200) }) }) describe('when the authType is OAuth2', () => { it('passes through to the oauth1 authenticate middleware', async () => { const test = setup(EAuthType.OAuth2) mockAuth(test, oauth2.authenticate) await test .get() .expect(testResponse) .expect(200) }) }) describe('when the authType is any other type', () => { it('raises an OAuthOnlyEndpoint error', async () => { const test = setup(EAuthType.NoAuth) await test.get().expect(422) expect(test.err).toMatchSnapshot() }) }) }) describe('fetchAuthDetails', () => { const log = jest.fn() const setup = ({ withAuthId = true, withSetupId = true, authType }) => new MiddlewareTestHarness({ configureRequest: (req: TBackendRequestV4) => { req.integration = { buid: 'test-buid', config: jest.fn(() => ({ authType, some: 'config' })) } req.buid = 'test-buid' if (withAuthId) { req.authId = 'test-auth-id' } if (withSetupId) { req.setupId = 'test-setup-id' } req.logger = { log } }, testMiddleware: fetchAuthDetails }) beforeEach(() => { log.mockClear() }) describe('when the authType is NoAuth', () => { it('returns no auth details', async () => { const test = setup({ authType: EAuthType.NoAuth }) await test.get().expect(200) expect(test.req.auth).toEqual({}) }) }) describe('when the authType is Basic', () => { const authDetails = { username: 'test-user', password: 'test-password' } beforeEach(() => { // mocked(basic.fetchAuthDetails).mockClear() }) describe('when both a setupId and authId were provided', () => { const setupParams = { authType: EAuthType.NoAuth } it('uses the basic strategy to fetch the auth details', async () => { // mocked(basic.fetchAuthDetails).mockResolvedValueOnce(authDetails) const test = setup(setupParams) await test.get().expect(200) expect(test.req.auth).toEqual(authDetails) }) }) describe('when NO setupId was provided', () => { const setupParams = { authType: EAuthType.NoAuth, withSetupId: false } it('raises a CredentialsNotConfigured error', async () => { const test = setup(setupParams) await test.get().expect(422) expect(test.err).toMatchInlineSnapshot(` [CredentialsNotConfigured: Missing credentials for the 'test-alias' API Please configure the credentials in the dashboard and try again. See the following link for information: https://docs.bearer.sh/dashboard/apis] `) }) }) describe('when NO authId was provided', () => { const setupParams = { authType: EAuthType.NoAuth, withAuthId: false } it('uses the basic strategy to fetch the auth details', async () => { // mocked(basic.fetchAuthDetails).mockResolvedValueOnce(authDetails) const test = setup(setupParams) await test.get().expect(200) expect(test.req.auth).toEqual(authDetails) }) }) }) describe('when the authType is ApiKey', () => { // const authDetails = { apiKey: 'test-api-key' } beforeEach(() => { // mocked(apiKey.fetchAuthDetails).mockClear() }) describe('when both a setupId and authId were provided', () => { // const setupParams = { authType: EAuthType.NoAuth } it('uses the api key strategy to fetch the auth details', async () => { // mocked(apiKey.fetchAuthDetails).mockResolvedValueOnce(authDetails) // const test = setup(setupParams) // await test.get().expect(200) // expect(test.req.auth).toEqual(authDetails) }) }) describe('when NO setupId was provided', () => { const setupParams = { authType: EAuthType.NoAuth, withSetupId: false } it('raises a CredentialsNotConfigured error', async () => { const test = setup(setupParams) await test.get().expect(422) expect(test.err).toMatchInlineSnapshot(` [CredentialsNotConfigured: Missing credentials for the 'test-alias' API Please configure the credentials in the dashboard and try again. See the following link for information: https://docs.bearer.sh/dashboard/apis] `) }) }) describe('when NO authId was provided', () => { // const setupParams = { authType: EAuthType.NoAuth, withAuthId: false } it('uses the api key strategy to fetch the auth details', async () => { // mocked(apiKey.fetchAuthDetails).mockResolvedValueOnce(authDetails) // const test = setup(setupParams) // await test.get().expect(200) // expect(test.req.auth).toEqual(authDetails) // }) }) }) describe('when the authType is OAuth1', () => { const authDetails = { accessToken: 'test-access-token', tokenSecret: 'test-token-secret', consumerKey: 'test-consumer-key', consumerSecret: 'test-consumer-secret' } beforeEach(() => { // mocked(oauth1.fetchAuthDetails).mockClear() }) describe('when both a setupId and authId were provided', () => { const setupParams = { authType: EAuthType.OAuth1 } it('uses the oauth1 strategy to fetch the auth details', async () => { // mocked(oauth1.fetchAuthDetails).mockResolvedValueOnce(authDetails) const test = setup(setupParams) await test.get().expect(200) expect(test.req.auth).toEqual(authDetails) }) }) describe('when NO setupId was provided', () => { const setupParams = { authType: EAuthType.OAuth1, withSetupId: false } it('uses the oauth1 strategy to fetch the auth details', async () => { // mocked(oauth1.fetchAuthDetails).mockResolvedValueOnce(authDetails) const test = setup(setupParams) await test.get().expect(200) expect(test.req.auth).toEqual(authDetails) }) }) describe('when NO authId was provided', () => { const setupParams = { authType: EAuthType.OAuth1, withAuthId: false } it('raises a MissingAuthId error ', async () => { const test = setup(setupParams) await test.get().expect(401) expect(test.err).toMatchInlineSnapshot(` [MissingAuthId: You must supply an authId to use the 'test-alias' API Please try again with a valid authId. See the following link for information on how to obtain an authId: https://docs.bearer.sh/faq/connect-button] `) }) }) }) describe('when the authType is OAuth2', () => { const authDetails = { idToken: 'test-id-token', accessToken: 'test-access-token' } beforeEach(() => { // mocked(oauth2.fetchAuthDetails).mockClear() }) describe('when both a setupId and authId were provided', () => { const setupParams = { authType: EAuthType.OAuth2 } it('uses the oauth2 strategy to fetch the auth details', async () => { // mocked(oauth2.fetchAuthDetails).mockResolvedValueOnce(authDetails) const test = setup(setupParams) await test.get().expect(200) expect(test.req.auth).toEqual(authDetails) }) }) describe('when NO setupId was provided', () => { const setupParams = { authType: EAuthType.OAuth2, withSetupId: false } it('uses the oauth2 strategy to fetch the auth details', async () => { // mocked(oauth2.fetchAuthDetails).mockResolvedValueOnce(authDetails) const test = setup(setupParams) await test.get().expect(200) expect(test.req.auth).toEqual(authDetails) }) }) describe('when NO authId was provided', () => { const setupParams = { authType: EAuthType.OAuth2, withAuthId: false } it('raises a MissingAuthId error ', async () => { const test = setup(setupParams) await test.get().expect(401) expect(test.err).toMatchInlineSnapshot(` [MissingAuthId: You must supply an authId to use the 'test-alias' API Please try again with a valid authId. See the following link for information on how to obtain an authId: https://docs.bearer.sh/faq/connect-button] `) }) }) }) describe('when the authType is any other value', () => { it('raises an InvalidAuthType error', async () => { const test = setup({ authType: 'invalid' }) await test.get().expect(422) await expect(test.err).toMatchSnapshot() }) }) }) it('returns null credentials when it encounters a MissingAuthId error', async () => { // mocked(oauth2.fetchAuthDetails).mockRejectedValueOnce(new MissingAuthId('test-alias')) // const test = setup() // await test.get().expect(200) // expect(test.req.auth).toEqual(oauth2.nullAuthDetails) // expect(log.mock.calls.map(v => v[0])).toContain( // 'Warning: Using null credentials as no authId parameter was specified' // ) }) it('returns null credentials when it encounters a CredentialsNotConfigured error', async () => { // mocked(oauth2.fetchAuthDetails).mockRejectedValueOnce(new CredentialsNotConfigured('test-alias')) // const test = setup() // await test.get().expect(200) // expect(test.req.auth).toEqual(oauth2.nullAuthDetails) // expect(log.mock.calls.map(v => v[0])).toContain('Warning: Using null credentials as no setupId was specified') }) it('returns null credentials when it encounters a InvalidAuthId error', async () => { // mocked(oauth2.fetchAuthDetails).mockRejectedValueOnce(new InvalidAuthId('test-alias', 'test-auth-id')) // const test = setup() // await test.get().expect(200) // expect(test.req.auth).toEqual(oauth2.nullAuthDetails) // expect(log.mock.calls.map(v => v[0])).toContain( // 'Warning: Using null credentials as authId is not authorized for this integration' // ) }) it('fetches the auth details otherwise', async () => { // mocked(oauth2.fetchAuthDetails).mockResolvedValueOnce(authDetails) // const test = setup() // await test.get().expect(200) // expect(test.req.auth).toEqual(authDetails) }) })
the_stack
module BABYLON { class FocusScopeData { constructor(focusScope: UIElement) { this.focusScope = focusScope; this.focusedElement = null; } focusScope: UIElement; focusedElement: UIElement; } export class FocusManager { constructor() { this._focusScopes = new StringDictionary<FocusScopeData>(); this._rootScope = new FocusScopeData(null); this._activeScope = null; } public setFocusOn(el: UIElement, focusScope: UIElement) { let fsd = (focusScope != null) ? this._focusScopes.getOrAddWithFactory(focusScope.uid, k => new FocusScopeData(focusScope)) : this._rootScope; if (fsd.focusedElement !== el) { // Remove focus from current if (fsd.focusedElement) { fsd.focusedElement.isFocused = false; } fsd.focusedElement = el; } if (this._activeScope !== fsd) { this._activeScope = fsd; } } private _rootScope: FocusScopeData; private _focusScopes: StringDictionary<FocusScopeData>; private _activeScope: FocusScopeData; } class GUISceneData { constructor(scene: Scene) { this.scene = scene; this.screenSpaceCanvas = new ScreenSpaceCanvas2D(scene, { id: "GUI Canvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE }); this.focusManager = new FocusManager(); } screenSpaceCanvas: ScreenSpaceCanvas2D; scene: Scene; focusManager: FocusManager; } @className("Window", "BABYLON") export class Window extends ContentControl { static WINDOW_PROPCOUNT = ContentControl.CONTENTCONTROL_PROPCOUNT + 4; static leftProperty: Prim2DPropInfo; static bottomProperty: Prim2DPropInfo; static positionProperty: Prim2DPropInfo; static isActiveProperty: Prim2DPropInfo; constructor(scene: Scene, settings?: { id ?: string, templateName ?: string, styleName ?: string, content ?: any, left ?: number, bottom ?: number, minWidth ?: number, minHeight ?: number, maxWidth ?: number, maxHeight ?: number, width ?: number, height ?: number, worldPosition ?: Vector3, worldRotation ?: Quaternion, marginTop ?: number | string, marginLeft ?: number | string, marginRight ?: number | string, marginBottom ?: number | string, margin ?: number | string, marginHAlignment ?: number, marginVAlignment ?: number, marginAlignment ?: string, paddingTop ?: number | string, paddingLeft ?: number | string, paddingRight ?: number | string, paddingBottom ?: number | string, padding ?: string, paddingHAlignment?: number, paddingVAlignment?: number, paddingAlignment ?: string, }) { if (!settings) { settings = {}; } super(settings); // Per default a Window is focus scope this.isFocusScope = true; this.isActive = false; if (!this._UIElementVisualToBuildList) { this._UIElementVisualToBuildList = new Array<UIElement>(); } // Patch the owner and also the parent property through the whole tree this._patchUIElement(this, null); // Screen Space UI if (!settings.worldPosition && !settings.worldRotation) { this._sceneData = Window.getSceneData(scene); this._canvas = this._sceneData.screenSpaceCanvas; this._isWorldSpaceCanvas = false; this._left = (settings.left != null) ? settings.left : 0; this._bottom = (settings.bottom != null) ? settings.bottom : 0; } // WorldSpace UI else { let w = (settings.width == null) ? 100 : settings.width; let h = (settings.height == null) ? 100 : settings.height; let wpos = (settings.worldPosition == null) ? Vector3.Zero() : settings.worldPosition; let wrot = (settings.worldRotation == null) ? Quaternion.Identity() : settings.worldRotation; this._canvas = new WorldSpaceCanvas2D(scene, new Size(w, h), { id: "GUI Canvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, worldPosition: wpos, worldRotation: wrot }); this._isWorldSpaceCanvas = true; } this._renderObserver = this._canvas.renderObservable.add((e, s) => this._canvasPreRender(), Canvas2D.RENDEROBSERVABLE_PRE); this._disposeObserver = this._canvas.disposeObservable.add((e, s) => this._canvasDisposed()); this._canvas.propertyChanged.add((e, s) => { if (e.propertyName === "overPrim") { this._overPrimChanged(e.oldValue, e.newValue); } }); this._mouseOverUIElement = null; } public get canvas(): Canvas2D { return this._canvas; } @dependencyProperty(ContentControl.CONTENTCONTROL_PROPCOUNT + 0, pi => Window.leftProperty = pi) public get left(): number { return this._left; } public set left(value: number) { let old = new Vector2(this._left, this._bottom); this._left = value; this.onPropertyChanged("_position", old, this._position); } @dependencyProperty(ContentControl.CONTENTCONTROL_PROPCOUNT + 1, pi => Window.bottomProperty = pi) public get bottom(): number { return this._bottom; } public set bottom(value: number) { let old = new Vector2(this._left, this._bottom); this._bottom = value; this.onPropertyChanged("_position", old, this._position); } @dependencyProperty(ContentControl.CONTENTCONTROL_PROPCOUNT + 2, pi => Window.positionProperty = pi) public get position(): Vector2 { return this._position; } public set position(value: Vector2) { this._left = value.x; this._bottom = value.y; } @dependencyProperty(ContentControl.CONTENTCONTROL_PROPCOUNT + 3, pi => Window.isActiveProperty = pi) public get isActive(): boolean { return this._isActive; } public set isActive(value: boolean) { this._isActive = value; } public get focusManager(): FocusManager { return this._sceneData.focusManager; } protected get _position(): Vector2 { return new Vector2(this.left, this.bottom); } protected createVisualTree() { super.createVisualTree(); let p = this._visualPlaceholder; p.createSimpleDataBinding(Group2D.positionProperty, "position"); } public _registerVisualToBuild(uiel: UIElement) { if (uiel._isFlagSet(UIElement.flagVisualToBuild)) { return; } if (!this._UIElementVisualToBuildList) { this._UIElementVisualToBuildList = new Array<UIElement>(); } this._UIElementVisualToBuildList.push(uiel); uiel._setFlags(UIElement.flagVisualToBuild); } private _overPrimChanged(oldPrim: Prim2DBase, newPrim: Prim2DBase) { let curOverEl = this._mouseOverUIElement; let newOverEl: UIElement = null; let curGroup = newPrim ? newPrim.traverseUp(p => p instanceof Group2D) : null; while (curGroup) { let uiel = curGroup.getExternalData<UIElement>("_GUIOwnerElement_"); if (uiel) { newOverEl = uiel; break; } curGroup = curGroup.parent ? curGroup.parent.traverseUp(p => p instanceof Group2D) : null; } if (curOverEl === newOverEl) { return; } if (curOverEl) { curOverEl.isMouseOver = false; } if (newOverEl) { newOverEl.isMouseOver = true; } this._mouseOverUIElement = newOverEl; } private _canvasPreRender() { // Check if we have visual to create if (this._UIElementVisualToBuildList.length > 0) { // Sort the UI Element to get the highest (so lowest hierarchy depth) in the hierarchy tree first let sortedElementList = this._UIElementVisualToBuildList.sort((a, b) => a.hierarchyDepth - b.hierarchyDepth); for (let el of sortedElementList) { el._createVisualTree(); } this._UIElementVisualToBuildList.splice(0); } } private _canvasDisposed() { this._canvas.disposeObservable.remove(this._disposeObserver); this._canvas.renderObservable.remove(this._renderObserver); } private _sceneData: GUISceneData; private _canvas: Canvas2D; private _left: number; private _bottom: number; private _isActive: boolean; private _isWorldSpaceCanvas: boolean; private _renderObserver: Observer<Canvas2D>; private _disposeObserver: Observer<SmartPropertyBase>; private _UIElementVisualToBuildList: Array<UIElement>; private _mouseOverUIElement: UIElement; private static getSceneData(scene: Scene): GUISceneData { return Window._sceneData.getOrAddWithFactory(scene.uid, k => new GUISceneData(scene)); } private static _sceneData: StringDictionary<GUISceneData> = new StringDictionary<GUISceneData>(); } @registerWindowRenderingTemplate("BABYLON.Window", "Default", () => new DefaultWindowRenderingTemplate ()) export class DefaultWindowRenderingTemplate extends UIElementRenderingTemplateBase { createVisualTree(owner: UIElement, visualPlaceholder: Group2D): { root: Prim2DBase; contentPlaceholder: Prim2DBase } { let r = new Rectangle2D({ parent: visualPlaceholder, fill: "#808080FF" }); return { root: r, contentPlaceholder: r }; } } }
the_stack
import { expect } from "chai"; import "mocha"; import { range, Subject } from "rxjs"; import { skip, take } from "rxjs/operators"; import { Reducer, Store } from "../src/index"; import { ExampleState, GenericState, RootState, SliceState } from "./test_common_types"; describe("initial state setting", () => { class Foo {} let store: Store<RootState>; let genericStore: Store<GenericState>; let genericAction: Subject<any>; const genericReducer: Reducer<GenericState, any> = (state, payload) => ({ ...state, value: payload }); beforeEach(() => { store = Store.create<RootState>(); genericStore = Store.create(); genericAction = new Subject<any>(); genericStore.addReducer(genericAction, genericReducer); }); // justification: Slices can have any type like "number" etc., so makes no sense to initialize with {} it("should accept an initial state of undefined and create and empty object as initial root state", done => { const store = Store.create<object>(); store .select() .pipe(take(1)) .subscribe(state => { expect(state).to.be.an("Object"); expect(Object.getOwnPropertyNames(state)).to.have.lengthOf(0); done(); }); }); it("should set the initial state and have it available as currentState immediately", () => { const initialState = {} const store = Store.create(initialState); expect(store.currentState).to.equal(initialState) }) it("should accept an initial state of undefined and use undefined as initial state", done => { const sliceStore = store.createSlice("slice", undefined); sliceStore .select() .pipe(take(1)) .subscribe(initialState => { expect(initialState).to.be.undefined; done(); }); }); it("should accept an initial state object when creating a slice", () => { const sliceStore = store.createSlice("slice", { foo: "bar" }); sliceStore .select() .pipe(take(1)) .subscribe(slice => { expect(slice).to.be.an("Object"); expect(Object.getOwnPropertyNames(slice)).to.deep.equal(["foo"]); expect(slice!.foo).to.equal("bar"); }); }); it("should set the initial state for a slice-of-a-slice on the sliced state", done => { const sliceStore = store.createSlice("slice", { foo: "bar" }) as Store<SliceState>; store .select(s => s) .pipe(skip(1)) .subscribe(s => { if (!s.slice || !s.slice.slice) { done("Error"); return; } expect(s.slice.slice.foo).to.equal("baz"); expect(Object.getOwnPropertyNames(s.slice)).to.deep.equal(["foo", "slice"]); expect(Object.getOwnPropertyNames(s.slice.slice)).to.deep.equal(["foo"]); done(); }); sliceStore.createSlice("slice", { foo: "baz" }); }); it("should not allow non-plain objects for the root store creation as initialState", () => { expect(() => Store.create(new Foo())).to.throw(); }); it("should not allow non-plain objects for the slice store as initialState", () => { expect(() => genericStore.createSlice("value", new Foo())).to.throw(); }); it("should not allow non-plain objects for the slice store as cleanupState", () => { // we have to trick TypeScript compiler for this test expect(() => genericStore.createSlice("value", undefined, <SliceState>new Foo())).to.throw(); }); it("should allow primitive types, plain object and array as initial state for root store creation", () => { expect(() => Store.create(null)).not.to.throw(); expect(() => Store.create(undefined)).not.to.throw(); expect(() => Store.create("foobar")).not.to.throw(); expect(() => Store.create(5)).not.to.throw(); expect(() => Store.create(false)).not.to.throw(); expect(() => Store.create({})).not.to.throw(); expect(() => Store.create([])).not.to.throw(); expect(() => Store.create(Symbol())).not.to.throw(); }); it("should allow primitive types, plain object and array as initial state for slice store creation", () => { expect(() => genericStore.createSlice("value", null)).not.to.throw(); expect(() => genericStore.createSlice("value", undefined)).not.to.throw(); expect(() => genericStore.createSlice("value", "foobar")).not.to.throw(); expect(() => genericStore.createSlice("value", 5)).not.to.throw(); expect(() => genericStore.createSlice("value", false)).not.to.throw(); expect(() => genericStore.createSlice("value", {})).not.to.throw(); expect(() => genericStore.createSlice("value", [])).not.to.throw(); expect(() => genericStore.createSlice("value", Symbol())).not.to.throw(); }); it("should allow primitive types, plain object and array as cleanup state for slice store creation", () => { expect(() => genericStore.createSlice("value", undefined, null)).not.to.throw(); expect(() => genericStore.createSlice("value", undefined, undefined)).not.to.throw(); expect(() => genericStore.createSlice("value", undefined, "foobar")).not.to.throw(); expect(() => genericStore.createSlice("value", undefined, 5)).not.to.throw(); expect(() => genericStore.createSlice("value", undefined, false)).not.to.throw(); expect(() => genericStore.createSlice("value", undefined, {})).not.to.throw(); expect(() => genericStore.createSlice("value", undefined, [])).not.to.throw(); expect(() => genericStore.createSlice("value", undefined, Symbol())).not.to.throw(); }); it("does not clone the initialState object when creating the root store, so changes to it will be reflected in our root store", done => { const initialState: ExampleState = { counter: 0, }; const store = Store.create(initialState); const counterAction = new Subject<number>(); const counterReducer: Reducer<ExampleState, number> = (state, payload = 1) => { // WARNING this is not immutable and should not be done in production code // we just do it here for the test... state.counter++; return state; }; store.addReducer(counterAction, counterReducer); counterAction.next(); // verify currentState (=synchronous state access) works, too expect(store.currentState.counter).to.equal(1) store.select().subscribe(s => { expect(initialState.counter).to.equal(1); done(); }); }); it("should not create an immutable copy of the initialState object when creating a slice store, so changes to it will be noticed outside the slice", done => { const initialState: ExampleState = { counter: 0, }; const store = Store.create(initialState); const counterAction = new Subject<number>(); const counterReducer: Reducer<number, number> = (state, payload = 1) => state + payload; const slice = store.createSlice("counter"); slice.addReducer(counterAction, counterReducer); counterAction.next(); slice .select() .pipe(take(2)) .subscribe(s => { expect(initialState.counter).to.equal(1); done(); }); }); it("should be possible to create a lot of nested slices", done => { const nestingLevel = 100; const rootStore = Store.create<SliceState>({ foo: "0", slice: undefined }); let currentStore: Store<SliceState> = rootStore; range(1, nestingLevel).subscribe( n => { const nestedStore = currentStore.createSlice("slice", { foo: n.toString() }); nestedStore .select() .pipe(take(1)) .subscribe(state => { expect(state!.foo).to.equal(n.toString()); }); currentStore = nestedStore as Store<SliceState>; }, undefined, done, ); }); it("should trigger a state change on the root store when the initial state on the slice is created", done => { store .select(s => s) .pipe( skip(1), take(1), ) .subscribe(state => { expect(state.slice).not.to.be.undefined; expect(state.slice).to.have.property("foo"); if (state.slice) { expect(state.slice.foo).to.equal("bar"); done(); } }); store.createSlice("slice", { foo: "bar" }); }); it("should overwrite an initial state on the slice if the slice key already has a value", done => { const sliceStore = store.createSlice("slice", { foo: "bar" }); sliceStore.destroy(); const sliceStore2 = store.createSlice("slice", { foo: "different" }); sliceStore2.select().subscribe(state => { expect(state!.foo).to.equal("different"); done(); }); }); it("should set the state to the cleanup value undefined but keep the property on the object, when the slice store is destroyed for case 'undefined'", done => { const sliceStore = store.createSlice("slice", { foo: "bar" }, "undefined"); sliceStore.destroy(); store.select().subscribe(state => { expect(state.hasOwnProperty("slice")).to.equal(true); expect(state.slice).to.be.undefined; done(); }); }); it("should remove the slice property on parent state altogether when the slice store is destroyed for case 'delete'", done => { const sliceStore = store.createSlice("slice", { foo: "bar" }, "delete"); sliceStore.destroy(); store.select().subscribe(state => { expect(state.hasOwnProperty("slice")).to.equal(false); expect(Object.getOwnPropertyNames(state)).to.deep.equal([]); done(); }); }); it("should set the state to the cleanup value when the slice store is unsubscribed for case null", done => { const sliceStore = store.createSlice("slice", { foo: "bar" }, null); sliceStore.destroy(); store.select().subscribe(state => { expect(state.slice).to.be.null; done(); }); }); it("should set the state to the cleanup value when the slice store is unsubscribed for case any object", done => { const sliceStore = store.createSlice("slice", { foo: "bar" }, { foo: "baz" }); sliceStore.destroy(); store.select().subscribe(state => { expect(state.slice).to.be.deep.equal({ foo: "baz" }); done(); }); }); });
the_stack
import * as tar from "tar-stream"; import * as path from "path"; import * as fs from "fs"; import * as zlib from "zlib"; import * as bunzip2 from "unbzip2-stream"; import { ArchiveCommon } from "./ArchiveCommon"; import { File, FileLink } from "../../common/File"; import { ProgressFunc, ProgressResult } from "../../common/Reader"; import { Logger } from "../../common/Logger"; import { Transform, Readable } from "stream"; import { convertAttrToStatMode } from "../FileReader"; const log = Logger("archivetar"); export class ArchiveTarGz extends ArchiveCommon { protected isSupportType( file: File ): string { let supportType = null; const name = file.name; if ( name.match( /(\.tar\.gz$|\.tgz$)/ ) ) { supportType = "tgz"; } else if ( name.match( /(\.tar\.bz2$|\.tar\.bz$|\.tbz2$|\.tbz$)/ ) ) { supportType = "tbz2"; } else if ( name.match( /(\.tar$)/ ) ) { supportType = "tar"; } else if ( name.match( /\.gz$/ ) ) { supportType = "gz"; } else if ( name.match( /.bz$/ )) { supportType = "bz2"; } else if ( name.match( /(\.tar\.xz$|\.txz$)/ )) { supportType = "txz"; } else if ( name.match( /.xz$/ )) { supportType = "xz"; } return supportType; } getArchivedFiles(progress?: ProgressFunc): Promise<File[]> { return new Promise( (resolve, reject) => { if ( this.supportType === "gz" || this.supportType === "xz" ) { const file = this.originalFile.clone(); file.fstype = "archive"; file.name = file.name.substr(file.name.length - 3); file.fullname = file.fullname.substr(file.fullname.length - 3); resolve( [file] ); return; } let resultFiles = []; const file = this.originalFile; let stream: any = fs.createReadStream(file.fullname); let chunkSum = 0; const reportProgress = new Transform({ transform(chunk: Buffer, encoding, callback) { chunkSum += chunk.length; progress && progress( file, chunkSum, file.size, chunk.length ); log.debug( "Transform: %s => %d / %d", file.fullname, chunkSum, file.size ); callback( null, chunk ); } }); stream = stream.pipe( reportProgress ); let outstream: any = null; const extract = tar.extract(); extract.on("entry", (header, stream, next) => { resultFiles.push(this.convertTarToFile(header)); stream.resume(); next(); }); stream.on("error", (error) => { log.error( error ); reject(error); }); if ( this.supportType === "tgz" ) { outstream = stream.pipe(zlib.createGunzip()); } else if ( this.supportType === "tbz2" ) { outstream = stream.pipe(bunzip2()); } else if ( this.supportType === "txz" ) { try { // eslint-disable-next-line @typescript-eslint/no-var-requires const lzma = require("lzma-native"); outstream = stream.pipe(lzma.createDecompressor()); } catch( e ) { reject( "unsupport xz file" ); return; } } else { outstream = stream; } outstream = outstream.pipe( extract ); outstream.on("error", (error) => { log.error( error ); reject(error); }).on("finish", () => { log.info( "finish : [%d]", resultFiles.length ); resultFiles = this.subDirectoryCheck( resultFiles ); log.info( "finish 2 : [%d]", resultFiles.length ); resolve( resultFiles ); }); }); } uncompress( extractDir: File, files?: File[], progress?: ProgressFunc ): Promise<void> { return new Promise((resolve, reject) => { const extractFiles = []; const file = this.originalFile; const tarStream: any = fs.createReadStream(file.fullname); const filesBaseDir = files && files.length > 0 ? files[0].dirname : ""; let outstream: any = null; const extract = tar.extract(); extract.on("entry", (header, stream, next: any) => { const tarFileInfo = this.convertTarToFile(header); if ( files ) { if ( !files.find( item => tarFileInfo.fullname === item.fullname ) ) { stream.resume(); next(); return; } } let chunkSum = 0; const reportProgress = new Transform({ transform(chunk: Buffer, encoding, callback) { chunkSum += chunk.length; if ( progress ) { const result = progress( tarFileInfo, chunkSum, tarFileInfo.size, chunk.length ); if ( result === ProgressResult.USER_CANCELED ) { extract.destroy(); reject("USER_CANCEL"); return; } } // log.debug( "Transform: %s => %d / %d", tarFileInfo.fullname, chunkSum, file.size ); callback( null, chunk ); } }); this.fileStreamWrite( extractDir, filesBaseDir, tarFileInfo, stream, reportProgress, (status: string, err) => { next(err); }); extractFiles.push( tarFileInfo ); }); try { if ( this.supportType === "tgz" ) { const gunzip = zlib.createGunzip(); gunzip.on("error", (error) => { log.error( "ERROR [%s]", error ); extract.destroy(); reject(error); }); outstream = tarStream.pipe(gunzip); } else if ( this.supportType === "tbz2" ) { outstream = tarStream.pipe(bunzip2()); } else if ( this.supportType === "txz" ) { try { // eslint-disable-next-line @typescript-eslint/no-var-requires const lzma = require("lzma-native"); outstream = tarStream.pipe(lzma.createDecompressor()); } catch( e ) { log.error( "ERROR [%s]", e ); extract.destroy(); reject( e ); return; } } else { outstream = tarStream; } outstream = outstream.pipe( extract ); outstream.on("error", (error) => { log.error( "ERROR [%s]", error ); extract.destroy(); reject(error); }).on("finish", () => { log.info( "finish : [%d]", extractFiles.length ); resolve(); }); } catch( err ) { log.error( "ERROR [%s]", err ); extract.destroy(); reject(err); } }); } protected commonCompress( writeTarStream: fs.WriteStream, packFunc: (pack: tar.Pack) => Promise<void>, _progress?: ProgressFunc ): Promise<void> { const pack = tar.pack(); return new Promise( async (resolve, reject) => { if ( this.supportType === "tbz2" ) { reject("Unsupport bzip2 compress !!!"); return; } try { let outstream = null; writeTarStream.on("error", (error) => { log.error( "ERROR [%s]", error ); pack.destroy(); reject(error); }); if ( this.supportType === "tgz" ) { const gzip = zlib.createGzip(); gzip.on("error", (error) => { log.error( "ERROR [%s]", error ); pack.destroy(error); writeTarStream.close(); reject(error); }); outstream = pack.pipe(gzip).pipe(writeTarStream); } else if ( this.supportType === "txz" ) { try { // eslint-disable-next-line @typescript-eslint/no-var-requires const lzma = require("lzma-native"); const xz = lzma.createCompressor(); xz.on("error", (error) => { log.error( "ERROR [%s]", error ); pack.destroy(error); writeTarStream.close(); reject(error); }); outstream = pack.pipe(xz).pipe(writeTarStream); } catch( e ) { log.error( "ERROR [%s]", e ); reject( e ); return; } } else { outstream = pack.pipe(writeTarStream); } outstream.on("error", (error) => { log.error( "ERROR [%s]", error ); pack.destroy(); writeTarStream.close(); reject(error); }).on("finish", () => { log.info( "Compress Finish !!!" ); writeTarStream.close(); resolve(); }); await packFunc( pack ); pack.finalize(); } catch ( err ) { pack.destroy( err ); reject( err ); } }); } protected originalPacking( pack: tar.Pack, filterEntryFunc: (tarFileInfo: File, header) => boolean, progress?: ProgressFunc ): Promise<void> { return new Promise( (resolve, reject) => { const tarStream: any = fs.createReadStream(this.originalFile.fullname); const extract = tar.extract(); extract.on("entry", (header, stream, next: any) => { const tarFileInfo = this.convertTarToFile(header); if ( filterEntryFunc && !filterEntryFunc( tarFileInfo, header ) ) { stream.on("end", function() { next(); }); stream.resume(); return; } let chunkSum = 0; const reportProgress = new Transform({ transform(chunk: Buffer, encoding, callback) { chunkSum += chunk.length; if ( progress ) { const result = progress( tarFileInfo, chunkSum, tarFileInfo.size, chunk.length ); if ( result === ProgressResult.USER_CANCELED ) { extract.destroy(); reject("USER_CANCEL"); return; } } // log.debug( "Transform: %s => %d / %d", tarFileInfo.fullname, chunkSum, file.size ); callback( null, chunk ); } }); this.packEntry(tarFileInfo, header, stream, pack, reportProgress).then( () => { next(); }).catch( (error) => { reject(error); }); }); let outstream = null; if ( this.supportType === "tgz" ) { outstream = tarStream.pipe(zlib.createGunzip()); } else if ( this.supportType === "tbz2" ) { outstream = tarStream.pipe(bunzip2()); } else if ( this.supportType === "txz" ) { try { // eslint-disable-next-line @typescript-eslint/no-var-requires const lzma = require("lzma-native"); outstream = tarStream.pipe(lzma.createDecompressor()); } catch( e ) { log.error( "ERROR [%s]", e ); extract.destroy(); reject( e ); return; } } else { outstream = tarStream; } outstream = outstream.pipe( extract ); outstream.on("error", (error) => { log.error( "ERROR [%s]", error ); extract.destroy(); reject(error); }).on("finish", () => { log.info( "originalFileLoader finish !!" ); resolve(); }); }); } protected packEntry(file: File, header, stream: Readable, pack, reportProgress?: Transform): Promise<void> { return new Promise( (resolve, reject) => { if ( file.dir || file.link ) { log.debug( "Insert Directory : [%s] [%s]", file.fullname, header.name ); pack.entry( header, (err) => err ? reject(err) : resolve()); } else { const entry = pack.entry( header, (err) => { log.debug( "Insert File : [%s] [%s]", file.fullname, header.name ); if ( err ) { reject(err); } else { resolve(); } }); stream.on( "error", (err) => { entry.destroy(err); }); if ( reportProgress ) { stream.pipe(reportProgress).pipe( entry ); } else { stream.pipe( entry ); } } }); } private convertAttr( stats: tar.Headers ): string { const fileMode: string[] = "----------".split(""); fileMode[0] = stats.type === "block-device" ? "b" : fileMode[0]; fileMode[0] = stats.type === "character-device" ? "c" : fileMode[0]; fileMode[0] = stats.type === "fifo" ? "p" : fileMode[0]; fileMode[0] = stats.type === "directory" ? "d" : fileMode[0]; fileMode[0] = stats.type === "link" ? "l" : fileMode[0]; fileMode[1] = stats.mode & fs.constants.S_IRUSR ? "r" : "-"; fileMode[2] = stats.mode & fs.constants.S_IWUSR ? "w" : "-"; fileMode[3] = stats.mode & fs.constants.S_IXUSR ? "x" : "-"; fileMode[4] = stats.mode & fs.constants.S_IRGRP ? "r" : "-"; fileMode[5] = stats.mode & fs.constants.S_IWGRP ? "w" : "-"; fileMode[6] = stats.mode & fs.constants.S_IXGRP ? "x" : "-"; fileMode[7] = stats.mode & fs.constants.S_IROTH ? "r" : "-"; fileMode[8] = stats.mode & fs.constants.S_IWOTH ? "w" : "-"; fileMode[9] = stats.mode & fs.constants.S_IXOTH ? "x" : "-"; return fileMode.join(""); } private convertTarToFile(header: tar.Headers): File { const file = new File(); file.fstype = "archive"; file.fullname = header.name[0] !== path.posix.sep ? path.posix.sep + header.name : header.name; file.orgname = header.name; file.name = path.basename(file.fullname); file.owner = header.uname; if ( header.linkname ) { file.link = new FileLink( header.linkname, null ); } file.uid = header.uid; file.gid = header.gid; file.group = header.gname; file.mtime = header.mtime; file.root = this.originalFile.fullname; file.attr = this.convertAttr(header); file.size = header.size; file.dir = file.attr[0] === "d"; return file; } protected convertFileToHeader(file: File, srcBaseDir: File, targetDir: string): tar.Headers { const header: tar.Headers = { name: file.orgname, mode: convertAttrToStatMode(file), mtime: file.mtime, size: file.size, type: file.dir ? "directory": "file", uid: file.uid, gid: file.gid }; if ( file.fstype === "file" ) { let orgFilename = file.fullname.substr(srcBaseDir.fullname.length); orgFilename = orgFilename.split(path.sep).join(path.posix.sep); header.name = path.posix.normalize(targetDir + orgFilename).replace( /^\//, ""); } if ( file.link ) { header.linkname = file.link.name; header.type = "symlink"; header.size = 0; } return header; } }
the_stack
import { expect } from 'chai'; import * as http from 'http'; import * as qs from 'querystring'; import * as path from 'path'; import * as url from 'url'; import * as WebSocket from 'ws'; import { ipcMain, protocol, session, WebContents, webContents } from 'electron/main'; import { AddressInfo } from 'net'; import { emittedOnce } from './events-helpers'; const fixturesPath = path.resolve(__dirname, 'fixtures'); describe('webRequest module', () => { const ses = session.defaultSession; const server = http.createServer((req, res) => { if (req.url === '/serverRedirect') { res.statusCode = 301; res.setHeader('Location', 'http://' + req.rawHeaders[1]); res.end(); } else if (req.url === '/contentDisposition') { res.setHeader('content-disposition', [' attachment; filename=aa%E4%B8%ADaa.txt']); const content = req.url; res.end(content); } else { res.setHeader('Custom', ['Header']); let content = req.url; if (req.headers.accept === '*/*;test/header') { content += 'header/received'; } if (req.headers.origin === 'http://new-origin') { content += 'new/origin'; } res.end(content); } }); let defaultURL: string; before((done) => { protocol.registerStringProtocol('neworigin', (req, cb) => cb('')); server.listen(0, '127.0.0.1', () => { const port = (server.address() as AddressInfo).port; defaultURL = `http://127.0.0.1:${port}/`; done(); }); }); after(() => { server.close(); protocol.unregisterProtocol('neworigin'); }); let contents: WebContents = null as unknown as WebContents; // NB. sandbox: true is used because it makes navigations much (~8x) faster. before(async () => { contents = (webContents as any).create({ sandbox: true }); await contents.loadFile(path.join(fixturesPath, 'pages', 'jquery.html')); }); after(() => (contents as any).destroy()); async function ajax (url: string, options = {}) { return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`); } describe('webRequest.onBeforeRequest', () => { afterEach(() => { ses.webRequest.onBeforeRequest(null); }); it('can cancel the request', async () => { ses.webRequest.onBeforeRequest((details, callback) => { callback({ cancel: true }); }); await expect(ajax(defaultURL)).to.eventually.be.rejectedWith('404'); }); it('can filter URLs', async () => { const filter = { urls: [defaultURL + 'filter/*'] }; ses.webRequest.onBeforeRequest(filter, (details, callback) => { callback({ cancel: true }); }); const { data } = await ajax(`${defaultURL}nofilter/test`); expect(data).to.equal('/nofilter/test'); await expect(ajax(`${defaultURL}filter/test`)).to.eventually.be.rejectedWith('404'); }); it('receives details object', async () => { ses.webRequest.onBeforeRequest((details, callback) => { expect(details.id).to.be.a('number'); expect(details.timestamp).to.be.a('number'); expect(details.webContentsId).to.be.a('number'); expect(details.webContents).to.be.an('object'); expect(details.webContents!.id).to.equal(details.webContentsId); expect(details.frame).to.be.an('object'); expect(details.url).to.be.a('string').that.is.equal(defaultURL); expect(details.method).to.be.a('string').that.is.equal('GET'); expect(details.resourceType).to.be.a('string').that.is.equal('xhr'); expect(details.uploadData).to.be.undefined(); callback({}); }); const { data } = await ajax(defaultURL); expect(data).to.equal('/'); }); it('receives post data in details object', async () => { const postData = { name: 'post test', type: 'string' }; ses.webRequest.onBeforeRequest((details, callback) => { expect(details.url).to.equal(defaultURL); expect(details.method).to.equal('POST'); expect(details.uploadData).to.have.lengthOf(1); const data = qs.parse(details.uploadData[0].bytes.toString()); expect(data).to.deep.equal(postData); callback({ cancel: true }); }); await expect(ajax(defaultURL, { type: 'POST', data: postData })).to.eventually.be.rejectedWith('404'); }); it('can redirect the request', async () => { ses.webRequest.onBeforeRequest((details, callback) => { if (details.url === defaultURL) { callback({ redirectURL: `${defaultURL}redirect` }); } else { callback({}); } }); const { data } = await ajax(defaultURL); expect(data).to.equal('/redirect'); }); it('does not crash for redirects', async () => { ses.webRequest.onBeforeRequest((details, callback) => { callback({ cancel: false }); }); await ajax(defaultURL + 'serverRedirect'); await ajax(defaultURL + 'serverRedirect'); }); it('works with file:// protocol', async () => { ses.webRequest.onBeforeRequest((details, callback) => { callback({ cancel: true }); }); const fileURL = url.format({ pathname: path.join(fixturesPath, 'blank.html').replace(/\\/g, '/'), protocol: 'file', slashes: true }); await expect(ajax(fileURL)).to.eventually.be.rejectedWith('404'); }); }); describe('webRequest.onBeforeSendHeaders', () => { afterEach(() => { ses.webRequest.onBeforeSendHeaders(null); ses.webRequest.onSendHeaders(null); }); it('receives details object', async () => { ses.webRequest.onBeforeSendHeaders((details, callback) => { expect(details.requestHeaders).to.be.an('object'); expect(details.requestHeaders['Foo.Bar']).to.equal('baz'); callback({}); }); const { data } = await ajax(defaultURL, { headers: { 'Foo.Bar': 'baz' } }); expect(data).to.equal('/'); }); it('can change the request headers', async () => { ses.webRequest.onBeforeSendHeaders((details, callback) => { const requestHeaders = details.requestHeaders; requestHeaders.Accept = '*/*;test/header'; callback({ requestHeaders: requestHeaders }); }); const { data } = await ajax(defaultURL); expect(data).to.equal('/header/received'); }); it('can change the request headers on a custom protocol redirect', async () => { protocol.registerStringProtocol('custom-scheme', (req, callback) => { if (req.url === 'custom-scheme://fake-host/redirect') { callback({ statusCode: 302, headers: { Location: 'custom-scheme://fake-host' } }); } else { let content = ''; if (req.headers.Accept === '*/*;test/header') { content = 'header-received'; } callback(content); } }); // Note that we need to do navigation every time after a protocol is // registered or unregistered, otherwise the new protocol won't be // recognized by current page when NetworkService is used. await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html')); try { ses.webRequest.onBeforeSendHeaders((details, callback) => { const requestHeaders = details.requestHeaders; requestHeaders.Accept = '*/*;test/header'; callback({ requestHeaders: requestHeaders }); }); const { data } = await ajax('custom-scheme://fake-host/redirect'); expect(data).to.equal('header-received'); } finally { protocol.unregisterProtocol('custom-scheme'); } }); it('can change request origin', async () => { ses.webRequest.onBeforeSendHeaders((details, callback) => { const requestHeaders = details.requestHeaders; requestHeaders.Origin = 'http://new-origin'; callback({ requestHeaders: requestHeaders }); }); const { data } = await ajax(defaultURL); expect(data).to.equal('/new/origin'); }); it('can capture CORS requests', async () => { let called = false; ses.webRequest.onBeforeSendHeaders((details, callback) => { called = true; callback({ requestHeaders: details.requestHeaders }); }); await ajax('neworigin://host'); expect(called).to.be.true(); }); it('resets the whole headers', async () => { const requestHeaders = { Test: 'header' }; ses.webRequest.onBeforeSendHeaders((details, callback) => { callback({ requestHeaders: requestHeaders }); }); ses.webRequest.onSendHeaders((details) => { expect(details.requestHeaders).to.deep.equal(requestHeaders); }); await ajax(defaultURL); }); it('leaves headers unchanged when no requestHeaders in callback', async () => { let originalRequestHeaders: Record<string, string>; ses.webRequest.onBeforeSendHeaders((details, callback) => { originalRequestHeaders = details.requestHeaders; callback({}); }); ses.webRequest.onSendHeaders((details) => { expect(details.requestHeaders).to.deep.equal(originalRequestHeaders); }); await ajax(defaultURL); }); it('works with file:// protocol', async () => { const requestHeaders = { Test: 'header' }; let onSendHeadersCalled = false; ses.webRequest.onBeforeSendHeaders((details, callback) => { callback({ requestHeaders: requestHeaders }); }); ses.webRequest.onSendHeaders((details) => { expect(details.requestHeaders).to.deep.equal(requestHeaders); onSendHeadersCalled = true; }); await ajax(url.format({ pathname: path.join(fixturesPath, 'blank.html').replace(/\\/g, '/'), protocol: 'file', slashes: true })); expect(onSendHeadersCalled).to.be.true(); }); }); describe('webRequest.onSendHeaders', () => { afterEach(() => { ses.webRequest.onSendHeaders(null); }); it('receives details object', async () => { ses.webRequest.onSendHeaders((details) => { expect(details.requestHeaders).to.be.an('object'); }); const { data } = await ajax(defaultURL); expect(data).to.equal('/'); }); }); describe('webRequest.onHeadersReceived', () => { afterEach(() => { ses.webRequest.onHeadersReceived(null); }); it('receives details object', async () => { ses.webRequest.onHeadersReceived((details, callback) => { expect(details.statusLine).to.equal('HTTP/1.1 200 OK'); expect(details.statusCode).to.equal(200); expect(details.responseHeaders!.Custom).to.deep.equal(['Header']); callback({}); }); const { data } = await ajax(defaultURL); expect(data).to.equal('/'); }); it('can change the response header', async () => { ses.webRequest.onHeadersReceived((details, callback) => { const responseHeaders = details.responseHeaders!; responseHeaders.Custom = ['Changed'] as any; callback({ responseHeaders: responseHeaders }); }); const { headers } = await ajax(defaultURL); expect(headers).to.match(/^custom: Changed$/m); }); it('can change response origin', async () => { ses.webRequest.onHeadersReceived((details, callback) => { const responseHeaders = details.responseHeaders!; responseHeaders['access-control-allow-origin'] = ['http://new-origin'] as any; callback({ responseHeaders: responseHeaders }); }); const { headers } = await ajax(defaultURL); expect(headers).to.match(/^access-control-allow-origin: http:\/\/new-origin$/m); }); it('can change headers of CORS responses', async () => { ses.webRequest.onHeadersReceived((details, callback) => { const responseHeaders = details.responseHeaders!; responseHeaders.Custom = ['Changed'] as any; callback({ responseHeaders: responseHeaders }); }); const { headers } = await ajax('neworigin://host'); expect(headers).to.match(/^custom: Changed$/m); }); it('does not change header by default', async () => { ses.webRequest.onHeadersReceived((details, callback) => { callback({}); }); const { data, headers } = await ajax(defaultURL); expect(headers).to.match(/^custom: Header$/m); expect(data).to.equal('/'); }); it('does not change content-disposition header by default', async () => { ses.webRequest.onHeadersReceived((details, callback) => { expect(details.responseHeaders!['content-disposition']).to.deep.equal([' attachment; filename=aa中aa.txt']); callback({}); }); const { data, headers } = await ajax(defaultURL + 'contentDisposition'); expect(headers).to.match(/^content-disposition: attachment; filename=aa%E4%B8%ADaa.txt$/m); expect(data).to.equal('/contentDisposition'); }); it('follows server redirect', async () => { ses.webRequest.onHeadersReceived((details, callback) => { const responseHeaders = details.responseHeaders; callback({ responseHeaders: responseHeaders }); }); const { headers } = await ajax(defaultURL + 'serverRedirect'); expect(headers).to.match(/^custom: Header$/m); }); it('can change the header status', async () => { ses.webRequest.onHeadersReceived((details, callback) => { const responseHeaders = details.responseHeaders; callback({ responseHeaders: responseHeaders, statusLine: 'HTTP/1.1 404 Not Found' }); }); const { headers } = await contents.executeJavaScript(`new Promise((resolve, reject) => { const options = { ...${JSON.stringify({ url: defaultURL })}, success: (data, status, request) => { reject(new Error('expected failure')) }, error: (xhr) => { resolve({ headers: xhr.getAllResponseHeaders() }) } } $.ajax(options) })`); expect(headers).to.match(/^custom: Header$/m); }); }); describe('webRequest.onResponseStarted', () => { afterEach(() => { ses.webRequest.onResponseStarted(null); }); it('receives details object', async () => { ses.webRequest.onResponseStarted((details) => { expect(details.fromCache).to.be.a('boolean'); expect(details.statusLine).to.equal('HTTP/1.1 200 OK'); expect(details.statusCode).to.equal(200); expect(details.responseHeaders!.Custom).to.deep.equal(['Header']); }); const { data, headers } = await ajax(defaultURL); expect(headers).to.match(/^custom: Header$/m); expect(data).to.equal('/'); }); }); describe('webRequest.onBeforeRedirect', () => { afterEach(() => { ses.webRequest.onBeforeRedirect(null); ses.webRequest.onBeforeRequest(null); }); it('receives details object', async () => { const redirectURL = defaultURL + 'redirect'; ses.webRequest.onBeforeRequest((details, callback) => { if (details.url === defaultURL) { callback({ redirectURL: redirectURL }); } else { callback({}); } }); ses.webRequest.onBeforeRedirect((details) => { expect(details.fromCache).to.be.a('boolean'); expect(details.statusLine).to.equal('HTTP/1.1 307 Internal Redirect'); expect(details.statusCode).to.equal(307); expect(details.redirectURL).to.equal(redirectURL); }); const { data } = await ajax(defaultURL); expect(data).to.equal('/redirect'); }); }); describe('webRequest.onCompleted', () => { afterEach(() => { ses.webRequest.onCompleted(null); }); it('receives details object', async () => { ses.webRequest.onCompleted((details) => { expect(details.fromCache).to.be.a('boolean'); expect(details.statusLine).to.equal('HTTP/1.1 200 OK'); expect(details.statusCode).to.equal(200); }); const { data } = await ajax(defaultURL); expect(data).to.equal('/'); }); }); describe('webRequest.onErrorOccurred', () => { afterEach(() => { ses.webRequest.onErrorOccurred(null); ses.webRequest.onBeforeRequest(null); }); it('receives details object', async () => { ses.webRequest.onBeforeRequest((details, callback) => { callback({ cancel: true }); }); ses.webRequest.onErrorOccurred((details) => { expect(details.error).to.equal('net::ERR_BLOCKED_BY_CLIENT'); }); await expect(ajax(defaultURL)).to.eventually.be.rejectedWith('404'); }); }); describe('WebSocket connections', () => { it('can be proxyed', async () => { // Setup server. const reqHeaders : { [key: string] : any } = {}; const server = http.createServer((req, res) => { reqHeaders[req.url!] = req.headers; res.setHeader('foo1', 'bar1'); res.end('ok'); }); const wss = new WebSocket.Server({ noServer: true }); wss.on('connection', function connection (ws) { ws.on('message', function incoming (message) { if (message === 'foo') { ws.send('bar'); } }); }); server.on('upgrade', function upgrade (request, socket, head) { const pathname = require('url').parse(request.url).pathname; if (pathname === '/websocket') { reqHeaders[request.url] = request.headers; wss.handleUpgrade(request, socket, head, function done (ws) { wss.emit('connection', ws, request); }); } }); // Start server. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = String((server.address() as AddressInfo).port); // Use a separate session for testing. const ses = session.fromPartition('WebRequestWebSocket'); // Setup listeners. const receivedHeaders : { [key: string] : any } = {}; ses.webRequest.onBeforeSendHeaders((details, callback) => { details.requestHeaders.foo = 'bar'; callback({ requestHeaders: details.requestHeaders }); }); ses.webRequest.onHeadersReceived((details, callback) => { const pathname = require('url').parse(details.url).pathname; receivedHeaders[pathname] = details.responseHeaders; callback({ cancel: false }); }); ses.webRequest.onResponseStarted((details) => { if (details.url.startsWith('ws://')) { expect(details.responseHeaders!.Connection[0]).be.equal('Upgrade'); } else if (details.url.startsWith('http')) { expect(details.responseHeaders!.foo1[0]).be.equal('bar1'); } }); ses.webRequest.onSendHeaders((details) => { if (details.url.startsWith('ws://')) { expect(details.requestHeaders.foo).be.equal('bar'); expect(details.requestHeaders.Upgrade).be.equal('websocket'); } else if (details.url.startsWith('http')) { expect(details.requestHeaders.foo).be.equal('bar'); } }); ses.webRequest.onCompleted((details) => { if (details.url.startsWith('ws://')) { expect(details.error).be.equal('net::ERR_WS_UPGRADE'); } else if (details.url.startsWith('http')) { expect(details.error).be.equal('net::OK'); } }); const contents = (webContents as any).create({ session: ses, nodeIntegration: true, webSecurity: false, contextIsolation: false }); // Cleanup. after(() => { contents.destroy(); server.close(); ses.webRequest.onBeforeRequest(null); ses.webRequest.onBeforeSendHeaders(null); ses.webRequest.onHeadersReceived(null); ses.webRequest.onResponseStarted(null); ses.webRequest.onSendHeaders(null); ses.webRequest.onCompleted(null); }); contents.loadFile(path.join(fixturesPath, 'api', 'webrequest.html'), { query: { port } }); await emittedOnce(ipcMain, 'websocket-success'); expect(receivedHeaders['/websocket'].Upgrade[0]).to.equal('websocket'); expect(receivedHeaders['/'].foo1[0]).to.equal('bar1'); expect(reqHeaders['/websocket'].foo).to.equal('bar'); expect(reqHeaders['/'].foo).to.equal('bar'); }); }); });
the_stack
import { Arn, Aws, Lazy, Resource, SecretValue, Stack } from '@aws-cdk/core'; import { Construct } from 'constructs'; import { IGroup } from './group'; import { CfnUser, CfnUserToGroupAddition } from './iam.generated'; import { IIdentity } from './identity-base'; import { IManagedPolicy } from './managed-policy'; import { Policy } from './policy'; import { PolicyStatement } from './policy-statement'; import { AddToPrincipalPolicyResult, ArnPrincipal, IPrincipal, PrincipalPolicyFragment } from './principals'; import { AttachedPolicies, undefinedIfEmpty } from './util'; /** * Represents an IAM user * * @see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html */ export interface IUser extends IIdentity { /** * The user's name * @attribute */ readonly userName: string; /** * The user's ARN * @attribute */ readonly userArn: string; /** * Adds this user to a group. */ addToGroup(group: IGroup): void; } /** * Properties for defining an IAM user */ export interface UserProps { /** * Groups to add this user to. You can also use `addToGroup` to add this * user to a group. * * @default - No groups. */ readonly groups?: IGroup[]; /** * A list of managed policies associated with this role. * * You can add managed policies later using * `addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`. * * @default - No managed policies. */ readonly managedPolicies?: IManagedPolicy[]; /** * The path for the user name. For more information about paths, see IAM * Identifiers in the IAM User Guide. * * @default / */ readonly path?: string; /** * AWS supports permissions boundaries for IAM entities (users or roles). * A permissions boundary is an advanced feature for using a managed policy * to set the maximum permissions that an identity-based policy can grant to * an IAM entity. An entity's permissions boundary allows it to perform only * the actions that are allowed by both its identity-based policies and its * permissions boundaries. * * @link https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#cfn-iam-role-permissionsboundary * @link https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html * * @default - No permissions boundary. */ readonly permissionsBoundary?: IManagedPolicy; /** * A name for the IAM user. For valid values, see the UserName parameter for * the CreateUser action in the IAM API Reference. If you don't specify a * name, AWS CloudFormation generates a unique physical ID and uses that ID * for the user name. * * If you specify a name, you cannot perform updates that require * replacement of this resource. You can perform updates that require no or * some interruption. If you must replace the resource, specify a new name. * * If you specify a name, you must specify the CAPABILITY_NAMED_IAM value to * acknowledge your template's capabilities. For more information, see * Acknowledging IAM Resources in AWS CloudFormation Templates. * * @default - Generated by CloudFormation (recommended) */ readonly userName?: string; /** * The password for the user. This is required so the user can access the * AWS Management Console. * * You can use `SecretValue.plainText` to specify a password in plain text or * use `secretsmanager.Secret.fromSecretAttributes` to reference a secret in * Secrets Manager. * * @default - User won't be able to access the management console without a password. */ readonly password?: SecretValue; /** * Specifies whether the user is required to set a new password the next * time the user logs in to the AWS Management Console. * * If this is set to 'true', you must also specify "initialPassword". * * @default false */ readonly passwordResetRequired?: boolean; } /** * Represents a user defined outside of this stack. */ export interface UserAttributes { /** * The ARN of the user. * * Format: arn:<partition>:iam::<account-id>:user/<user-name-with-path> */ readonly userArn: string; } /** * Define a new IAM user */ export class User extends Resource implements IIdentity, IUser { /** * Import an existing user given a username. * * @param scope construct scope * @param id construct id * @param userName the username of the existing user to import */ public static fromUserName(scope: Construct, id: string, userName: string): IUser { const userArn = Stack.of(scope).formatArn({ service: 'iam', region: '', resource: 'user', resourceName: userName, }); return User.fromUserAttributes(scope, id, { userArn }); } /** * Import an existing user given a user ARN. * * If the ARN comes from a Token, the User cannot have a path; if so, any attempt * to reference its username will fail. * * @param scope construct scope * @param id construct id * @param userArn the ARN of an existing user to import */ public static fromUserArn(scope: Construct, id: string, userArn: string): IUser { return User.fromUserAttributes(scope, id, { userArn }); } /** * Import an existing user given user attributes. * * If the ARN comes from a Token, the User cannot have a path; if so, any attempt * to reference its username will fail. * * @param scope construct scope * @param id construct id * @param attrs the attributes of the user to import */ public static fromUserAttributes(scope: Construct, id: string, attrs: UserAttributes): IUser { class Import extends Resource implements IUser { public readonly grantPrincipal: IPrincipal = this; public readonly principalAccount = Aws.ACCOUNT_ID; // Resource name with path can have multiple elements separated by slash. // Therefore, use element after last slash as userName. Happens to work for Tokens since // they don't have a '/' in them. public readonly userName: string = Arn.extractResourceName(attrs.userArn, 'user').split('/').pop()!; public readonly userArn: string = attrs.userArn; public readonly assumeRoleAction: string = 'sts:AssumeRole'; public readonly policyFragment: PrincipalPolicyFragment = new ArnPrincipal(attrs.userArn).policyFragment; private readonly attachedPolicies = new AttachedPolicies(); private defaultPolicy?: Policy; private groupId = 0; public addToPolicy(statement: PolicyStatement): boolean { return this.addToPrincipalPolicy(statement).statementAdded; } public addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult { if (!this.defaultPolicy) { this.defaultPolicy = new Policy(this, 'Policy'); this.defaultPolicy.attachToUser(this); } this.defaultPolicy.addStatements(statement); return { statementAdded: true, policyDependable: this.defaultPolicy }; } public addToGroup(group: IGroup): void { new CfnUserToGroupAddition(Stack.of(group), `${this.userName}Group${this.groupId}`, { groupName: group.groupName, users: [this.userName], }); this.groupId += 1; } public attachInlinePolicy(policy: Policy): void { this.attachedPolicies.attach(policy); policy.attachToUser(this); } public addManagedPolicy(_policy: IManagedPolicy): void { throw new Error('Cannot add managed policy to imported User'); } } return new Import(scope, id); } public readonly grantPrincipal: IPrincipal = this; public readonly principalAccount: string | undefined = this.env.account; public readonly assumeRoleAction: string = 'sts:AssumeRole'; /** * An attribute that represents the user name. * @attribute */ public readonly userName: string; /** * An attribute that represents the user's ARN. * @attribute */ public readonly userArn: string; /** * Returns the permissions boundary attached to this user */ public readonly permissionsBoundary?: IManagedPolicy; public readonly policyFragment: PrincipalPolicyFragment; private readonly groups = new Array<any>(); private readonly managedPolicies = new Array<IManagedPolicy>(); private readonly attachedPolicies = new AttachedPolicies(); private defaultPolicy?: Policy; constructor(scope: Construct, id: string, props: UserProps = {}) { super(scope, id, { physicalName: props.userName, }); this.managedPolicies.push(...props.managedPolicies || []); this.permissionsBoundary = props.permissionsBoundary; const user = new CfnUser(this, 'Resource', { userName: this.physicalName, groups: undefinedIfEmpty(() => this.groups), managedPolicyArns: Lazy.list({ produce: () => this.managedPolicies.map(p => p.managedPolicyArn) }, { omitEmpty: true }), path: props.path, permissionsBoundary: this.permissionsBoundary ? this.permissionsBoundary.managedPolicyArn : undefined, loginProfile: this.parseLoginProfile(props), }); this.userName = this.getResourceNameAttribute(user.ref); this.userArn = this.getResourceArnAttribute(user.attrArn, { region: '', // IAM is global in each partition service: 'iam', resource: 'user', resourceName: this.physicalName, }); this.policyFragment = new ArnPrincipal(this.userArn).policyFragment; if (props.groups) { props.groups.forEach(g => this.addToGroup(g)); } } /** * Adds this user to a group. */ public addToGroup(group: IGroup) { this.groups.push(group.groupName); } /** * Attaches a managed policy to the user. * @param policy The managed policy to attach. */ public addManagedPolicy(policy: IManagedPolicy) { if (this.managedPolicies.find(mp => mp === policy)) { return; } this.managedPolicies.push(policy); } /** * Attaches a policy to this user. */ public attachInlinePolicy(policy: Policy) { this.attachedPolicies.attach(policy); policy.attachToUser(this); } /** * Adds an IAM statement to the default policy. * * @returns true */ public addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult { if (!this.defaultPolicy) { this.defaultPolicy = new Policy(this, 'DefaultPolicy'); this.defaultPolicy.attachToUser(this); } this.defaultPolicy.addStatements(statement); return { statementAdded: true, policyDependable: this.defaultPolicy }; } public addToPolicy(statement: PolicyStatement): boolean { return this.addToPrincipalPolicy(statement).statementAdded; } private parseLoginProfile(props: UserProps): CfnUser.LoginProfileProperty | undefined { if (props.password) { return { password: props.password.toString(), passwordResetRequired: props.passwordResetRequired, }; } if (props.passwordResetRequired) { throw new Error('Cannot set "passwordResetRequired" without specifying "initialPassword"'); } return undefined; // no console access } }
the_stack
declare namespace Magix3 { /** * 配置信息接口 */ interface Config { /** * 默认加载的view */ defaultView?: string /** * 默认路径 */ defaultPath?: string /** * path与view关系映射对象或方法 */ routes?: string | ((this: Config, path: string, loc?: RouterParse) => string) /** * 在routes里找不到匹配时使用的view,比如显示404 */ unmatchView?: string /** * 根view的id */ rootId?: string /** * 项目启动时加载的扩展,这些扩展会在项目初始化之前加载进来 */ exts?: string[] /** * 以try catch执行一些用户重写的核心流程,当出错时,允许开发者通过该配置项进行捕获。注意:您不应该在该方法内再次抛出任何错误 */ error?: (this: void, exception: Error) => void /** * 其它配置项 */ [key: string]: any } /** * url解析部分对象接口 */ interface RouterParseParts { /** * 参数对象 */ readonly params: { readonly [key: string]: string } /** * 路径字符串 */ readonly path: string } /** * url解析接口 */ interface RouterParse { /** * 原始的href */ readonly href: string /** * 原始的query */ readonly srcQuery: string /** * 原始的hash */ readonly srcHash: string /** * srcQuery解析出的对象 */ readonly query: RouterParseParts /** * srcHash解析出的对象 */ readonly hash: RouterParseParts /** * query中的params与hash中的params对象合并出来的新对象 */ readonly params: { readonly [key: string]: string } /** * 根据hash对象中的path和query对象中的path,再根据要求得出的path */ readonly path: string /** * 当前url对应的要渲染的根view */ readonly view: string /** * 从params中获取参数值,当参数不存在时返回空字符串 * @param key key * @param defaultValue 当值不存在时候返回的默认值 */ get<TDefaultValueType = any>(key: string, defaultValue?: TDefaultValueType): string } /** * 差异对象接口 */ interface RouterDiffItem { /** * 旧值 */ readonly from: string /** * 新值 */ readonly to: string } /** * url差异对象接口 */ interface RouterDiff { /** * 是否为应用首次初始化时强制触发的差异比较 */ readonly force: boolean /** * 当路径有变化时,才有path这个对象 */ readonly path?: RouterDiffItem /** * 当渲染的根view有变化时,才有view这个对象 */ readonly view?: RouterDiffItem /** * 都有哪些参数发生变化的对象 */ readonly params: { readonly [key: string]: RouterDiffItem } } /** * view更新器接口 */ interface Updater { /** * 获取设置的数据,当key未传递时,返回整个数据对象 * @param key 设置时的数据key */ get<TReturnType = any>(key?: string): TReturnType /** * 设置数据 * @param data 数据对象,如{a:20,b:30} * @param unchanged 指示哪些数据并没有变化的对象 */ set(data?: { [key: string]: any }, unchanged?: { [key: string]: any }, ): this /** * 通过path获取值,path形如"data.list.2.name"字符串 * @param path 路径 */ //gain<TReturnType>(path: string): TReturnType /** * 检测数据变化,更新界面,放入数据后需要显式调用该方法才可以把数据更新到界面 * @param data 数据对象,如{a:20,b:30} * @param unchanged 指示哪些数据并没有变化的对象 * @param resolve 完成更新后的回调 */ digest(data?: { [key: string]: any }, unchanged?: { [key: string]: any }, resolve?: Function): void /** * 获取当前数据状态的快照,配合altered方法可获得数据是否有变化 */ snapshot(): this /** * 检测数据是否有变动 */ altered(): boolean /** * 得到模板中@符号对应的原始数据 * @param data 数据对象 */ translate(data: object): object /** * 得到模板中@符号对应的原始数据 * @param origin 源字符串 */ parse(origin: string): object } /** * 数据载体接口 */ interface Bag { /** * bag id */ id: string /** * 从bag中获取数据 * @param key 数据key,如果未传递则返回整个数据对象 * @param defaultValue 默认值,如果传递了该参数且从bag中获取到的数据类型如果与defaultValue不一致,则使用defaultValue */ get<TReturnAndDefaultValueType = any>(key?: string, defaultValue?: TReturnAndDefaultValueType): TReturnAndDefaultValueType /** * 设置数据 * @param key 数据key * @param value 数据 */ set(key: string, value: any): void /** * 设置数据 * @param data 包含数据的对象 */ set(data: object): void } /** * Magix.State变化事件接口 */ interface StateChangedEvent extends TriggerEventDescriptor { /** * 包含哪些数据变化的集合对象 */ readonly keys: { readonly [key: string]: 1 } } /** * 事件对象接口 */ interface Event<T = any> { /** * 绑定事件 * @param name 事件名称 * @param fn 事件处理函数 */ on(name: string, fn: (this: T, e?: TriggerEventDescriptor) => void): this /** * 解除事件绑定 * @param name 事件名称 * @param fn 事件处理函数 */ off(name: string, fn?: Function): this /** * 派发事件 * @param name 事件名称 * @param data 事件参数 * @param remove 是否移除所有的事件监听 * @param lastToFirst 是否倒序派发列表中的监听 */ fire(name: string, data?: object, remove?: boolean, lastToFirst?: boolean): this } /** * 状态接口 */ interface State extends Event<State> { /** * 从状态对象中获取数据 * @param key 数据key,如果未传递则返回整个状态对象 */ get<TReturnType = any>(key?: string): TReturnType /** * 设置数据 * @param data 数据对象 * @param unchanged 指示哪些数据并没有变化的对象 */ set(data: object, unchanged?: { [key: string]: any }): this /** * 清理Magix.State中的数据,只能在view的mixins中使用,如 mixins:[Magix.State.clean("a,b")] * @param keys 逗号分割的字符串 */ clean(keys: string): void /** * 检测数据变化,派发changed事件,通过set放入数据后需要显式调用该方法才会派发事件 * @param data 数据对象,如{a:20,b:30} * @param unchanged 指示哪些数据并没有变化的对象 */ digest(data?: object, unchanged?: { [key: string]: any }): void /** * 返回有哪些变化的数据key */ diff(): object /** * 建立数据与key的引用关系 * @param keys 逗号分割的字符串 */ setup(keys: string): void /** * 解除数据与key的引用关系 * @param keys 逗号分割的字符串 */ teardown(keys: string): void /** * State中的数据发生变化时触发 */ onchanged: (this: this, e?: StateChangedEvent) => void } /** * api注册信息接口 */ interface ServiceInterfaceMeta { /** * 缓存时间,以毫秒为单位 */ cache?: number /** * 请求的url地址 */ url?: string /** * 添加的接口元信息名称,需要确保在一个Service中唯一 */ name: string /** * 逗号分割的字符串,用来清除其它接口的缓存,如该接口是一个添加新数据的接口,这个接口调用成功后,应该把所有获取相关数据的缓存接口给清理掉,否则将获取不到新数据 */ cleans?: string | string[] /** * 接口在请求发送前调用,可以在该方法内对数据进行加工处理 */ before?: (this: Bag, bag: Bag) => void /** * 接口在成功请求后,在送到view毅调用该方法,可在该方法对数据进行加工处理 */ after?: (this: Bag, bag: Bag) => void [key: string]: any } /** * 基础触发事件接口 */ interface TriggerEventDescriptor { /** * 事件类型 */ readonly type: string } /** * 路由变化事件接口 */ interface RouterChangeEvent extends TriggerEventDescriptor { /** * 拒绝url改变 */ reject: () => void /** * 接受url改变 */ resolve: () => void /** * 阻止url改变 */ prevent: () => void } /** * 路由变化后事件接口 */ interface RouterChangedEvent extends RouterDiff, TriggerEventDescriptor { } /** * view监听location接口 */ interface ViewObserveLocation { /** * 监听path */ path?: boolean /** * 监听参数 */ params?: string | string[] } /** * 路由对象接口 */ interface Router extends Event<Router> { /** * 解析href的query和hash,默认href为location.href * @param url 待解析的url,如果未指定则使用location.href */ parse(url?: string): RouterParse /** * 当前地址栏中的地址与上一个地址栏中的地址差异对象 */ diff(): RouterDiff /** * 导航到新的地址 * @param path 路径字符串 * @param params 参数对象 * @param replace 是否替换当前的历史记录 * @param silent 是否是静默更新,不触发change事件 */ to(path: string, params?: object, replace?: boolean, silent?: boolean): void /** * 导航到新的地址 * @param params 参数对象 * @param replace 是否替换当前的历史记录 * @param silent 是否是静默更新,不触发change事件 */ to(params: object, empty?: any, replace?: boolean, silent?: boolean): void /** * url即将改变时发生 */ onchange: (this: this, e?: RouterChangeEvent) => void /** * url改变后发生 */ onchanged: (this: this, e?: RouterChangedEvent) => void } /** * 接口服务事件接口 */ interface ServiceEvent extends TriggerEventDescriptor { /** * 数据对象的载体 */ readonly bag: Bag /** * 错误对象,如果有错误发生的话 */ readonly error: object | string | null } /** * 继承对象接口 */ interface ExtendPropertyDescriptor<T> { [key: string]: string | number | undefined | boolean | RegExp | symbol | object | null | ((this: T, ...args: any[]) => any) } /** * 继承方法中的this指向 */ type TExtendPropertyDescriptor<T> = ExtendPropertyDescriptor<T> & ThisType<T>; /** * 继承静态属性 */ interface ExtendStaticPropertyDescriptor { [key: string]: any } /** * 监控url参数接口 */ interface ViewObserveUrl { /** * 监听参数。逗号分割的字符串,或字符串数组 */ params?: string | string[] /** * 是否监听地址的改变 */ path?: boolean } /** * view事件接口 */ interface ViewEvent extends TriggerEventDescriptor { /** * 节点id */ readonly id: string } /** * vframe静态事件接口 */ interface VframeStaticEvent extends TriggerEventDescriptor { /** * vframe对象 */ readonly vframe: VframePrototype } /** * 缓存类 */ interface CachePrototype { /** * 设置缓存的资源 * @param key 缓存资源时使用的key,唯一的key对应唯一的资源 * @param resource 缓存的资源 */ set<TResourceAndReturnType = any>(key: string, resource: TResourceAndReturnType): TResourceAndReturnType /** * 获取缓存的资源,如果不存在则返回undefined * @param key 缓存资源时使用的key */ get<TReturnType = any>(key: string): TReturnType /** * 从缓存对象中删除缓存的资源 * @param key 缓存的资源key */ del<TReturnType = any>(key: string): TReturnType /** * 判断缓存对象中是否包含给定key的缓存资源 * @param key 缓存的资源key */ has(key: string): boolean /** * 遍历缓存对象中的所有资源 * @param callback 回调 * @param options 回调时传递的额外对象 */ each<TResourceType = any, TOptionsType = any>(callback: (resource: TResourceType, options: TOptionsType, cache: this) => void, options?: TOptionsType): void } /** * 缓存类 */ interface Cache { /** * 缓存类 * @param max 最大缓存个数 * @param buffer 缓存区个数,默认5 * @param removedCallback 当缓存的资源被删除时调用 */ new(max?: number, buffer?: number, removedCallback?: (this: void, resource: any) => void): CachePrototype readonly prototype: CachePrototype } /** * 拥有事件on,off,fire的基类原型 */ interface BasePrototype extends Event<BasePrototype> { } /** * 拥有事件on,off,fire的基类 */ interface Base { /** * 初始化 */ new(...args: any[]): BasePrototype /** * 继承Magix.Base * @param props 原型方法或属性的对象 * @param statics 静态方法或属性的对象 */ extend<TProps = object, TStatics = object>(props?: TExtendPropertyDescriptor<TProps & BasePrototype>, statics?: TStatics): this & TStatics /** * 原型 */ readonly prototype: BasePrototype } /** * Vframe类原型 */ interface VframePrototype extends Event<VframePrototype> { /** * vframe所在的节点id */ readonly id: string /** * 渲染的view模块路径,如app/views/default */ readonly path: string /** * 父vframe id,如果没有则为undefined */ readonly pId: string /** * 渲染view * @param viewPath view模块路径,如app/views/default * @param viewInitParams 初始化view时传递的参数,可以在view的init方法中接收 */ mountView(viewPath: string, viewInitParams?: object): void /** * 销毁view */ unmountView(): void /** * 在某个dom节点上渲染vframe * @param id 要渲染的节点id * @param viewPath view路径 * @param viewInitParams 初始化view时传递的参数,可以在view的init方法中接收 */ mountVframe(id: string, viewPath: string, viewInitParams?: object): this /** * 销毁dom节点上渲染的vframe * @param id 节点id,默认当前view */ unmountVframe(id?: string): void /** * 渲染某个节点下的所有子view * @param id 节点id,默认当前view * @param viewInitParams 初始化view时传递的参数,可以在view的init方法中接收 */ mountZone(id?: string, viewInitParams?: object): void /** * 销毁某个节点下的所有子view * @param id 节点id,默认当前view */ unmountZone(id?: string): void /** * 获取祖先vframe * @param level 向上查找层级,默认1级,即父vframe */ parent(level?: number): this | null /** * 获取当前vframe的所有子vframe的id。返回数组中,id在数组中的位置并不固定 */ children(): string[] /** * 调用vframe的view中的方法 * @param name 方法名 * @param args 传递的参数 */ invoke<TReturnType>(name: string, args?: any[]): TReturnType /** * 子孙view创建完成时触发 */ oncreated: (this: this, e?: TriggerEventDescriptor) => void /** * 子孙view修改时触发 */ onalter: (this: this, e?: TriggerEventDescriptor) => void } /** * Vframe类,开发者绝对不需要继承、实例化该类! */ interface Vframe extends Event<Vframe> { /** * 获取当前页面上所有的vframe */ all(): { [key: string]: VframePrototype } /** * 根据id获取vframe * @param id id */ get(id: string): VframePrototype /** * 当vframe创建并添加到管理对象上时触发 */ onadd: (this: this, e?: VframeStaticEvent) => void /** * 当vframe销毁并从管理对象上删除时触发 */ onremove: (this: this, e?: VframeStaticEvent) => void /** * 原型 */ readonly prototype: VframePrototype } interface IncrementDiff { node: HTMLElement, deep: boolean data: boolean html: boolean keys: object } /** * view类原型 */ interface ViewPrototype extends Event<ViewPrototype> { /** * 当前view所在的节点id */ readonly id: string /** * 模板 */ readonly tmpl: string | { html: string subs: object[] } /** * 持有当前view的vframe */ readonly owner: VframePrototype /** * 更新界面对象 */ readonly updater: Updater /** * 混入的当前View类原型链上的其它对象 */ mixins?: ExtendStaticPropertyDescriptor[] /** * 初始化View时调用 * @param extra 初始化时传递的额外参数 */ init(extra?: object): void /** * 渲染界面,开发者在该方法内完成界面渲染的流程 */ render(...args: any[]): void /** * 更新某个节点的html,该方法内部会自动处理相关的子view * @param id 设置html的节点id * @param html 待设置的html */ assign(data: object, options?: IncrementDiff): boolean /** * 监听地址栏的改变,如"/app/path?page=1&size=20",其中"/app/path"为path,"page,size"为参数 * @param parameters 监听地址栏中的参数,如"page,size"或["page","size"]表示监听page或size的改变 * @param observePath 是否监听path的改变 */ observeLocation(parameters: string | string[], observePath?: boolean): void /** * 监听地址栏的改变 * @param observeObject 参数对象 */ observeLocation(observeObject: ViewObserveLocation): void /** * 监听Magix.State中的数据变化 * @param keys 逗号分割的字符串 */ observeState(keys: string): void /** * 通知当前view某个节点即将开始进行html的更新,在该方法内部会派发prerender事件 * @param id 哪块区域需要更新,默认当前view */ beginUpdate(id?: string): void /** * 通知当前view某个节点结束html的更新,在该方法内部会派发rendered事件 * @param id 哪块区域需要更新,默认当前view */ endUpdate(id?: string): void /** * 包装异步回调 * 为什么要包装? * 在单页应用的情况下,一些异步(如setTimeout,ajax等)回调执行时,当前view已经被销毁。如果你的回调中去操作了DOM, * 则会出错,为了避免这种情况的出现,可以调用该方法包装一次,magix会确保你的回调在view未销毁的情况下被调用 * @param callback 回调方法 * @param context 回调方法执行时的this指向 */ wrapAsync<TThisType>(callback: (this: TThisType, ...args: any[]) => void, context?: TThisType): Function /** * 把资源交给当前view托管,当view销毁或重新渲染时自动对托管的资源做处理,即在合适的时候调用资源的destroy方法。返回托管的资源 * @param key 托管资源的key,当要托管的key已经存在时且要托管的资源与之前的不相同时,会自动销毁之前托管的资源 * @param resource 托管的资源 * @param destroyWhenCallRender 当render方法再次调用时,是否自动销毁该资源,通常Magix.Service实例需要在render时自动销毁 */ capture<TResourceAndReturnType extends { destroy: () => void }>(key: string, resource?: TResourceAndReturnType, destroyWhenCallRender?: boolean): TResourceAndReturnType /** * 释放管理的资源。返回托管的资源,无论是否销毁 * @param key 托管资源的key * @param destroy 是否销毁资源,即自动调用资源的destroy方法 */ release<TResourceType extends { destroy: () => void }>(key: string, destroy?: boolean): TResourceType /** * 离开确认方法,需要开发者实现离开的界面和逻辑 * @param resolve 确定离开时调用该方法,通知magix离开 * @param reject 留在当前界面时调用的方法,通知magix不要离开 * @param msg 调用leaveTip时传递的离开消息 */ leaveConfirm(resolve: Function, reject: Function, msg: string): void /** * 离开提醒,比如表单有变化且未保存,我们可以提示用户是直接离开,还是保存后再离开 * @param msg 离开提示消息 * @param hasChanged 是否显示提示消息的方法,返回true表示需要提示用户 */ leaveTip(msg: string, hasChanged: () => boolean): void /** * view销毁时触发 */ ondestroy: (this: this, e?: TriggerEventDescriptor) => void; /** * 当render方法被调用时触发 */ onrendercall: (this: this, e?: TriggerEventDescriptor) => void; } /** * View类 */ interface View { /** * 继承Magix.View * @param props 包含可选的init和render方法的对象 * @param statics 静态方法或属性的对象 */ extend<TProps = object, TStatics = object>(props?: TExtendPropertyDescriptor<TProps & ViewPrototype>, statics?: TStatics): this & TStatics /** * 扩展到Magix.View原型上的对象 * @param props 包含可选的ctor方法的对象 */ merge(...args: TExtendPropertyDescriptor<ViewPrototype>[]): void /** * 原型 */ readonly prototype: ViewPrototype } /** * 接口管理类原型 */ interface ServicePrototype { /** * 所有请求完成回调done * @param metas 接口名称或对象数组 * @param done 全部接口成功时回调 */ all(metas: object[] | string[] | string, done: (this: this, err: any, ...bags: Bag[]) => void): this /** * 所有请求完成回调done,与all不同的是:如果接口指定了缓存,all会走缓存,而save则不会 * @param metas 接口名称或对象数组 * @param done 全部接口成功时回调 */ save(metas: object[] | string[] | string, done: (this: this, err: any, ...bags: Bag[]) => void): this /** * 任意一个成功均立即回调,回调会被调用多次 * @param metas 接口名称或对象数组 * @param done 全部接口成功时回调 */ one(metas: object[] | string[] | string, done: (this: this, err: any, ...bags: Bag[]) => void): this /** * 排队,前一个all,one或save任务做完后的下一个任务,类似promise * @param callback 当前面的任务完成后调用该回调 */ enqueue(callback: (this: this, ...args: any[]) => void): this /** * 开始处理队列中的下一个任务 */ dequeue(...args: any[]): void /** * 销毁当前请求,不可以继续发起新请求,而且不再调用相应的回调 */ destroy(): void } /** * 接口管理类 */ interface Service extends Event<Service> { /** * 继承产生新的Service类 * @param sync 同步数据的方法,通常在该方法内与服务端交换数据 * @param cacheMax 最大缓存数 * @param cacheBuffer 缓存区数量 */ extend(sync: (this: void, bag: Bag, callback: (error?: string | object) => void) => void, cacheMax?: number, cacheBuffer?: number): this /** * 添加接口元信息 * @param metas 接口元信息数组 */ add(metas: ServiceInterfaceMeta[]): void /** * 根据接口元信息创建bag对象 * @param meta 接口元信息对象或名称字符串 */ create(meta: ServiceInterfaceMeta | string): Bag /** * 获取元信息对象 * @param meta 接口元信息对象或名称字符串 */ meta(meta: ServiceInterfaceMeta | string): ServiceInterfaceMeta /** * 从缓存中获取或创意bag对象 * @param meta 接口元信息对象或名称字符串 * @param create 是否是创建新的Bag对象,如果否,则尝试从缓存中获取 */ get(meta: ServiceInterfaceMeta | string, create: boolean): Bag /** * 从缓存中清除指定接口的数据 * @param names 逗号分割的接口名称字符串或数组 */ clear(names: string | string[]): void /** * 从缓存中获取bag对象 * @param meta 接口元信息对象或名称字符串 */ cached(meta: ServiceInterfaceMeta | string): Bag | null /** * 接口发送请求前触发 */ onbegin: (this: this, e?: ServiceEvent) => void; /** * 接口发送结束时触发,不管请求成功或失败 */ onend: (this: this, e?: ServiceEvent) => void; /** * 初始化 */ new(): ServicePrototype /** * 原型 */ readonly prototype: ServicePrototype } interface Magix { /** * 设置或获取配置信息 * @param cfg 配置信息参数对象 */ config<T extends object>(cfg: Magix3.Config & T): Magix3.Config & T /** * 获取配置信息 * @param key 配置key */ config(key: string): any /** * 获取配置信息对象 */ config<T extends object>(): Magix3.Config & T /** * 应用初始化入口 * @param cfg 配置信息参数对象 */ boot(cfg: Magix3.Config): void /** * 把列表转化成hash对象。Magix.toMap([1,2,3,5,6]) => {1:1,2:1,3:1,4:1,5:1,6:1}。Magix.toMap([{id:20},{id:30},{id:40}],'id') => {20:{id:20},30:{id:30},40:{id:40}} * @param list 源数组 * @param key 以数组中对象的哪个key的value做为hash的key */ toMap<T extends object>(list: any[], key?: string): T /** * 以try catch方式执行方法,忽略掉任何异常。返回成功执行的最后一个方法的返回值 * @param fns 函数数组 * @param args 参数数组 * @param context 在待执行的方法内部,this的指向 */ toTry<TReturnType, TContextType>(fns: ((this: TContextType, ...args: any[]) => void) | ((this: TContextType, ...args: any[]) => void)[], args?: any[], context?: TContextType): TReturnType /** * 以try catch方式执行方法,忽略掉任何异常。返回成功执行的最后一个方法的返回值 * @param fns 函数数组 * @param args 参数数组 * @param context 在待执行的方法内部,this的指向 */ toTry<TReturnType>(fns: Function | Function[], args?: any[], context?: any): TReturnType /** * 转换成字符串路径。Magix.toUrl('/xxx/',{a:'b',c:'d'}) => /xxx/?a=b&c=d * @param path 路径 * @param params 参数对象 * @param keo 保留空白值的对象 */ toUrl(path: string, params?: object, keo?: object): string /** * 把路径字符串转换成对象。Magix.parseUrl('/xxx/?a=b&c=d') => {path:'/xxx/',params:{a:'b',c:'d'}} * @param url 路径字符串 */ parseUrl(url: string): Magix3.RouterParseParts /** * 把source对象的值添加到target对象上 * @param target 要mix的目标对象 * @param source mix的来源对象 */ mix<T, U>(target: T, source: U): T & U; /** * 把source对象的值添加到target对象上 * @param target 要mix的目标对象 * @param source1 第一个mix的来源对象 * @param source2 第二个mix的来源对象 */ mix<T, U, V>(target: T, source1: U, source2: V): T & U & V; /** * 把source对象的值添加到target对象上 * @param target 要mix的目标对象 * @param source1 第一个mix的来源对象 * @param source2 第二个mix的来源对象 * @param source3 第三个mix的来源对象 */ mix<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W; /** * 把source对象的值添加到target对象上 * @param target 要mix的目标对象 * @param sources 一个或多个mix的来源对象 */ mix(target: object, ...sources: any[]): any; /** * 检测某个对象是否拥有某个属性。 * @param owner 检测对象 * @param prop 属性 */ has(owner: object, prop: string | number): boolean /** * 获取对象的keys * @param src 源对象 */ keys(src: object): string[] /** * 判断一个节点是否在另外一个节点内,如果比较的2个节点是同一个节点,也返回true * @param node 节点或节点id * @param container 容器节点或节点id */ inside(node: HTMLElement | string, container: HTMLElement | string): boolean /** * document.getElementById的简写 * @param id 节点id */ node(id: string | HTMLElement): HTMLElement | null /** * 给节点添加id * @param node 节点对象 */ nodeId(node: HTMLElement): string /** * 使用加载器的加载模块功能 * @param deps 模块id * @param callback 回调 */ use(deps: string[], callback: (...args: object[]) => any): void /** * 保护对象不被修改 * @param o 保护对象 */ guard<T extends object>(o: T): T /** * 排除执行函数,解决卡顿问题 * @param fn 待执行的函数 * @param args 向函数传递的参数 * @param context 执行上下文对象 */ task(fn: (...args) => any, args?: any[], context?: object): void /** * 向页面追加样式 * @param key 样式对应的唯一key,该key主要防止向页面反复添加同样的样式 * @param cssText 样式字符串 */ applyStyle(key: string, cssText: string): void /** * 向页面追加样式 * @param atFile 以@开头的文件路径 */ applyStyle(atFile: string): void /** * 生成唯一的guid * @param prefix guid的前缀,默认mx- */ guid(prefix?: string): string /** * 在某个对象上打标,处理异步问题 * @param host 打标对象 * @param signature 标志字符串 */ mark(host: Object, signature: String): () => boolean /** * 取消打标 * @param host 打标对象 */ unmark(host: Object): void /** * 派发dom事件 * @param element dom节点对象 * @param type 事件名称 * @param data 事件参数 */ dispatch(element: HTMLElement | Node, type: string, data?: object): void /** * 接管管理类 */ Service: Magix3.Service /** * view类 */ View: Magix3.View /** * 缓存类 */ Cache: Magix3.Cache /** * 状态对象 */ State: Magix3.State /** * 事件对象 */ Event: Magix3.Event /** * 路由对象 */ Router: Magix3.Router /** * Vframe类,开发者绝对不需要继承、实例化该类! */ Vframe: Magix3.Vframe /** * 拥有事件on,off,fire的基类 */ Base: Magix3.Base default: Magix } } /** * export module */ declare module "magix" { const Magix: Magix3.Magix export = Magix; }
the_stack
import { SectionHeading } from "../site/SectionHeading" import * as cheerio from "cheerio" import urlSlug from "url-slug" import * as lodash from "lodash" import * as React from "react" import * as ReactDOMServer from "react-dom/server" import { HTTPS_ONLY } from "../settings/serverSettings" import { getTables } from "../db/wpdb" import Tablepress from "../site/Tablepress" import { GrapherExports } from "../baker/GrapherBakingUtils" import * as path from "path" import { renderBlocks } from "../site/blocks" import { RelatedCharts } from "../site/blocks/RelatedCharts" import { DataValueProps, FormattedPost, FormattingOptions, FullPost, JsonError, TocHeading, } from "../clientUtils/owidTypes" import { bakeGlobalEntitySelector } from "./bakeGlobalEntitySelector" import { Footnote } from "../site/Footnote" import { LoadingIndicator } from "../grapher/loadingIndicator/LoadingIndicator" import { PROMINENT_LINK_CLASSNAME } from "../site/blocks/ProminentLink" import { countryProfileSpecs } from "../site/countryProfileProjects" import { formatGlossaryTerms } from "../site/formatGlossary" import { getMutableGlossary, glossary } from "../site/glossary" import { DataToken } from "../site/DataToken" import { dataValueRegex, DEEP_LINK_CLASS, extractDataValuesConfiguration, formatDataValue, formatLinks, getHtmlContentWithStyles, parseKeyValueArgs, } from "./formatting" import { mathjax } from "mathjax-full/js/mathjax" import { TeX } from "mathjax-full/js/input/tex" import { SVG } from "mathjax-full/js/output/svg" import { liteAdaptor } from "mathjax-full/js/adaptors/liteAdaptor" import { RegisterHTMLHandler } from "mathjax-full/js/handlers/html" import { AllPackages } from "mathjax-full/js/input/tex/AllPackages" import { replaceIframesWithExplorerRedirectsInWordPressPost } from "./replaceExplorerRedirects" import { EXPLORERS_ROUTE_FOLDER } from "../explorer/ExplorerConstants" import { getDataValue, getLegacyChartDimensionConfigForVariable, getLegacyVariableDisplayConfig, } from "../db/model/Variable" import { AnnotatingDataValue } from "../site/AnnotatingDataValue" const initMathJax = () => { const adaptor = liteAdaptor() RegisterHTMLHandler(adaptor) const tex = new TeX({ packages: AllPackages }) const svg = new SVG({ fontCache: "none" }) const doc = mathjax.document("", { InputJax: tex, OutputJax: svg, }) return function format(latex: string): string { const node = doc.convert(latex, { display: true, }) return adaptor.outerHTML(node) // as HTML } } const formatMathJax = initMathJax() // A modifed FontAwesome icon const INTERACTIVE_ICON_SVG = `<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="hand-pointer" class="svg-inline--fa fa-hand-pointer fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 617"> <path fill="currentColor" d="M448,344.59v96a40.36,40.36,0,0,1-1.06,9.16l-32,136A40,40,0,0,1,376,616.59H168a40,40,0,0,1-32.35-16.47l-128-176a40,40,0,0,1,64.7-47.06L104,420.58v-276a40,40,0,0,1,80,0v200h8v-40a40,40,0,1,1,80,0v40h8v-24a40,40,0,1,1,80,0v24h8a40,40,0,1,1,80,0Zm-256,80h-8v96h8Zm88,0h-8v96h8Zm88,0h-8v96h8Z" transform="translate(0 -0.41)"/> <path fill="currentColor" opacity="0.6" d="M239.76,234.78A27.5,27.5,0,0,1,217,192a87.76,87.76,0,1,0-145.9,0A27.5,27.5,0,1,1,25.37,222.6,142.17,142.17,0,0,1,1.24,143.17C1.24,64.45,65.28.41,144,.41s142.76,64,142.76,142.76a142.17,142.17,0,0,1-24.13,79.43A27.47,27.47,0,0,1,239.76,234.78Z" transform="translate(0 -0.41)"/> </svg>` const extractLatex = (html: string): [string, string[]] => { const latexBlocks: string[] = [] html = html.replace(/\[latex\]([\s\S]*?)\[\/latex\]/gm, (_, latex) => { latexBlocks.push( latex.replace("\\[", "").replace("\\]", "").replace(/\$\$/g, "") ) return "[latex]" }) return [html, latexBlocks] } const formatLatex = async ( html: string, latexBlocks?: string[] ): Promise<string> => { if (!latexBlocks) [html, latexBlocks] = extractLatex(html) // return early so we don't do unnecessary work for sites without latex if (!latexBlocks.length) return html const compiled: string[] = [] for (const latex of latexBlocks) { try { compiled.push(formatMathJax(latex)) } catch (err) { compiled.push( `${latex} (Could not format equation due to MathJax error)` ) } } let i = -1 return html.replace(/\[latex\]/g, () => { i += 1 return compiled[i] }) } export const formatWordpressPost = async ( post: FullPost, html: string, formattingOptions: FormattingOptions, grapherExports?: GrapherExports ): Promise<FormattedPost> => { // Strip comments html = html.replace(/<!--[^>]+-->/g, "") // Need to skirt around wordpress formatting to get proper latex rendering let latexBlocks ;[html, latexBlocks] = extractLatex(html) const references: any[] = [] html = html.replace(/\[cite\]([\s\S]*?)\[\/cite\]/gm, () => { references.push({}) // Todo return `` }) html = await formatLatex(html, latexBlocks) // Footnotes const footnotes: string[] = [] html = html.replace(/{ref}([\s\S]*?){\/ref}/gm, (_, footnote) => { if (formattingOptions.footnotes) { footnotes.push(footnote) const i = footnotes.length const href = `#note-${i}` return ReactDOMServer.renderToStaticMarkup( <a id={`ref-${i}`} className="ref" href={href}> <Footnote index={i} /> </a> ) } else { return "" } }) const dataValuesConfigurationsMap = await extractDataValuesConfiguration( html ) const dataValues = new Map<string, DataValueProps>() for (const [ dataValueConfigurationString, dataValueConfiguration, ] of dataValuesConfigurationsMap) { const { queryArgs, template } = dataValueConfiguration const { variableId, chartId } = queryArgs const { value, year, unit, entityName } = (await getDataValue(queryArgs)) || {} if (!value || !year || !entityName) throw new JsonError( `Missing data for query ${dataValueConfigurationString}. Please check the tag for any missing or wrong argument.` ) if (!template) throw new JsonError( `Missing template for query ${dataValueConfigurationString}` ) let formattedValue if (variableId && chartId) { const legacyVariableDisplayConfig = await getLegacyVariableDisplayConfig(variableId) const legacyChartDimension = await getLegacyChartDimensionConfigForVariable( variableId, chartId ) formattedValue = formatDataValue( value, variableId, legacyVariableDisplayConfig, legacyChartDimension ) } dataValues.set(dataValueConfigurationString, { value, formattedValue, template, year, unit, entityName, }) } html = html.replace(dataValueRegex, (_, dataValueConfigurationString) => { const dataValueProps: DataValueProps | undefined = dataValues.get( dataValueConfigurationString ) if (!dataValueProps) throw new JsonError( `Missing data value for query ${dataValueConfigurationString}` ) return ReactDOMServer.renderToString( <AnnotatingDataValue dataValueProps={dataValueProps} /> ) }) // Needs to be happen after DataValue replacements, as the DataToken regex // would otherwise capture DataValue tags const dataTokenRegex = /{{\s*([a-zA-Z]+)\s*(.+?)\s*}}/g html = html.replace( dataTokenRegex, (_, token, dataTokenConfigurationString) => { return ReactDOMServer.renderToString( <DataToken token={token} {...parseKeyValueArgs(dataTokenConfigurationString)} /> ) } ) // Insert [table id=foo] tablepress tables const tables = await getTables() html = html.replace(/\[table\s+id=(\d+)\s*\/\]/g, (match, tableId) => { const table = tables.get(tableId) if (table) return ReactDOMServer.renderToStaticMarkup( <Tablepress data={table.data} /> ) return "UNKNOWN TABLE" }) // No need for wordpress urls html = html.replace(new RegExp("/app/uploads", "g"), "/uploads") // Give "Add country" text (and variations) the appearance of "+ Add Country" chart control html = html.replace( /(\+ )?[a|A]dd [c|C]ountry/g, `<span class="add-country"> <span class="icon"> <svg width="16" height="16"><path d="M3,8 h10 m-5,-5 v10"></path></svg> </span> Add country </span>` ) const cheerioEl = cheerio.load(html) // Related charts // Mimicking SSR output of additional information block from PHP if ( !countryProfileSpecs.some( (spec) => post.slug === spec.landingPageSlug ) && post.relatedCharts && post.relatedCharts.length !== 0 ) { const allCharts = ` <block type="additional-information"> <content> <h3>All our charts on ${post.title}</h3> ${ReactDOMServer.renderToStaticMarkup( <div> <RelatedCharts charts={post.relatedCharts} /> </div> )} </content> </block> ` const $summary = cheerioEl(".wp-block-owid-summary") if ($summary.length !== 0) { $summary.after(allCharts) } else { cheerioEl("body > h2:first-of-type, body > h3:first-of-type") .first() .before(allCharts) } } // SSR rendering of Gutenberg blocks, before hydration on client renderBlocks(cheerioEl) // Extract blog info content let info = null const $info = cheerioEl(".blog-info") if ($info.length) { info = $info.html() $info.remove() } // Extract last updated let lastUpdated const $lastUpdated = cheerioEl(".wp-block-last-updated p") if ($lastUpdated.length) { lastUpdated = $lastUpdated.html() $lastUpdated.remove() } // Extract page supertitle let supertitle const $supertitle = cheerioEl(".wp-block-owid-supertitle") if ($supertitle.length) { supertitle = $supertitle.text() $supertitle.remove() } // Extract page byline let byline const $byline = cheerioEl(".wp-block-owid-byline") if ($byline.length) { byline = $byline.html() $byline.remove() } // Replace URLs pointing to Explorer redirect URLs with the destination URLs replaceIframesWithExplorerRedirectsInWordPressPost(cheerioEl) // Replace grapher iframes with static previews const GRAPHER_PREVIEW_CLASS = "grapherPreview" if (grapherExports) { const grapherIframes = cheerioEl("iframe") .toArray() .filter((el) => (el.attribs["src"] || "").match(/\/grapher\//)) for (const el of grapherIframes) { const $el = cheerioEl(el) const src = el.attribs["src"].trim() const chart = grapherExports.get(src) if (chart) { const output = ` <figure data-grapher-src="${src}" class="${GRAPHER_PREVIEW_CLASS}"> <a href="${src}" target="_blank"> <div><img src="${chart.svgUrl}" width="${chart.width}" height="${chart.height}" loading="lazy" data-no-lightbox /></div> <div class="interactionNotice"> <span class="icon">${INTERACTIVE_ICON_SVG}</span> <span class="label">Click to open interactive version</span> </div> </a> </figure>` if (el.parent.tagName === "p") { // We are about to replace <iframe> with <figure>. However, there cannot be <figure> within <p>, // so we are lifting the <figure> out. // Where does this markup come from? Historically, wpautop wrapped <iframe> in <p>. Some non-Gutengerg // posts will still show that, until they are converted. As a reminder, wpautop is not being used // on the overall post content anymore, neither on the Wordpress side nor on the grapher side (through // the wpautop npm package), but its effects are still "present" after the result of wpautop were committed // to the DB during a one-time refactoring session. // <p><iframe></iframe></p> --> <p></p><figure></figure> const $p = $el.parent() $p.after(output) $el.remove() } else if (el.parent.tagName === "figure") { // Support for <iframe> wrapped in <figure> // <figure> automatically added by Gutenberg on copy / paste <iframe> // Lifting up <iframe> out of <figure>, before it becomes a <figure> itself. // <figure><iframe></iframe></figure> --> <figure></figure> const $figure = $el.parent() $figure.after(output) $figure.remove() } else { // No lifting up otherwise, just replacing <iframe> with <figure> // <iframe></iframe> --> <figure></figure> $el.after(output) $el.remove() } } } } // Replace explorer iframes with iframeless embed const explorerIframes = cheerioEl("iframe") .toArray() .filter((el) => (el.attribs["src"] || "").includes(`/${EXPLORERS_ROUTE_FOLDER}/`) ) for (const el of explorerIframes) { const $el = cheerioEl(el) const src = el.attribs["src"].trim() // set a default style if none exists on the existing iframe const style = el.attribs["style"] || "width: 100%; height: 600px;" const cssClass = el.attribs["class"] const $figure = cheerioEl( ReactDOMServer.renderToStaticMarkup( <figure data-explorer-src={src} className={cssClass}> <LoadingIndicator /> </figure> ) ) $figure.attr("style", style) $el.after($figure) $el.remove() } // Any remaining iframes for (const iframe of cheerioEl("iframe").toArray()) { // Ensure https embeds if (HTTPS_ONLY && iframe.attribs["src"]) { iframe.attribs["src"] = iframe.attribs["src"].replace( "http://", "https://" ) } // Lazy load unless "loading" attribute already specified if (!iframe.attribs["loading"]) { iframe.attribs["loading"] = "lazy" } } // Remove any empty elements for (const p of cheerioEl("p").toArray()) { const $p = cheerioEl(p) if ($p.contents().length === 0) $p.remove() } // Wrap tables so we can do overflow-x: scroll if needed for (const table of cheerioEl("table").toArray()) { const $table = cheerioEl(table) const $div = cheerioEl("<div class='tableContainer'></div>") $table.after($div) $div.append($table) } // Make sticky-right layout the default for columns cheerioEl(".wp-block-columns").each((_, columns) => { const $columns = cheerioEl(columns) if (columns.attribs.class === "wp-block-columns") { $columns.addClass("is-style-sticky-right") } }) // Image processing // Assumptions: // - original images are not uploaded with a suffix "-[number]x[number]" // (without the quotes). // - variants are being generated by wordpress when the original is uploaded // - images are never legitimate direct descendants of <a> tags. // <a><img /></a> is considered deprecated (was used to create direct links to // the full resolution variant) and wrapping <a> will be removed to prevent // conflicts with lightboxes. Chosen over preventDefault() in front-end code // to avoid clicks before javascript executes. for (const el of cheerioEl("img").toArray()) { // Recreate source image path by removing automatically added image // dimensions (e.g. remove 800x600). const src = el.attribs["src"] const parsedPath = path.parse(src) let originalFilename = "" if (parsedPath.ext !== ".svg") { originalFilename = parsedPath.name.replace(/-\d+x\d+$/, "") const originalSrc = path.format({ dir: parsedPath.dir, name: originalFilename, ext: parsedPath.ext, }) el.attribs["data-high-res-src"] = originalSrc } else { originalFilename = parsedPath.name } // Remove wrapping <a> tag, conflicting with lightbox (cf. assumptions above) if (el.parent.tagName === "a") { const $a = cheerioEl(el.parent) $a.replaceWith(cheerioEl(el)) } // Add alt attribute if (!el.attribs["alt"]) { el.attribs["alt"] = lodash.capitalize( originalFilename.replace(/[-_]/g, " ") ) } // Lazy load all images, unless they already have a "loading" attribute. if (!el.attribs["loading"]) { el.attribs["loading"] = "lazy" } } // Table of contents and deep links const tocHeadings: TocHeading[] = [] const existingSlugs: string[] = [] let parentHeading: TocHeading | null = null cheerioEl("h1, h2, h3, h4").each((_, el) => { const $heading = cheerioEl(el) const headingText = $heading.text() let slug = urlSlug(headingText) // Avoid If the slug already exists, try prepend the parent if (existingSlugs.indexOf(slug) !== -1 && parentHeading) { slug = `${parentHeading.slug}-${slug}` } existingSlugs.push(slug) // Table of contents if (formattingOptions.toc) { if ($heading.is("#footnotes") && footnotes.length > 0) { tocHeadings.push({ text: headingText, slug: "footnotes", isSubheading: false, }) } else if (!$heading.is("h1") && !$heading.is("h4")) { if ($heading.is("h2")) { const tocHeading = { text: headingText, slug: slug, isSubheading: false, } tocHeadings.push(tocHeading) parentHeading = tocHeading } else if ( $heading.closest(`.${PROMINENT_LINK_CLASSNAME}`).length === 0 && $heading.closest(".wp-block-owid-additional-information") .length === 0 ) { tocHeadings.push({ text: headingText, html: $heading.html() || undefined, slug: slug, isSubheading: true, }) } } } $heading.attr("id", slug) // Add deep link for headings not contained in <a> tags already // (e.g. within a prominent link block) if ( !$heading.closest(`.${PROMINENT_LINK_CLASSNAME}`).length && // already wrapped in <a> !$heading.closest(".wp-block-owid-additional-information").length && // prioritize clean SSR of AdditionalInformation !$heading.closest(".wp-block-help").length ) { $heading.prepend( `<a class="${DEEP_LINK_CLASS}" href="#${slug}"></a>` ) } }) interface Columns { wrapper: Cheerio first: Cheerio last: Cheerio } const getColumns = (style: string = "sticky-right"): Columns => { const emptyColumns = `<div class="wp-block-columns is-style-${style}"><div class="wp-block-column"></div><div class="wp-block-column"></div></div>` const $columns = cheerioEl(emptyColumns) return { wrapper: $columns, first: $columns.children().first(), last: $columns.children().last(), } } const isColumnsEmpty = (columns: Columns) => { return columns.first.children().length === 0 && columns.last.children().length === 0 ? true : false } const flushColumns = (columns: Columns, $section: Cheerio): Columns => { $section.append(columns.wrapper) return getColumns() } // Wrap content demarcated by headings into section blocks // and automatically divide content into columns const sectionStarts = [cheerioEl("body").children().get(0)].concat( cheerioEl("body > h2").toArray() ) for (const start of sectionStarts) { const $start = cheerioEl(start) const $section = cheerioEl("<section>") let columns = getColumns() let sideBySideColumns = getColumns("side-by-side") const $tempWrapper = cheerioEl("<div>") const $contents = $tempWrapper .append($start.clone(), $start.nextUntil(cheerioEl("h2"))) .contents() if (post.glossary) { formatGlossaryTerms( cheerioEl, $contents, getMutableGlossary(glossary) ) } $contents.each((i, el) => { const $el = cheerioEl(el) // Leave h2 at the section level, do not move into columns if (el.name === "h2") { $section.append( ReactDOMServer.renderToStaticMarkup( <SectionHeading title={$el.text()} tocHeadings={tocHeadings} > <div dangerouslySetInnerHTML={{ __html: cheerioEl.html($el), }} /> </SectionHeading> ) ) } else if ( el.name === "h3" || $el.hasClass("wp-block-columns") || $el.hasClass("wp-block-owid-grid") || $el.hasClass("wp-block-full-content-width") || $el.find( '.wp-block-owid-additional-information[data-variation="full-width"]' ).length !== 0 ) { if (!isColumnsEmpty(columns)) { columns = flushColumns(columns, $section) } $section.append($el) } else if (el.name === "h4") { if (!isColumnsEmpty(columns)) { columns = flushColumns(columns, $section) } columns.first.append($el) columns = flushColumns(columns, $section) } else { if ( el.name === "figure" && $el.hasClass(GRAPHER_PREVIEW_CLASS) ) { if (isColumnsEmpty(sideBySideColumns)) { // Only fill the side by side buffer if there is an upcoming chart for a potential comparison. // Otherwise let the standard process (sticky right) take over. if ( $contents[i].nextSibling?.attribs?.class === GRAPHER_PREVIEW_CLASS ) { columns = flushColumns(columns, $section) sideBySideColumns.first.append($el) } else { columns.last.append($el) } } else { sideBySideColumns.last.append($el) $section.append(sideBySideColumns.wrapper) sideBySideColumns = getColumns("side-by-side") } } // Move images to the right column else if ( el.name === "figure" || el.name === "iframe" || // Temporary support for old chart iframes el.name === "address" || $el.hasClass("wp-block-image") || $el.hasClass("tableContainer") || // Temporary support for non-Gutenberg iframes wrapped in wpautop's <p> // Also catches older iframes (e.g. https://ourworldindata.org/food-per-person#world-map-of-minimum-and-average-dietary-energy-requirement-mder-and-ader) $el.find("iframe").length !== 0 || // TODO: remove temporary support for pre-Gutenberg images and associated captions el.name === "h6" || ($el.find("img").length !== 0 && !$el.hasClass(PROMINENT_LINK_CLASSNAME) && !$el.find( ".wp-block-owid-additional-information[data-variation='merge-left']" )) ) { columns.last.append($el) } else { // Move non-heading, non-image content to the left column columns.first.append($el) } } }) if (!isColumnsEmpty(columns)) { $section.append(columns.wrapper) } $start.replaceWith($section) } // Render global country selection component. // Injects a <section>, which is why it executes last. bakeGlobalEntitySelector(cheerioEl) return { id: post.id, type: post.type, slug: post.slug, path: post.path, title: post.title, subtitle: post.subtitle, supertitle: supertitle, date: post.date, modifiedDate: post.modifiedDate, lastUpdated: lastUpdated, authors: post.authors, byline: byline, info: info, html: getHtmlContentWithStyles(cheerioEl), footnotes: footnotes, references: references, excerpt: post.excerpt || cheerioEl("p").first().text(), imageUrl: post.imageUrl, tocHeadings: tocHeadings, relatedCharts: post.relatedCharts, } } export const formatPost = async ( post: FullPost, formattingOptions: FormattingOptions, grapherExports?: GrapherExports ): Promise<FormattedPost> => { const html = formatLinks(post.content) // No formatting applied, plain source HTML returned if (formattingOptions.raw) return { ...post, html, footnotes: [], references: [], tocHeadings: [], excerpt: post.excerpt || "", } // Override formattingOptions if specified in the post (as an HTML comment) const options: FormattingOptions = Object.assign( { toc: post.type === "page", footnotes: true, }, formattingOptions ) return formatWordpressPost(post, html, options, grapherExports) }
the_stack
import { SpecPage } from '@stencil/core/testing'; import { flushTransitions } from './unit-test-utils'; const fakePosition = { pageX: 125, pageY: 250 }; const tooltipSelector = '[data-testid=tooltip-container]'; export const tooltip_showTooltip_default = { prop: 'showTooltip', group: 'labels', name: 'tooltip should render and have opacity 0 by default on load (before a hover)', testProps: {}, testSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, expectedTooltipContent: string ) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } page.root.appendChild(component); await page.waitForChanges(); // ACT const tooltipContainer = await page.doc.querySelector(tooltipSelector); // ASSERT expect(tooltipContainer).toHaveClass('vcl-tooltip'); expect(parseFloat(tooltipContainer.style.opacity)).toEqual(0); } }; export const tooltip_showTooltip_hover = { prop: 'showTooltip', group: 'labels', name: 'tooltip should render and have opacity 1 and be placed on hover', testProps: {}, testSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, expectedTooltipContent: string ) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } page.root.appendChild(component); await page.waitForChanges(); // ACT - TRIGGER HOVER const tooltipContainer = await page.doc.querySelector(tooltipSelector); const markerToHover = await page.doc.querySelector(testSelector); const mockMouseEvent = new MouseEvent('mouseover'); markerToHover.dispatchEvent({ ...mockMouseEvent, ...fakePosition }); // ACT - FLUSH TRANSITIONS flushTransitions(tooltipContainer); await page.waitForChanges(); expect(parseFloat(tooltipContainer.style.opacity)).toEqual(1); expect(tooltipContainer.style.left).toEqual(`${fakePosition.pageX}px`); expect(tooltipContainer.style.top).toEqual(`${fakePosition.pageY}px`); } }; export const tooltip_showTooltip_false = { prop: 'showTooltip', group: 'labels', name: 'tooltip should not render when event is triggered and showTooltip is false', testProps: { showTooltip: false }, testSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, expectedTooltipContent: string ) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } page.root.appendChild(component); await page.waitForChanges(); // ACT - TRIGGER HOVER const tooltipContainer = await page.doc.querySelector(tooltipSelector); const markerToHover = await page.doc.querySelector(testSelector); const mockMouseEvent = new MouseEvent('mouseover'); markerToHover.dispatchEvent({ ...mockMouseEvent, ...fakePosition }); // ACT - FLUSH TRANSITIONS flushTransitions(tooltipContainer); await page.waitForChanges(); expect(parseFloat(tooltipContainer.style.opacity)).toEqual(0); } }; export const tooltip_tooltipLabel_default = { prop: 'tooltipLabel', group: 'labels', name: 'tooltip should render default content on load', testProps: {}, testSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, expectedTooltipContent: string ) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } page.root.appendChild(component); await page.waitForChanges(); // ACT - TRIGGER HOVER const tooltipContainer = await page.doc.querySelector(tooltipSelector); const markerToHover = await page.doc.querySelector(testSelector); const mockMouseEvent = new MouseEvent('mouseover'); markerToHover.dispatchEvent({ ...mockMouseEvent, ...fakePosition }); // ACT - FLUSH TRANSITIONS flushTransitions(tooltipContainer); await page.waitForChanges(); const tooltipContent = tooltipContainer.querySelector('p'); expect(tooltipContent).toEqualHtml(expectedTooltipContent); expect(parseFloat(tooltipContainer.style.opacity)).toEqual(1); expect(tooltipContainer.style.left).toEqual(`${fakePosition.pageX}px`); expect(tooltipContainer.style.top).toEqual(`${fakePosition.pageY}px`); } }; export const tooltip_tooltipLabel_custom_load = { prop: 'tooltipLabel', group: 'labels', name: 'tooltip should render custom content on load', testProps: {}, testSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, expectedTooltipContent: string ) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } page.root.appendChild(component); await page.waitForChanges(); // ACT - TRIGGER HOVER const tooltipContainer = await page.doc.querySelector(tooltipSelector); const markerToHover = await page.doc.querySelector(testSelector); const mockMouseEvent = new MouseEvent('mouseover'); markerToHover.dispatchEvent({ ...mockMouseEvent, ...fakePosition }); // ACT - FLUSH TRANSITIONS flushTransitions(tooltipContainer); await page.waitForChanges(); const tooltipContent = tooltipContainer.querySelector('p'); expect(tooltipContent).toEqualHtml(expectedTooltipContent); expect(parseFloat(tooltipContainer.style.opacity)).toEqual(1); expect(tooltipContainer.style.left).toEqual(`${fakePosition.pageX}px`); expect(tooltipContainer.style.top).toEqual(`${fakePosition.pageY}px`); } }; export const tooltip_tooltipLabel_custom_update = { prop: 'tooltipLabel', group: 'labels', name: 'tooltip should render custom content on update', testProps: {}, testSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, expectedTooltipContent: string ) => { // ARRANGE RENDER page.root.appendChild(component); await page.waitForChanges(); // ARRANGE UPDATE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } await page.waitForChanges(); // ACT - TRIGGER HOVER const tooltipContainer = await page.doc.querySelector(tooltipSelector); const markerToHover = await page.doc.querySelector(testSelector); const mockMouseEvent = new MouseEvent('mouseover'); markerToHover.dispatchEvent({ ...mockMouseEvent, ...fakePosition }); // ACT - FLUSH TRANSITIONS flushTransitions(tooltipContainer); await page.waitForChanges(); const tooltipContent = tooltipContainer.querySelector('p'); expect(tooltipContent).toEqualHtml(expectedTooltipContent); expect(parseFloat(tooltipContainer.style.opacity)).toEqual(1); expect(tooltipContainer.style.left).toEqual(`${fakePosition.pageX}px`); expect(tooltipContainer.style.top).toEqual(`${fakePosition.pageY}px`); } }; export const tooltip_tooltipLabel_custom_format_load = { prop: 'tooltipLabel', group: 'labels', name: 'tooltip should render formatted custom content on load', testProps: {}, testSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, expectedTooltipContent: string ) => { // ARRANGE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } page.root.appendChild(component); await page.waitForChanges(); // ACT - TRIGGER HOVER const tooltipContainer = await page.doc.querySelector(tooltipSelector); const markerToHover = await page.doc.querySelector(testSelector); const mockMouseEvent = new MouseEvent('mouseover'); markerToHover.dispatchEvent({ ...mockMouseEvent, ...fakePosition }); // ACT - FLUSH TRANSITIONS flushTransitions(tooltipContainer); await page.waitForChanges(); const tooltipContent = tooltipContainer.querySelector('p'); expect(tooltipContent).toEqualHtml(expectedTooltipContent); expect(parseFloat(tooltipContainer.style.opacity)).toEqual(1); expect(tooltipContainer.style.left).toEqual(`${fakePosition.pageX}px`); expect(tooltipContainer.style.top).toEqual(`${fakePosition.pageY}px`); } }; export const tooltip_tooltipLabel_custom_format_update = { prop: 'tooltipLabel', group: 'labels', name: 'tooltip should render formatted custom content on update', testProps: {}, testSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, expectedTooltipContent: string ) => { // ARRANGE RENDER page.root.appendChild(component); await page.waitForChanges(); // ARRANGE UPDATE // if we have any testProps apply them if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { component[testProp] = testProps[testProp]; }); } await page.waitForChanges(); // ACT - TRIGGER HOVER const tooltipContainer = await page.doc.querySelector(tooltipSelector); const markerToHover = await page.doc.querySelector(testSelector); const mockMouseEvent = new MouseEvent('mouseover'); markerToHover.dispatchEvent({ ...mockMouseEvent, ...fakePosition }); // ACT - FLUSH TRANSITIONS flushTransitions(tooltipContainer); await page.waitForChanges(); const tooltipContent = tooltipContainer.querySelector('p'); expect(tooltipContent).toEqualHtml(expectedTooltipContent); expect(parseFloat(tooltipContainer.style.opacity)).toEqual(1); expect(tooltipContainer.style.left).toEqual(`${fakePosition.pageX}px`); expect(tooltipContainer.style.top).toEqual(`${fakePosition.pageY}px`); } };
the_stack
import * as nls from 'vs/nls'; import { isObject } from 'vs/base/common/types'; import { IJSONSchema, IJSONSchemaMap, IJSONSchemaSnippet } from 'vs/base/common/jsonSchema'; import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { IConfig, IDebuggerContribution, IDebugAdapter, IDebugger, IDebugSession, IAdapterManager, IDebugService, debuggerDisabledMessage, IDebuggerMetadata } from 'vs/workbench/contrib/debug/common/debug'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver'; import * as ConfigurationResolverUtils from 'vs/workbench/services/configurationResolver/common/configurationResolverUtils'; import { ITextResourcePropertiesService } from 'vs/editor/common/services/textResourceConfiguration'; import { URI } from 'vs/base/common/uri'; import { Schemas } from 'vs/base/common/network'; import { isDebuggerMainContribution } from 'vs/workbench/contrib/debug/common/debugUtils'; import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { ITelemetryEndpoint } from 'vs/platform/telemetry/common/telemetry'; import { cleanRemoteAuthority } from 'vs/platform/telemetry/common/telemetryUtils'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { ContextKeyExpr, ContextKeyExpression, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; export class Debugger implements IDebugger, IDebuggerMetadata { private debuggerContribution: IDebuggerContribution; private mergedExtensionDescriptions: IExtensionDescription[] = []; private mainExtensionDescription: IExtensionDescription | undefined; private debuggerWhen: ContextKeyExpression | undefined; constructor( private adapterManager: IAdapterManager, dbgContribution: IDebuggerContribution, extensionDescription: IExtensionDescription, @IConfigurationService private readonly configurationService: IConfigurationService, @ITextResourcePropertiesService private readonly resourcePropertiesService: ITextResourcePropertiesService, @IConfigurationResolverService private readonly configurationResolverService: IConfigurationResolverService, @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, @IDebugService private readonly debugService: IDebugService, @IContextKeyService private readonly contextKeyService: IContextKeyService, ) { this.debuggerContribution = { type: dbgContribution.type }; this.merge(dbgContribution, extensionDescription); this.debuggerWhen = typeof this.debuggerContribution.when === 'string' ? ContextKeyExpr.deserialize(this.debuggerContribution.when) : undefined; } merge(otherDebuggerContribution: IDebuggerContribution, extensionDescription: IExtensionDescription): void { /** * Copies all properties of source into destination. The optional parameter "overwrite" allows to control * if existing non-structured properties on the destination should be overwritten or not. Defaults to true (overwrite). */ function mixin(destination: any, source: any, overwrite: boolean, level = 0): any { if (!isObject(destination)) { return source; } if (isObject(source)) { Object.keys(source).forEach(key => { if (key !== '__proto__') { if (isObject(destination[key]) && isObject(source[key])) { mixin(destination[key], source[key], overwrite, level + 1); } else { if (key in destination) { if (overwrite) { if (level === 0 && key === 'type') { // don't merge the 'type' property } else { destination[key] = source[key]; } } } else { destination[key] = source[key]; } } } }); } return destination; } // only if not already merged if (this.mergedExtensionDescriptions.indexOf(extensionDescription) < 0) { // remember all extensions that have been merged for this debugger this.mergedExtensionDescriptions.push(extensionDescription); // merge new debugger contribution into existing contributions (and don't overwrite values in built-in extensions) mixin(this.debuggerContribution, otherDebuggerContribution, extensionDescription.isBuiltin); // remember the extension that is considered the "main" debugger contribution if (isDebuggerMainContribution(otherDebuggerContribution)) { this.mainExtensionDescription = extensionDescription; } } } createDebugAdapter(session: IDebugSession): Promise<IDebugAdapter> { return this.adapterManager.activateDebuggers('onDebugAdapterProtocolTracker', this.type).then(_ => { const da = this.adapterManager.createDebugAdapter(session); if (da) { return Promise.resolve(da); } throw new Error(nls.localize('cannot.find.da', "Cannot find debug adapter for type '{0}'.", this.type)); }); } substituteVariables(folder: IWorkspaceFolder | undefined, config: IConfig): Promise<IConfig> { return this.adapterManager.substituteVariables(this.type, folder, config).then(config => { return this.configurationResolverService.resolveWithInteractionReplace(folder, config, 'launch', this.variables, config.__configurationTarget); }); } runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments, sessionId: string): Promise<number | undefined> { return this.adapterManager.runInTerminal(this.type, args, sessionId); } get label(): string { return this.debuggerContribution.label || this.debuggerContribution.type; } get type(): string { return this.debuggerContribution.type; } get variables(): { [key: string]: string } | undefined { return this.debuggerContribution.variables; } get configurationSnippets(): IJSONSchemaSnippet[] | undefined { return this.debuggerContribution.configurationSnippets; } get languages(): string[] | undefined { return this.debuggerContribution.languages; } get when(): ContextKeyExpression | undefined { return this.debuggerWhen; } get enabled() { return !this.debuggerWhen || this.contextKeyService.contextMatchesRules(this.debuggerWhen); } get uiMessages() { return this.debuggerContribution.uiMessages; } interestedInLanguage(languageId: string): boolean { return !!(this.languages && this.languages.indexOf(languageId) >= 0); } hasInitialConfiguration(): boolean { return !!this.debuggerContribution.initialConfigurations; } hasConfigurationProvider(): boolean { return this.debugService.getConfigurationManager().hasDebugConfigurationProvider(this.type); } getInitialConfigurationContent(initialConfigs?: IConfig[]): Promise<string> { // at this point we got some configs from the package.json and/or from registered DebugConfigurationProviders let initialConfigurations = this.debuggerContribution.initialConfigurations || []; if (initialConfigs) { initialConfigurations = initialConfigurations.concat(initialConfigs); } const eol = this.resourcePropertiesService.getEOL(URI.from({ scheme: Schemas.untitled, path: '1' })) === '\r\n' ? '\r\n' : '\n'; const configs = JSON.stringify(initialConfigurations, null, '\t').split('\n').map(line => '\t' + line).join(eol).trim(); const comment1 = nls.localize('launch.config.comment1', "Use IntelliSense to learn about possible attributes."); const comment2 = nls.localize('launch.config.comment2', "Hover to view descriptions of existing attributes."); const comment3 = nls.localize('launch.config.comment3', "For more information, visit: {0}", 'https://go.microsoft.com/fwlink/?linkid=830387'); let content = [ '{', `\t// ${comment1}`, `\t// ${comment2}`, `\t// ${comment3}`, `\t"version": "0.2.0",`, `\t"configurations": ${configs}`, '}' ].join(eol); // fix formatting const editorConfig = this.configurationService.getValue<any>(); if (editorConfig.editor && editorConfig.editor.insertSpaces) { content = content.replace(new RegExp('\t', 'g'), ' '.repeat(editorConfig.editor.tabSize)); } return Promise.resolve(content); } getMainExtensionDescriptor(): IExtensionDescription { return this.mainExtensionDescription || this.mergedExtensionDescriptions[0]; } getCustomTelemetryEndpoint(): ITelemetryEndpoint | undefined { const aiKey = this.debuggerContribution.aiKey; if (!aiKey) { return undefined; } const sendErrorTelemtry = cleanRemoteAuthority(this.environmentService.remoteAuthority) !== 'other'; return { id: `${this.getMainExtensionDescriptor().publisher}.${this.type}`, aiKey, sendErrorTelemetry: sendErrorTelemtry }; } getSchemaAttributes(definitions: IJSONSchemaMap): IJSONSchema[] | null { if (!this.debuggerContribution.configurationAttributes) { return null; } // fill in the default configuration attributes shared by all adapters. return Object.keys(this.debuggerContribution.configurationAttributes).map(request => { const definitionId = `${this.type}:${request}`; const attributes: IJSONSchema = this.debuggerContribution.configurationAttributes[request]; const defaultRequired = ['name', 'type', 'request']; attributes.required = attributes.required && attributes.required.length ? defaultRequired.concat(attributes.required) : defaultRequired; attributes.additionalProperties = false; attributes.type = 'object'; if (!attributes.properties) { attributes.properties = {}; } const properties = attributes.properties; properties['type'] = { enum: [this.type], enumDescriptions: [this.label], description: nls.localize('debugType', "Type of configuration."), pattern: '^(?!node2)', deprecationMessage: this.debuggerContribution.deprecated || (this.enabled ? undefined : debuggerDisabledMessage(this.type)), doNotSuggest: !!this.debuggerContribution.deprecated, errorMessage: nls.localize('debugTypeNotRecognised', "The debug type is not recognized. Make sure that you have a corresponding debug extension installed and that it is enabled."), patternErrorMessage: nls.localize('node2NotSupported', "\"node2\" is no longer supported, use \"node\" instead and set the \"protocol\" attribute to \"inspector\".") }; properties['request'] = { enum: [request], description: nls.localize('debugRequest', "Request type of configuration. Can be \"launch\" or \"attach\"."), }; for (const prop in definitions['common'].properties) { properties[prop] = { $ref: `#/definitions/common/properties/${prop}` }; } Object.keys(properties).forEach(name => { // Use schema allOf property to get independent error reporting #21113 ConfigurationResolverUtils.applyDeprecatedVariableMessage(properties[name]); }); definitions[definitionId] = { ...attributes }; // Don't add the OS props to the real attributes object so they don't show up in 'definitions' const attributesCopy = { ...attributes }; attributesCopy.properties = { ...properties, ...{ windows: { $ref: `#/definitions/${definitionId}`, description: nls.localize('debugWindowsConfiguration', "Windows specific launch configuration attributes."), required: [], }, osx: { $ref: `#/definitions/${definitionId}`, description: nls.localize('debugOSXConfiguration', "OS X specific launch configuration attributes."), required: [], }, linux: { $ref: `#/definitions/${definitionId}`, description: nls.localize('debugLinuxConfiguration', "Linux specific launch configuration attributes."), required: [], } } }; return attributesCopy; }); } }
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Chart } from '../../../src/chart/chart'; import { LineSeries } from '../../../src/chart/series/line-series'; import { DataLabel } from '../../../src/chart/series/data-label'; import { Category } from '../../../src/chart/axis/category-axis'; import { DateTime } from '../../../src/chart/axis/date-time-axis'; import { Tooltip } from '../../../src/chart/user-interaction/tooltip'; import { ColumnSeries } from '../../../src/chart/series/column-series'; import '../../../node_modules/es6-promise/dist/es6-promise'; import { unbindResizeEvents } from '../base/data.spec'; import { EmitType } from '@syncfusion/ej2-base'; import { StackingColumnSeries } from '../../../src/chart/series/stacking-column-series'; import { sort } from '../../../src/common/utils/helper'; import '../../../node_modules/es6-promise/dist/es6-promise'; import { ILoadedEventArgs } from '../../../src/chart/model/chart-interface'; import {profile , inMB, getMemoryProfile} from '../../common.spec'; Chart.Inject(LineSeries, Category, DataLabel, StackingColumnSeries, ColumnSeries); export let data: Object[] = [ { country: 'USA', gold: 50, gold1: 55 }, { country: 'China', gold: 40, gold1: 45 }, { country: 'Japan', gold: 70, gold1: 75 }, { country: 'Australia', gold: 60, gold1: 65 }, { country: 'France', gold: 50, gold1: 55 }, { country: 'Germany', gold: 40, gold1: 45 }, { country: 'Italy', gold: 40, gold1: 45 }, { country: 'Sweden', gold: 30, gold1: 35 } ]; export let data1: any[] = [ { country: 'USA', gold: 55 }, { country: 'China', gold: 50 }, { country: 'Japan', gold: 75 }, { country: 'Australia', gold: 65 }, { country: 'France', gold: 60 }, { country: 'Germany', gold: 45 }, { country: 'Italy', gold: 40 }, { country: 'Sweden', gold: 35 } ]; describe('Chart Control', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe('Sorting', () => { let chart: Chart; let ele: HTMLElement; let loaded: EmitType<ILoadedEventArgs>; let element: Element; beforeAll((): void => { ele = createElement('div', { id: 'container' }); document.body.appendChild(ele); chart = new Chart( { primaryXAxis: { valueType: 'Category', rangePadding: 'Normal', labelIntersectAction :'Hide' }, series: [{ dataSource: data, xName: 'country', yName: 'gold', name: 'Gold', fill: 'red', animation: { enable: false }, type: 'Column' }], legendSettings: { visible: false } }); chart.appendTo('#container'); unbindResizeEvents(chart); }); afterAll((): void => { chart.destroy(); ele.remove(); }); it('X axis ascending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Australia').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'USA').toBe(true); done(); }; chart.loaded = loaded; chart.series[0].dataSource = sort(data, ['country'], false); chart.refresh(); unbindResizeEvents(chart); }); it('X axis descending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'USA').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'Australia').toBe(true); done(); }; chart.loaded = loaded; chart.series[0].dataSource = sort(data, ['country'], true); chart.refresh(); }); it('Y axis ascending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Sweden').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'Japan').toBe(true); done(); }; chart.loaded = loaded; chart.series[0].dataSource = sort(data, ['gold'], false); chart.refresh(); }); it('Y axis descending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Japan').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'Sweden').toBe(true); done(); }; chart.loaded = loaded; chart.series[0].dataSource = sort(data, ['gold'], true); chart.refresh(); }); it('Multiple series x axis ascending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Australia').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'USA').toBe(true); done(); }; chart.loaded = loaded; chart.series = [ { dataSource: sort(data, ['country'], false), xName: 'country', yName: 'gold', name: 'Gold', fill: 'red', animation: { enable: false } }, { dataSource: sort(data, ['country'], false), xName: 'country', yName: 'gold1', name: 'Gold', fill: 'red', animation: { enable: false } } ]; chart.refresh(); }); it('Multiple series X axis descending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'USA').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'Australia').toBe(true); done(); }; chart.loaded = loaded; chart.series[0].dataSource = sort(data, ['country'], true); chart.refresh(); }); it('Multiple series y axis ascending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Sweden').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'Japan').toBe(true); done(); }; chart.loaded = loaded; chart.series[0].dataSource = sort(data, ['gold', 'gold1'], false); chart.refresh(); }); it('Multiple series Y axis descending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Japan').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'Sweden').toBe(true); done(); }; chart.loaded = loaded; chart.series[0].dataSource = sort(data, ['gold', 'gold1'], true); chart.refresh(); }); it('Stacking column series X axis ascending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Australia').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'USA').toBe(true); done(); }; chart.loaded = loaded; chart.series[0].type = 'StackingColumn'; chart.series[1].type = 'StackingColumn'; chart.series[0].dataSource = sort(data, ['country'], false); chart.refresh(); }); it('Stacking column series X axis descending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'USA').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'Australia').toBe(true); done(); }; chart.loaded = loaded; chart.series[0].dataSource = sort(data, ['country'], true); chart.refresh(); }); it('Stacking column series y axis ascending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Sweden').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'Japan').toBe(true); done(); }; chart.loaded = loaded; chart.series[0].dataSource = sort(data, ['gold', 'gold1'], false); chart.refresh(); }); it('Stacking column series Y axis descending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Japan').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'Sweden').toBe(true); done(); }; chart.loaded = loaded; chart.series[0].dataSource = sort(data, ['gold', 'gold1'], true); chart.refresh(); }); it('indexed category axis ascending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'Australia, Australia').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'USA, USA').toBe(true); done(); }; chart.loaded = loaded; chart.series[0].type = 'Column'; chart.series[1].type = 'Column'; chart.primaryXAxis.isIndexed = true; chart.series[0].dataSource = sort(data, ['country'], false); chart.refresh(); }); it('indexed category axis descending order', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container0_AxisLabel_0'); expect(svg.textContent == 'USA, Australia').toBe(true); svg = document.getElementById('container0_AxisLabel_7'); expect(svg.textContent == 'Australia, USA').toBe(true); done(); }; chart.loaded = loaded; chart.series[0].dataSource = sort(data, ['country'], true); chart.refresh(); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) });
the_stack
import { AppendCommand, BitCountCommand, BitOpCommand, BitPosCommand, CommandOptions, DBSizeCommand, DecrByCommand, DecrCommand, DelCommand, EchoCommand, EvalCommand, EvalshaCommand, ExistsCommand, ExpireAtCommand, ExpireCommand, FlushAllCommand, FlushDBCommand, GetBitCommand, GetCommand, GetRangeCommand, GetSetCommand, HDelCommand, HExistsCommand, HGetAllCommand, HGetCommand, HIncrByCommand, HIncrByFloatCommand, HKeysCommand, HLenCommand, HMGetCommand, HMSetCommand, HScanCommand, HSetCommand, HSetNXCommand, HStrLenCommand, HValsCommand, IncrByCommand, IncrByFloatCommand, IncrCommand, KeysCommand, LIndexCommand, LInsertCommand, LLenCommand, LPopCommand, LPushCommand, LPushXCommand, LRangeCommand, LRemCommand, LSetCommand, LTrimCommand, MGetCommand, MSetCommand, MSetNXCommand, PersistCommand, PExpireAtCommand, PExpireCommand, PingCommand, PSetEXCommand, PTtlCommand, PublishCommand, RandomKeyCommand, RenameCommand, RenameNXCommand, RPopCommand, RPushCommand, RPushXCommand, SAddCommand, ScanCommand, SCardCommand, ScoreMember, ScriptExistsCommand, ScriptFlushCommand, ScriptLoadCommand, SDiffCommand, SDiffStoreCommand, SetBitCommand, SetCommand, SetCommandOptions, SetExCommand, SetNxCommand, SetRangeCommand, SInterCommand, SInterStoreCommand, SIsMemberCommand, SMembersCommand, SMoveCommand, SPopCommand, SRandMemberCommand, SRemCommand, SScanCommand, StrLenCommand, SUnionCommand, SUnionStoreCommand, TimeCommand, TouchCommand, TtlCommand, TypeCommand, UnlinkCommand, ZAddCommand, ZAddCommandOptions, ZAddCommandOptionsWithIncr, ZCardCommand, ZCountCommand, ZIncrByCommand, ZInterStoreCommand, ZLexCountCommand, ZPopMaxCommand, ZPopMinCommand, ZRangeCommand, ZRangeCommandOptions, ZRankCommand, ZRemCommand, ZRemRangeByLexCommand, ZRemRangeByRankCommand, ZRemRangeByScoreCommand, ZRevRankCommand, ZScanCommand, ZScoreCommand, ZUnionStoreCommand, } from "./commands/mod.ts"; import { Requester } from "./http.ts"; import { Pipeline } from "./pipeline.ts"; import type { CommandArgs } from "./types.ts"; export type RedisOptions = { /** * Automatically try to deserialize the returned data from upstash using `JSON.deserialize` * * @default true */ automaticDeserialization?: boolean; }; /** * Serverless redis client for upstash. */ export class Redis { protected readonly client: Requester; protected opts?: CommandOptions<any, any>; /** * Create a new redis client * * @example * ```typescript * const redis = new Redis({ * url: "<UPSTASH_REDIS_REST_URL>", * token: "<UPSTASH_REDIS_REST_TOKEN>", * }); * ``` */ constructor(client: Requester, opts?: RedisOptions) { this.client = client; this.opts = opts; } /** * Create a new pipeline that allows you to send requests in bulk. * * @see {@link Pipeline} */ pipeline = () => new Pipeline(this.client, this.opts); /** * @see https://redis.io/commands/append */ append = (...args: CommandArgs<typeof AppendCommand>) => new AppendCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/bitcount */ bitcount = (...args: CommandArgs<typeof BitCountCommand>) => new BitCountCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/bitop */ bitop: { ( op: "and" | "or" | "xor", destinationKey: string, sourceKey: string, ...sourceKeys: string[] ): Promise<number>; (op: "not", destinationKey: string, sourceKey: string): Promise<number>; } = ( op: "and" | "or" | "xor" | "not", destinationKey: string, sourceKey: string, ...sourceKeys: string[] ) => new BitOpCommand( [op as any, destinationKey, sourceKey, ...sourceKeys], this.opts, ).exec(this.client); /** * @see https://redis.io/commands/bitpos */ bitpos = (...args: CommandArgs<typeof BitPosCommand>) => new BitPosCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/dbsize */ dbsize = () => new DBSizeCommand(this.opts).exec(this.client); /** * @see https://redis.io/commands/decr */ decr = (...args: CommandArgs<typeof DecrCommand>) => new DecrCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/decrby */ decrby = (...args: CommandArgs<typeof DecrByCommand>) => new DecrByCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/del */ del = (...args: CommandArgs<typeof DelCommand>) => new DelCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/echo */ echo = (...args: CommandArgs<typeof EchoCommand>) => new EchoCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/eval */ eval = <TArgs extends unknown[], TData = unknown>( ...args: [script: string, keys: string[], args: TArgs] ) => new EvalCommand<TArgs, TData>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/evalsha */ evalsha = <TArgs extends unknown[], TData = unknown>( ...args: [sha1: string, keys: string[], args: TArgs] ) => new EvalshaCommand<TArgs, TData>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/exists */ exists = (...args: CommandArgs<typeof ExistsCommand>) => new ExistsCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/expire */ expire = (...args: CommandArgs<typeof ExpireCommand>) => new ExpireCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/expireat */ expireat = (...args: CommandArgs<typeof ExpireAtCommand>) => new ExpireAtCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/flushall */ flushall = (args?: CommandArgs<typeof FlushAllCommand>) => new FlushAllCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/flushdb */ flushdb = (...args: CommandArgs<typeof FlushDBCommand>) => new FlushDBCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/get */ get = <TData>(...args: CommandArgs<typeof GetCommand>) => new GetCommand<TData>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/getbit */ getbit = (...args: CommandArgs<typeof GetBitCommand>) => new GetBitCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/getrange */ getrange = (...args: CommandArgs<typeof GetRangeCommand>) => new GetRangeCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/getset */ getset = <TData>(key: string, value: TData) => new GetSetCommand<TData>([key, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/hdel */ hdel = (...args: CommandArgs<typeof HDelCommand>) => new HDelCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hexists */ hexists = (...args: CommandArgs<typeof HExistsCommand>) => new HExistsCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hget */ hget = <TData>(...args: CommandArgs<typeof HGetCommand>) => new HGetCommand<TData>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hgetall */ hgetall = <TData extends Record<string, unknown>>( ...args: CommandArgs<typeof HGetAllCommand> ) => new HGetAllCommand<TData>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hincrby */ hincrby = (...args: CommandArgs<typeof HIncrByCommand>) => new HIncrByCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hincrbyfloat */ hincrbyfloat = (...args: CommandArgs<typeof HIncrByFloatCommand>) => new HIncrByFloatCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hkeys */ hkeys = (...args: CommandArgs<typeof HKeysCommand>) => new HKeysCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hlen */ hlen = (...args: CommandArgs<typeof HLenCommand>) => new HLenCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hmget */ hmget = <TData extends Record<string, unknown>>( ...args: CommandArgs<typeof HMGetCommand> ) => new HMGetCommand<TData>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hmset */ hmset = <TData>(key: string, kv: { [field: string]: TData }) => new HMSetCommand([key, kv], this.opts).exec(this.client); /** * @see https://redis.io/commands/hscan */ hscan = (...args: CommandArgs<typeof HScanCommand>) => new HScanCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hset */ hset = <TData>(key: string, kv: { [field: string]: TData }) => new HSetCommand<TData>([key, kv], this.opts).exec(this.client); /** * @see https://redis.io/commands/hsetnx */ hsetnx = <TData>(key: string, field: string, value: TData) => new HSetNXCommand<TData>([key, field, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/hstrlen */ hstrlen = (...args: CommandArgs<typeof HStrLenCommand>) => new HStrLenCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hvals */ hvals = (...args: CommandArgs<typeof HValsCommand>) => new HValsCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/incr */ incr = (...args: CommandArgs<typeof IncrCommand>) => new IncrCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/incrby */ incrby = (...args: CommandArgs<typeof IncrByCommand>) => new IncrByCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/incrbyfloat */ incrbyfloat = (...args: CommandArgs<typeof IncrByFloatCommand>) => new IncrByFloatCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/keys */ keys = (...args: CommandArgs<typeof KeysCommand>) => new KeysCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/lindex */ lindex = (...args: CommandArgs<typeof LIndexCommand>) => new LIndexCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/linsert */ linsert = <TData>( key: string, direction: "before" | "after", pivot: TData, value: TData, ) => new LInsertCommand<TData>([key, direction, pivot, value], this.opts).exec( this.client, ); /** * @see https://redis.io/commands/llen */ llen = (...args: CommandArgs<typeof LLenCommand>) => new LLenCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/lpop */ lpop = <TData>(...args: CommandArgs<typeof LPopCommand>) => new LPopCommand<TData>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/lpush */ lpush = <TData>(key: string, ...elements: TData[]) => new LPushCommand<TData>([key, ...elements], this.opts).exec(this.client); /** * @see https://redis.io/commands/lpushx */ lpushx = <TData>(key: string, ...elements: TData[]) => new LPushXCommand<TData>([key, ...elements], this.opts).exec(this.client); /** * @see https://redis.io/commands/lrange */ lrange = <TResult = string>(...args: CommandArgs<typeof LRangeCommand>) => new LRangeCommand<TResult>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/lrem */ lrem = <TData>(key: string, count: number, value: TData) => new LRemCommand([key, count, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/lset */ lset = <TData>(key: string, index: number, value: TData) => new LSetCommand([key, index, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/ltrim */ ltrim = (...args: CommandArgs<typeof LTrimCommand>) => new LTrimCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/mget */ mget = <TData extends unknown[]>(...args: CommandArgs<typeof MGetCommand>) => new MGetCommand<TData>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/mset */ mset = <TData>(kv: { [key: string]: TData }) => new MSetCommand<TData>([kv], this.opts).exec(this.client); /** * @see https://redis.io/commands/msetnx */ msetnx = <TData>(kv: { [key: string]: TData }) => new MSetNXCommand<TData>([kv], this.opts).exec(this.client); /** * @see https://redis.io/commands/persist */ persist = (...args: CommandArgs<typeof PersistCommand>) => new PersistCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/pexpire */ pexpire = (...args: CommandArgs<typeof PExpireCommand>) => new PExpireCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/pexpireat */ pexpireat = (...args: CommandArgs<typeof PExpireAtCommand>) => new PExpireAtCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/ping */ ping = (args?: CommandArgs<typeof PingCommand>) => new PingCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/psetex */ psetex = <TData>(key: string, ttl: number, value: TData) => new PSetEXCommand<TData>([key, ttl, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/pttl */ pttl = (...args: CommandArgs<typeof PTtlCommand>) => new PTtlCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/publish */ publish = (...args: CommandArgs<typeof PublishCommand>) => new PublishCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/randomkey */ randomkey = () => new RandomKeyCommand().exec(this.client); /** * @see https://redis.io/commands/rename */ rename = (...args: CommandArgs<typeof RenameCommand>) => new RenameCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/renamenx */ renamenx = (...args: CommandArgs<typeof RenameNXCommand>) => new RenameNXCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/rpop */ rpop = <TData = string>(...args: CommandArgs<typeof RPopCommand>) => new RPopCommand<TData>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/rpush */ rpush = <TData>(key: string, ...elements: TData[]) => new RPushCommand([key, ...elements], this.opts).exec(this.client); /** * @see https://redis.io/commands/rpushx */ rpushx = <TData>(key: string, ...elements: TData[]) => new RPushXCommand([key, ...elements], this.opts).exec(this.client); /** * @see https://redis.io/commands/sadd */ sadd = <TData>(key: string, ...members: TData[]) => new SAddCommand<TData>([key, ...members], this.opts).exec(this.client); /** * @see https://redis.io/commands/scan */ scan = (...args: CommandArgs<typeof ScanCommand>) => new ScanCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/scard */ scard = (...args: CommandArgs<typeof SCardCommand>) => new SCardCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/script-exists */ scriptExists = (...args: CommandArgs<typeof ScriptExistsCommand>) => new ScriptExistsCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/script-flush */ scriptFlush = (...args: CommandArgs<typeof ScriptFlushCommand>) => new ScriptFlushCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/script-load */ scriptLoad = (...args: CommandArgs<typeof ScriptLoadCommand>) => new ScriptLoadCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sdiff */ sdiff = (...args: CommandArgs<typeof SDiffCommand>) => new SDiffCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sdiffstore */ sdiffstore = (...args: CommandArgs<typeof SDiffStoreCommand>) => new SDiffStoreCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/set */ set = <TData>(key: string, value: TData, opts?: SetCommandOptions) => new SetCommand<TData>([key, value, opts], this.opts).exec(this.client); /** * @see https://redis.io/commands/setbit */ setbit = (...args: CommandArgs<typeof SetBitCommand>) => new SetBitCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/setex */ setex = <TData>(key: string, ttl: number, value: TData) => new SetExCommand<TData>([key, ttl, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/setnx */ setnx = <TData>(key: string, value: TData) => new SetNxCommand<TData>([key, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/setrange */ setrange = (...args: CommandArgs<typeof SetRangeCommand>) => new SetRangeCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sinter */ sinter = (...args: CommandArgs<typeof SInterCommand>) => new SInterCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sinterstore */ sinterstore = (...args: CommandArgs<typeof SInterStoreCommand>) => new SInterStoreCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sismember */ sismember = <TData>(key: string, member: TData) => new SIsMemberCommand<TData>([key, member], this.opts).exec(this.client); /** * @see https://redis.io/commands/smembers */ smembers = (...args: CommandArgs<typeof SMembersCommand>) => new SMembersCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/smove */ smove = <TData>(source: string, destination: string, member: TData) => new SMoveCommand<TData>([source, destination, member], this.opts).exec( this.client, ); /** * @see https://redis.io/commands/spop */ spop = <TData>(...args: CommandArgs<typeof SPopCommand>) => new SPopCommand<TData>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/srandmember */ srandmember = <TData>(...args: CommandArgs<typeof SRandMemberCommand>) => new SRandMemberCommand<TData>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/srem */ srem = <TData>(key: string, ...members: TData[]) => new SRemCommand<TData>([key, ...members], this.opts).exec(this.client); /** * @see https://redis.io/commands/sscan */ sscan = (...args: CommandArgs<typeof SScanCommand>) => new SScanCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/strlen */ strlen = (...args: CommandArgs<typeof StrLenCommand>) => new StrLenCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sunion */ sunion = (...args: CommandArgs<typeof SUnionCommand>) => new SUnionCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sunionstore */ sunionstore = (...args: CommandArgs<typeof SUnionStoreCommand>) => new SUnionStoreCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/time */ time = () => new TimeCommand().exec(this.client); /** * @see https://redis.io/commands/touch */ touch = (...args: CommandArgs<typeof TouchCommand>) => new TouchCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/ttl */ ttl = (...args: CommandArgs<typeof TtlCommand>) => new TtlCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/type */ type = (...args: CommandArgs<typeof TypeCommand>) => new TypeCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/unlink */ unlink = (...args: CommandArgs<typeof UnlinkCommand>) => new UnlinkCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zadd */ zadd = <TData>( ...args: | [ key: string, scoreMember: ScoreMember<TData>, ...scoreMemberPairs: ScoreMember<TData>[], ] | [ key: string, opts: ZAddCommandOptions | ZAddCommandOptionsWithIncr, ...scoreMemberPairs: [ScoreMember<TData>, ...ScoreMember<TData>[]], ] ) => { if ("score" in args[1]) { return new ZAddCommand<TData>( [args[0], args[1] as ScoreMember<TData>, ...(args.slice(2) as any)], this.opts, ).exec(this.client); } return new ZAddCommand<TData>( [args[0], args[1] as any, ...(args.slice(2) as any)], this.opts, ).exec(this.client); }; /** * @see https://redis.io/commands/zcard */ zcard = (...args: CommandArgs<typeof ZCardCommand>) => new ZCardCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zcount */ zcount = (...args: CommandArgs<typeof ZCountCommand>) => new ZCountCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zincrby */ zincrby = <TData>(key: string, increment: number, member: TData) => new ZIncrByCommand<TData>([key, increment, member], this.opts).exec( this.client, ); /** * @see https://redis.io/commands/zinterstore */ zinterstore = (...args: CommandArgs<typeof ZInterStoreCommand>) => new ZInterStoreCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zlexcount */ zlexcount = (...args: CommandArgs<typeof ZLexCountCommand>) => new ZLexCountCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zpopmax */ zpopmax = <TData>(...args: CommandArgs<typeof ZPopMaxCommand>) => new ZPopMaxCommand<TData>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zpopmin */ zpopmin = <TData>(...args: CommandArgs<typeof ZPopMinCommand>) => new ZPopMinCommand<TData>(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zrange */ zrange = <TData extends unknown[]>( ...args: | [key: string, min: number, max: number, opts?: ZRangeCommandOptions] | [ key: string, min: `(${string}` | `[${string}` | "-" | "+", max: `(${string}` | `[${string}` | "-" | "+", opts: { byLex: true } & ZRangeCommandOptions, ] | [ key: string, min: number | `(${number}` | "-inf" | "+inf", max: number | `(${number}` | "-inf" | "+inf", opts: { byScore: true } & ZRangeCommandOptions, ] ) => new ZRangeCommand<TData>(args as any, this.opts).exec(this.client); /** * @see https://redis.io/commands/zrank */ zrank = <TData>(key: string, member: TData) => new ZRankCommand<TData>([key, member], this.opts).exec(this.client); /** * @see https://redis.io/commands/zrem */ zrem = <TData>(key: string, ...members: TData[]) => new ZRemCommand<TData>([key, ...members], this.opts).exec(this.client); /** * @see https://redis.io/commands/zremrangebylex */ zremrangebylex = (...args: CommandArgs<typeof ZRemRangeByLexCommand>) => new ZRemRangeByLexCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zremrangebyrank */ zremrangebyrank = (...args: CommandArgs<typeof ZRemRangeByRankCommand>) => new ZRemRangeByRankCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zremrangebyscore */ zremrangebyscore = (...args: CommandArgs<typeof ZRemRangeByScoreCommand>) => new ZRemRangeByScoreCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zrevrank */ zrevrank = <TData>(key: string, member: TData) => new ZRevRankCommand<TData>([key, member], this.opts).exec(this.client); /** * @see https://redis.io/commands/zscan */ zscan = (...args: CommandArgs<typeof ZScanCommand>) => new ZScanCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zscore */ zscore = <TData>(key: string, member: TData) => new ZScoreCommand<TData>([key, member], this.opts).exec(this.client); /** * @see https://redis.io/commands/zunionstore */ zunionstore = (...args: CommandArgs<typeof ZUnionStoreCommand>) => new ZUnionStoreCommand(args, this.opts).exec(this.client); }
the_stack
import { ITokenService, IProfileProperties } from "@pnp/modern-search-extensibility"; import { ServiceKey, ServiceScope, Log, UrlQueryParameterCollection } from "@microsoft/sp-core-library"; import { PageContext } from '@microsoft/sp-page-context'; import { SPHttpClient } from '@microsoft/sp-http'; import { DateHelper } from "../../helpers/DateHelper"; import { Constants } from "../../common/Constants"; import { ObjectHelper } from "../../helpers/ObjectHelper"; const TokenService_ServiceKey = 'ModernSearchTokenService'; export enum BuiltinTokenNames { /** * The input query text configured in the search results Web Part */ inputQueryText = 'inputQueryText', /** * The current selected filters if any */ filters = 'filters' } export class TokenService implements ITokenService { /** * This regex only matches expressions enclosed with single, not escaped, curly braces '{}' */ private genericTokenRegexp: RegExp = /{[^\{]+?[^\\]}/gi; /** * The list of user properties. Used to avoid refetching it every time. */ private userProperties: IProfileProperties = null; /** * The current page item. Used to avoid refetching it every time. */ private currentPageItem: any = null; /** * The current service scope */ private serviceScope: ServiceScope; /** * The current page context */ private pageContext: PageContext; /** * The SPHttpClient instance */ private spHttpClient: SPHttpClient; /** * The list of static tokens values set by the Web Part as context */ private tokenValuesList: { [key: string]: any } = { [BuiltinTokenNames.inputQueryText]: undefined, [BuiltinTokenNames.filters]: {} }; /** * A date helper instance */ private dateHelper: DateHelper; /** * The moment.js library reference */ private moment: any; public static ServiceKey: ServiceKey<ITokenService> = ServiceKey.create(TokenService_ServiceKey, TokenService); public constructor(serviceScope: ServiceScope) { this.serviceScope = serviceScope; serviceScope.whenFinished(() => { this.dateHelper = serviceScope.consume<DateHelper>(DateHelper.ServiceKey); this.pageContext = serviceScope.consume<PageContext>(PageContext.serviceKey); this.spHttpClient = serviceScope.consume<SPHttpClient>(SPHttpClient.serviceKey); }); } public setTokenValue(token: string, value: any) { // Check if the token is in the whitelist if (Object.keys(this.tokenValuesList).indexOf(token) !== -1) { this.tokenValuesList[token] = value; } else { Log.warn(TokenService_ServiceKey, `The token '${token}' not allowed.`); } } public async resolveTokens(inputString: string): Promise<string> { if (inputString) { this.moment = await this.dateHelper.moment(); // Resolves dynamic tokens (i.e. tokens resolved asynchronously versus static ones set by the Web Part context) inputString = await this.replacePageTokens(inputString); inputString = await this.replaceUserTokens(inputString); inputString = this.replaceDateTokens(inputString); inputString = this.replaceQueryStringTokens(inputString); inputString = this.replaceWebTokens(inputString); inputString = this.replacePageContextTokens(inputString); inputString = this.replaceSiteTokens(inputString); inputString = this.replaceListTokens(inputString); inputString = this.replaceGroupTokens(inputString); inputString = this.replaceLegacyPageContextTokens(inputString); inputString = this.replaceOrOperator(inputString); inputString = await this.replaceHubTokens(inputString); inputString = inputString.replace(/\{TenantUrl\}/gi, `https://` + window.location.host); // Look for static tokens in the specified string const tokens = inputString.match(this.genericTokenRegexp); if (tokens !== null && tokens.length > 0) { tokens.forEach(token => { // Take the expression inside curly brackets const tokenName = token.substr(1).slice(0, -1); // Check if the property exists in the object // 'undefined' => token hasn't been initialized in the TokenService instance. We left the token expression untouched (ex: {token}). // 'null' => token has been initialized and set with a null value. We replace by an empty string as we don't want the string 'null' litterally. // '' (empty string) => replaced in the original string with an empty string as well. if (ObjectHelper.byPath(this.tokenValuesList, tokenName) !== undefined) { if (ObjectHelper.byPath(this.tokenValuesList, tokenName) !== null) { inputString = inputString.replace(new RegExp(token, 'gi'), ObjectHelper.byPath(this.tokenValuesList, tokenName)); } else { // If the property value is 'null', we replace by an empty string. 'null' means it has been already set but resolved as empty. inputString = inputString.replace(new RegExp(token, 'gi'), ''); } } }); } // Replace manually escaped characters inputString = inputString.replace(/\\(.)/gi, '$1'); } return inputString; } /** * Retrieves available current page item properties */ public async getPageProperties(): Promise<any> { let item = null; // Do this check to ensure we are not in the workbench if (this.pageContext.listItem) { const url = this.pageContext.web.absoluteUrl + `/_api/web/GetList(@v1)/RenderExtendedListFormData(itemId=${this.pageContext.listItem.id},formId='viewform',mode='2',options=7)?@v1='${this.pageContext.list.serverRelativeUrl}'`; try { const response = await this.spHttpClient.post(url, SPHttpClient.configurations.v1, { headers: { 'X-ClientService-ClientTag': Constants.X_CLIENTSERVICE_CLIENTTAG, 'UserAgent': Constants.X_CLIENTSERVICE_CLIENTTAG } }); if (response.ok) { let result = await response.json(); let itemRow = JSON.parse(result.value); // Lower case all properties // https://codereview.stackexchange.com/questions/162416/object-keys-to-lowercase item = Object.keys(itemRow.Data.Row[0]).reduce((c, k) => (c[k] = itemRow.Data.Row[0][k], c), {}); } else { throw response.statusText; } } catch (error) { const errorMessage = error ? error.message : `Failed to resolve page tokens`; Log.error(TokenService_ServiceKey, new Error(`Error: '${error}'`), this.serviceScope); throw new Error(errorMessage); } } return item; } /** * Retrieve all current user profile properties */ public async getUserProfileProperties(): Promise<IProfileProperties> { let responseJson = null; let userProperties: IProfileProperties = {}; const endpoint = `${this.pageContext.web.absoluteUrl}/_api/SP.UserProfiles.PeopleManager/GetMyProperties`; const response = await this.spHttpClient.get(endpoint, SPHttpClient.configurations.v1, { headers: { 'X-ClientService-ClientTag': Constants.X_CLIENTSERVICE_CLIENTTAG, 'UserAgent': Constants.X_CLIENTSERVICE_CLIENTTAG } }); if (response.ok) { responseJson = await response.json(); if (responseJson.UserProfileProperties) { responseJson.UserProfileProperties.forEach(property => { userProperties[property.Key.toLowerCase()] = property.Value; }); } return userProperties; } else { const errorMessage = `${TokenService_ServiceKey}: Error retrieving user profiel properties. Details: ${(response as any).statusMessage ? (response as any).statusMessage : response.status}`; const error = new Error(errorMessage); Log.error(TokenService_ServiceKey, error, this.serviceScope); throw error; } } /** * Resolve current page values from tokens * @param inputString the input string containing tokens */ private async replacePageTokens(inputString: string): Promise<string> { const pageTokenRegExp: RegExp = /\{(?:Page)\.(.*?)\}/gi; let matches = pageTokenRegExp.exec(inputString); let item = {}; // Make a check to the listItem property in the case we are in the hosted workbench if (matches != null && this.pageContext.listItem) { let pageItem = this.currentPageItem; if (!pageItem) { // Get page properties dymamically pageItem = await this.getPageProperties(); } let properties = Object.keys(pageItem); properties.forEach(property => { item[property] = pageItem[property]; }); item = this.recursivelyLowercaseJSONKeys(item); while (matches !== null && item != null) { const pageProperty = matches[1]; let itemProp: string = ''; // Return an empty string when not found instead of undefined since this value will be translated as text if (/\.Label|\.TermID/gi.test(pageProperty)) { let term = pageProperty.split("."); let columnName = term[0].toLowerCase(); let labelOrTermId = term[1].toLowerCase(); // Handle multi or single taxonomy values if (Array.isArray(item[columnName]) && item[columnName].length > 0) { // By convention, multi values should be separated by a comma, which is the default array delimiter for the array toString() method // This value could be processed in the replaceOrOperator() method so we need to keep the same delimiter convention itemProp = item[columnName].map(taxonomyValue => { return taxonomyValue[labelOrTermId]; // Use the 'TermId' or 'Label' properties }).join(','); } else if (!Array.isArray(item[columnName]) && item[columnName] !== undefined && item[columnName] !== "") { itemProp = item[columnName][labelOrTermId]; } } else { // Return the property as is itemProp = ObjectHelper.byPath(item, pageProperty.toLowerCase()); } inputString = inputString.replace(matches[0], itemProp); matches = pageTokenRegExp.exec(inputString); } } return inputString; } /** * Resolve current page context related tokens * @param inputString the input string containing tokens */ private replacePageContextTokens(inputString: string): string { const siteRegExp = /\{(?:PageContext)\.(.*?)\}/gi; let matches = siteRegExp.exec(inputString); if (matches != null) { while (matches !== null) { const prop = matches[1]; inputString = inputString.replace(new RegExp(matches[0], "gi"), this.pageContext ? ObjectHelper.byPath(this.pageContext, prop) : ''); matches = siteRegExp.exec(inputString); } } return inputString; } /** * Resolve current user property values from tokens * @param inputString the input string containing tokens */ private async replaceUserTokens(inputString: string): Promise<string> { const userTokenRegExp: RegExp = /\{(?:User)\.(.*?)\}/gi; let matches = userTokenRegExp.exec(inputString.toLowerCase()); // Browse matched tokens while (matches !== null) { let userProperty = matches[1].toLowerCase(); let propertyValue = null; // Check if other user profile properties have to be retrieved if (!/^(name|email)$/gi.test(userProperty)) { // Check if the user profile api was already called if (!this.userProperties) { this.userProperties = await this.getUserProfileProperties(); } propertyValue = this.userProperties[userProperty] ? this.userProperties[userProperty] : ''; } else { switch (userProperty) { case "email": propertyValue = this.pageContext.user.email; break; case "name": propertyValue = this.pageContext.user.displayName; break; default: propertyValue = this.pageContext.user.displayName; break; } } const tokenExprToReplace = new RegExp(matches[0], 'gi'); // Replace the match with the property value inputString = inputString.replace(tokenExprToReplace, propertyValue); // Look for other tokens matches = userTokenRegExp.exec(inputString); } inputString = inputString.replace(new RegExp("\{Me\}", 'gi'), this.pageContext.user.displayName); return inputString; } /** * Resolve date related tokens * @param inputString the input string containing tokens */ private replaceDateTokens(inputString: string): string { const currentDate = /\{CurrentDate\}/gi; const currentMonth = /\{CurrentMonth\}/gi; const currentYear = /\{CurrentYear\}/gi; // Replaces any "{Today} +/- [digit]" expression let results = /\{Today\s*[\+-]\s*\[{0,1}\d{1,}\]{0,1}\}/gi; let match; while ((match = results.exec(inputString)) !== null) { for (let result of match) { const operator = result.indexOf('+') !== -1 ? '+' : '-'; const addOrRemove = operator == '+' ? 1 : -1; const operatorSplit = result.split(operator); const digit = parseInt(operatorSplit[operatorSplit.length - 1].replace("{", "").replace("}", "").trim()) * addOrRemove; let dt = new Date(); dt.setDate(dt.getDate() + digit); const formatDate = this.moment(dt).format("YYYY-MM-DDTHH:mm:ss\\Z"); inputString = inputString.replace(result, formatDate); } } // Replaces any "{Today}" expression by it's actual value let formattedDate = this.moment(new Date()).format("YYYY-MM-DDTHH:mm:ss\\Z"); inputString = inputString.replace(new RegExp("{Today}", 'gi'), formattedDate); const d = new Date(); inputString = inputString.replace(currentDate, d.getDate().toString()); inputString = inputString.replace(currentMonth, (d.getMonth() + 1).toString()); inputString = inputString.replace(currentYear, d.getFullYear().toString()); return inputString; } /** * Resolve query string related tokens * @param inputString the input string containing tokens */ private replaceQueryStringTokens(inputString: string) { const webRegExp = /\{(?:QueryString)\.(.*?)\}/gi; let modifiedString = inputString; let matches = webRegExp.exec(inputString); if (matches != null) { const queryParameters = new UrlQueryParameterCollection(window.location.href); while (matches !== null) { const qsProp = matches[1]; const itemProp = decodeURIComponent(queryParameters.getValue(qsProp) || ""); modifiedString = modifiedString.replace(new RegExp(matches[0], "gi"), itemProp); matches = webRegExp.exec(inputString); } } return modifiedString; } /** * Resolve current web related tokens * @param inputString the input string containing tokens */ private replaceWebTokens(inputString: string): string { const queryStringVariables = /\{(?:Web)\.(.*?)\}/gi; let matches = queryStringVariables.exec(inputString); if (matches != null) { while (matches !== null) { const webProp = matches[1]; inputString = inputString.replace(new RegExp(matches[0], "gi"), this.pageContext.web ? this.pageContext.web[webProp] : ''); matches = queryStringVariables.exec(inputString); } } return inputString; } /** * Resolve current site related tokens * @param inputString the input string containing tokens */ private replaceSiteTokens(inputString: string): string { const siteRegExp = /\{(?:Site)\.(.*?)\}/gi; let matches = siteRegExp.exec(inputString); if (matches != null) { while (matches !== null) { const siteProp = matches[1]; inputString = inputString.replace(new RegExp(matches[0], "gi"), this.pageContext.site ? ObjectHelper.byPath(this.pageContext.site, siteProp) : ''); matches = siteRegExp.exec(inputString); } } return inputString; } /** * Resolve current hub site related tokens * @param inputString the input string containing tokens */ private async replaceHubTokens(inputString: string): Promise<string> { const hubRegExp = /\{(?:Hub)\.(.*?)\}/gi; let matches = hubRegExp.exec(inputString); // Get hub info const hubInfos = await this.getHubInfo(); if (matches != null && hubInfos) { while (matches !== null) { const hubProp = matches[1]; inputString = inputString.replace(new RegExp(matches[0], "gi"), hubInfos[hubProp]); matches = hubRegExp.exec(inputString); } } return inputString; } /** * Resolve current Office 365 group related tokens * @param inputString the input string containing tokens */ private replaceGroupTokens(inputString: string): string { const groupRegExp = /\{(?:Group)\.(.*?)\}/gi; let matches = groupRegExp.exec(inputString); if (matches != null) { while (matches !== null) { const groupProp = matches[1]; inputString = inputString.replace(new RegExp(matches[0], "gi"), this.pageContext.site.group ? ObjectHelper.byPath(this.pageContext.site.group, groupProp) : ''); matches = groupRegExp.exec(inputString); } } return inputString; } /** * Resolve current list related tokens * @param inputString the input string containing tokens */ private replaceListTokens(inputString: string): string { const listRegExp = /\{(?:List)\.(.*?)\}/gi; let matches = listRegExp.exec(inputString); if (matches != null) { while (matches !== null) { const listProp = matches[1]; inputString = inputString.replace(new RegExp(matches[0], "gi"), this.pageContext.list ? ObjectHelper.byPath(this.pageContext.list, listProp) : ''); matches = listRegExp.exec(inputString); } } return inputString; } /** * Resolve legacy page tokens * @param inputString the input string containing tokens */ private replaceLegacyPageContextTokens(inputString: string): string { const legacyPageContextRegExp = /\{(?:LegacyPageContext)\.(.*?)\}/gi; let matches = legacyPageContextRegExp.exec(inputString); if (matches != null) { while (matches !== null) { const legacyProp = matches[1]; inputString = inputString.replace(new RegExp(matches[0], "gi"), this.pageContext.legacyPageContext ? ObjectHelper.byPath(this.pageContext.legacyPageContext, legacyProp) : ''); matches = legacyPageContextRegExp.exec(inputString); } } return inputString; } private replaceOrOperator(inputString: string) { // Example match: {|owstaxidmetadataalltagsinfo:{Page.<TaxnomyProperty>.TermID}} const orConditionTokens = /\{(?:\|(.+?)(>=|=|<=|:|<>|<|>))(\{?.*?\}?\s*)\}/gi; let reQueryTemplate = inputString; let match = orConditionTokens.exec(inputString); if (match != null) { while (match !== null) { let conditions = []; const property = match[1]; const operator = match[2]; const tokenValue = match[3]; // {User} tokens are resolved server-side by SharePoint so we exclude them if (!/\{(?:User)\.(.*?)\}/gi.test(tokenValue)) { const allValues = tokenValue.split(','); // Works with taxonomy multi values (TermID, Label) + multi choices fields if (allValues.length > 0) { allValues.forEach(value => { conditions.push(`(${property}${operator}${/\s/g.test(value) ? `"${value}"` : value})`); }); } else { conditions.push(`${property}${operator}${/\s/g.test(tokenValue) ? `"${tokenValue}"` : tokenValue})`); } inputString = inputString.replace(match[0], `(${conditions.join(' OR ')})`); } match = orConditionTokens.exec(reQueryTemplate); } } return inputString; } /** * Get hub site data */ public async getHubInfo(): Promise<any> { try { const restUrl = `${this.pageContext.site.absoluteUrl}/_api/site?$select=IsHubSite,HubSiteId,Id`; const data = await this.spHttpClient.get(restUrl, SPHttpClient.configurations.v1, { headers: { 'X-ClientService-ClientTag': Constants.X_CLIENTSERVICE_CLIENTTAG, 'UserAgent': Constants.X_CLIENTSERVICE_CLIENTTAG } }); if (data && data.ok) { const jsonData = await data.json(); if (jsonData) { return jsonData; } } return null; } catch (error) { Log.error(TokenService_ServiceKey, new Error(`Error while fetching Hub site data. Details: ${error}`), this.serviceScope); return null; } } /** * Recursively lower case object keys * https://github.com/Vin65/recursive-lowercase-json/blob/master/src/index.js * @param obj the JSON object */ private recursivelyLowercaseJSONKeys(obj) { const copyOfObj = obj; if (typeof copyOfObj !== 'object' || copyOfObj === null) { return copyOfObj; } if (Array.isArray(copyOfObj)) { return copyOfObj.map(o => this.recursivelyLowercaseJSONKeys(o)); } return Object.keys(copyOfObj).reduce((prev, curr) => { prev[curr.toLowerCase()] = this.recursivelyLowercaseJSONKeys(copyOfObj[curr]); return prev; }, {}); } }
the_stack
import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, HostBinding, HostListener, Inject, Input, NgZone, OnChanges, OnDestroy, OnInit, Output, PLATFORM_ID, SimpleChange, SimpleChanges } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; import { Subject, timer } from 'rxjs'; import { filter, map, switchMap, takeUntil } from 'rxjs/operators'; import { AccessibleComponent } from '../accessible.component'; import { AccessibilityConfig } from '../../model/accessibility.interface'; import { Image, ImageEvent } from '../../model/image.class'; import { Action } from '../../model/action.enum'; import { getIndex } from '../../utils/image.util'; import { NEXT, PREV } from '../../utils/user-input.util'; import { DescriptionStrategy } from '../../model/description.interface'; import { DotsConfig } from '../../model/dots-config.interface'; import { KS_DEFAULT_ACCESSIBILITY_CONFIG } from '../accessibility-default'; import { PlayConfig } from '../../model/play-config.interface'; import { CarouselConfig } from '../../model/carousel-config.interface'; import { CarouselImageConfig } from '../../model/carousel-image-config.interface'; import { DomSanitizer, SafeStyle } from '@angular/platform-browser'; import { CarouselPreviewConfig } from '../../model/carousel-preview-config.interface'; import { ConfigService } from '../../services/config.service'; import { ModalGalleryService } from '../modal-gallery/modal-gallery.service'; import { LibConfig } from '../../model/lib-config.interface'; import { ModalGalleryConfig } from '../../model/modal-gallery-config.interface'; import { KeyboardServiceConfig } from '../../model/keyboard-service-config.interface'; /** * Component with configurable inline/plain carousel. */ @Component({ selector: 'ks-carousel', styleUrls: ['carousel.scss', '../image-arrows.scss'], templateUrl: 'carousel.html', changeDetection: ChangeDetectionStrategy.OnPush, providers: [ConfigService] }) export class CarouselComponent extends AccessibleComponent implements OnInit, AfterContentInit, OnDestroy, OnChanges { /** * Attribute to set ariaLabel of the host component */ @HostBinding('attr.aria-label') ariaLabel = `Carousel`; /** * Unique id (>=0) of the current instance of the carousel. This is useful when you are using * the carousel's feature to open modal gallery. */ @Input() id: number | undefined; /** * Array of `InternalLibImage` that represent the model of this library with all images, * thumbs and so on. */ @Input() images: Image[] = []; /** * Object of type `CarouselConfig` to init CarouselComponent's features. * For instance, it contains parameters to change the style, how it navigates and so on. */ @Input() carouselConfig: CarouselConfig | undefined; /** * Object of type `PlayConfig` to init CarouselComponent's features about auto-play. * For instance, it contains parameters to enable/disable autoPlay, interval and so on. */ @Input() playConfig: PlayConfig | undefined; /** * Interface to configure current image in carousel. * For instance you can change the description. */ @Input() carouselImageConfig: CarouselImageConfig | undefined; /** * Object of type `CarouselPreviewConfig` to init PreviewsComponent's features. * For instance, it contains a param to show/hide previews, change sizes and so on. */ @Input() previewConfig: CarouselPreviewConfig | undefined; /** * Object of type `DotsConfig` to init DotsComponent's features. * For instance, it contains a param to show/hide this component. */ @Input() dotsConfig: DotsConfig | undefined; /** * boolean to enable/disable infinite sliding. Enabled by default. */ @Input() infinite = true; /** * TODO add description */ @Input() disableSsrWorkaround = false; /** * Object of type `AccessibilityConfig` to init custom accessibility features. * For instance, it contains titles, alt texts, aria-labels and so on. */ @Input() accessibilityConfig: AccessibilityConfig | undefined; /** * Output to emit an event when an image is changed. */ @Output() showImage: EventEmitter<ImageEvent> = new EventEmitter<ImageEvent>(); /** * Output to emit an event when the current image is the first one. */ @Output() firstImage: EventEmitter<ImageEvent> = new EventEmitter<ImageEvent>(); /** * Output to emit an event when the current image is the last one. */ @Output() lastImage: EventEmitter<ImageEvent> = new EventEmitter<ImageEvent>(); /** * Object use in template */ configCarousel: CarouselConfig | undefined; /** * Object use in template */ configPlay: PlayConfig | undefined; /** * Object use in template */ configCarouselImage: CarouselImageConfig | undefined; /** * Object use in template */ configPreview: CarouselPreviewConfig | undefined; /** * Object use in template */ configDots: DotsConfig | undefined; /** * Object use in template */ configAccessibility: AccessibilityConfig = KS_DEFAULT_ACCESSIBILITY_CONFIG; /** * Enum of type `Action` that represents a mouse click on a button. * Declared here to be used inside the template. */ clickAction: Action = Action.CLICK; /** * Enum of type `Action` that represents a keyboard action. * Declared here to be used inside the template. */ keyboardAction: Action = Action.KEYBOARD; /** * `Image` that is visible right now. */ currentImage: Image | undefined; /** * Boolean that it's true when you are watching the first image (currently visible). * False by default */ isFirstImage = false; /** * Boolean that it's true when you are watching the last image (currently visible). * False by default */ isLastImage = false; /** * Subject to play the carousel. */ private start$ = new Subject<void>(); /** * Subject to stop the carousel. */ private stop$ = new Subject<void>(); /** * Private object without type to define all swipe actions used by hammerjs. */ private SWIPE_ACTION = { LEFT: 'swipeleft', RIGHT: 'swiperight', UP: 'swipeup', DOWN: 'swipedown' }; /** * Listener to stop the gallery when the mouse pointer is over the current image. */ @HostListener('mouseenter') onMouseEnter(): void { if (this.id === null || this.id === undefined) { throw new Error('Internal library error - id must be defined'); } const libConfig: LibConfig | undefined = this.configService.getConfig(this.id); if (!libConfig) { throw new Error('Internal library error - libConfig must be defined'); } if (!libConfig.carouselPlayConfig || !libConfig.carouselPlayConfig.pauseOnHover) { return; } this.stopCarousel(); } /** * Listener to play the gallery when the mouse pointer leave the current image. */ @HostListener('mouseleave') onMouseLeave(): void { if (this.id === null || this.id === undefined) { throw new Error('Internal library error - id must be defined'); } const libConfig: LibConfig | undefined = this.configService.getConfig(this.id); if (!libConfig) { throw new Error('Internal library error - libConfig must be defined'); } if (!libConfig.carouselPlayConfig || !libConfig.carouselPlayConfig.pauseOnHover || !libConfig.carouselPlayConfig.autoPlay) { return; } this.playCarousel(); } /** * Listener to navigate carousel images with keyboard (left). */ @HostListener('keydown.arrowLeft') onKeyDownLeft(): void { if (this.id === null || this.id === undefined) { throw new Error('Internal library error - id must be defined'); } const libConfig: LibConfig | undefined = this.configService.getConfig(this.id); if (!libConfig) { throw new Error('Internal library error - libConfig must be defined'); } if (!libConfig.carouselConfig || !libConfig.carouselConfig.keyboardEnable) { return; } this.prevImage(); } /** * Listener to navigate carousel images with keyboard (right). */ @HostListener('keydown.arrowRight') onKeyDownLRight(): void { if (this.id === null || this.id === undefined) { throw new Error('Internal library error - id must be defined'); } const libConfig: LibConfig | undefined = this.configService.getConfig(this.id); if (!libConfig) { throw new Error('Internal library error - libConfig must be defined'); } if (!libConfig.carouselConfig || !libConfig.carouselConfig.keyboardEnable) { return; } this.nextImage(); } constructor( // tslint:disable-next-line:no-any @Inject(PLATFORM_ID) private platformId: any, private ngZone: NgZone, private modalGalleryService: ModalGalleryService, private configService: ConfigService, private ref: ChangeDetectorRef, // sanitizer is used only to sanitize style before add it to background property when legacyIE11Mode is enabled private sanitizer: DomSanitizer ) { super(); } ngOnChanges(changes: SimpleChanges): void { if (this.id === null || this.id === undefined) { throw new Error('Internal library error - id must be defined'); } const libConfig: LibConfig | undefined = this.configService.getConfig(this.id); if (!libConfig) { throw new Error('Internal library error - libConfig must be defined'); } // handle changes of dotsConfig const configDotsChange: SimpleChange = changes.dotsConfig; if (configDotsChange && configDotsChange.currentValue !== configDotsChange.previousValue) { this.configService.setConfig(this.id, { carouselDotsConfig: configDotsChange.currentValue }); this.configDots = libConfig.carouselDotsConfig; } // handle changes of carouselConfig const carouselConfigChange: SimpleChange = changes.carouselConfig; if (carouselConfigChange && carouselConfigChange.currentValue !== carouselConfigChange.previousValue) { this.configService.setConfig(this.id, { carouselConfig: carouselConfigChange.currentValue }); this.configCarousel = carouselConfigChange.currentValue; } // handle changes of playConfig starting/stopping the carousel accordingly const playConfigChange: SimpleChange = changes.playConfig; if (playConfigChange) { const playConfigChangePrev: PlayConfig = playConfigChange.previousValue; const playConfigChangeCurr: PlayConfig = playConfigChange.currentValue; if (playConfigChangePrev !== playConfigChangeCurr) { this.configService.setConfig(this.id, { carouselPlayConfig: playConfigChange.currentValue }); // this.configPlay = playConfigChange.currentValue; // if autoplay is enabled, and this is not the // first change (to prevent multiple starts at the beginning) if (playConfigChangeCurr.autoPlay && !playConfigChange.isFirstChange()) { this.start$.next(); } else { this.stopCarousel(); } } } } ngOnInit(): void { if (this.id === null || this.id === undefined) { throw new Error('Internal library error - id must be defined'); } if (!this.images) { throw new Error('Internal library error - images must be defined'); } const libConfig: LibConfig | undefined = this.configService.getConfig(this.id); if (!libConfig) { throw new Error('Internal library error - libConfig must be defined'); } this.currentImage = this.images[0]; this.configService.setConfig(this.id, { carouselConfig: this.carouselConfig, carouselImageConfig: this.carouselImageConfig, carouselPlayConfig: this.playConfig, carouselPreviewsConfig: this.previewConfig, carouselDotsConfig: this.dotsConfig, accessibilityConfig: this.accessibilityConfig, // this custom config with 'disableSsrWorkaround: true' is required in case of SystemJS keyboardServiceConfig: { shortcuts: ['ctrl+s', 'meta+s'], disableSsrWorkaround: this.disableSsrWorkaround } }); this.configCarousel = libConfig.carouselConfig; this.configCarouselImage = libConfig.carouselImageConfig; this.configPlay = libConfig.carouselPlayConfig; this.configPreview = libConfig.carouselPreviewsConfig; this.configDots = libConfig.carouselDotsConfig; this.configAccessibility = libConfig.accessibilityConfig as AccessibilityConfig; this.manageSlideConfig(); } ngAfterContentInit(): void { // interval doesn't play well with SSR and protractor, // so we should run it in the browser and outside Angular if (isPlatformBrowser(this.platformId)) { if (this.id === null || this.id === undefined) { throw new Error('Internal library error - id must be defined'); } const libConfig: LibConfig | undefined = this.configService.getConfig(this.id); if (!libConfig || !libConfig.carouselPlayConfig) { throw new Error('Internal library error - libConfig and carouselPlayConfig must be defined'); } this.ngZone.runOutsideAngular(() => { this.start$ .pipe( map(() => libConfig && libConfig.carouselPlayConfig && libConfig.carouselPlayConfig.interval), // tslint:disable-next-line:no-any filter((interval: any) => interval > 0), switchMap(interval => timer(interval).pipe(takeUntil(this.stop$))) ) .subscribe(() => this.ngZone.run(() => { if (this.configPlay && this.configPlay.autoPlay) { this.nextImage(); } this.ref.markForCheck(); }) ); this.start$.next(); }); } } /** * Method used in template to sanitize an url when you need legacyIE11Mode. * In this way you can set an url as background of a div. * @param unsafeStyle is a string and represents the url to sanitize. * @param unsafeStyleFallback is a string and represents the fallback url to sanitize. * @returns a SafeStyle object that can be used in template without problems. */ sanitizeUrlBgStyle(unsafeStyle: string, unsafeStyleFallback: string): SafeStyle { // Method used only to sanitize background-image style before add it to background property when legacyIE11Mode is enabled let bg: string = 'url(' + unsafeStyle + ')'; if (!!unsafeStyleFallback) { // if a fallback image is defined, append it. In this way, it will be used by the browser as fallback. bg += ', ' + 'url(' + unsafeStyleFallback + ')'; } return this.sanitizer.bypassSecurityTrustStyle(bg); } /** * Method called when a dot is clicked and used to update the current image. * @param number index of the clicked dot */ onClickDot(index: number): void { this.changeCurrentImage(this.images[index], Action.NORMAL); } /** * Method called by events from both keyboard and mouse on a navigation arrow. * @param string direction of the navigation that can be either 'next' or 'prev' * @param KeyboardEvent | MouseEvent event payload * @param Action action that triggered the event or `Action.NORMAL` if not provided */ onNavigationEvent(direction: string, event: KeyboardEvent | MouseEvent, action: Action = Action.NORMAL): void { const result: number = super.handleNavigationEvent(direction, event); if (result === NEXT) { this.nextImage(action); } else if (result === PREV) { this.prevImage(action); } } /** * Method triggered when you click on the current image. * Also, if modalGalleryEnable is true, you can open the modal-gallery. */ onClickCurrentImage(): void { if (this.id === null || this.id === undefined) { throw new Error('Internal library error - id must be defined'); } const libConfig: LibConfig | undefined = this.configService.getConfig(this.id); if (!libConfig || !libConfig.carouselConfig || !this.currentImage) { throw new Error('Internal library error - libConfig, carouselConfig and currentImage must be defined'); } if (!libConfig.carouselConfig.modalGalleryEnable) { return; } const index = getIndex(this.currentImage, this.images); this.modalGalleryService.open({ id: this.id, images: this.images, currentImage: this.images[index], libConfig: { // this custom config with 'disableSsrWorkaround: true' is required in case of SystemJS keyboardServiceConfig: { shortcuts: ['ctrl+s', 'meta+s'], disableSsrWorkaround: this.disableSsrWorkaround } as KeyboardServiceConfig } as LibConfig } as ModalGalleryConfig); } /** * Method to get the image description based on input params. * If you provide a full description this will be the visible description, otherwise, * it will be built using the `Description` object, concatenating its fields. * @param Image image to get its description. If not provided it will be the current image * @returns String description of the image (or the current image if not provided) * @throws an Error if description isn't available */ getDescriptionToDisplay(image: Image | undefined = this.currentImage): string { if (this.id === null || this.id === undefined) { throw new Error('Internal library error - id must be defined'); } const libConfig: LibConfig | undefined = this.configService.getConfig(this.id); if (!libConfig) { throw new Error('Internal library error - libConfig must be defined'); } const configCurrentImageCarousel: CarouselImageConfig | undefined = libConfig.carouselImageConfig; if (!configCurrentImageCarousel || !configCurrentImageCarousel.description) { throw new Error('Description input must be a valid object implementing the Description interface'); } if (!image) { throw new Error('Internal library error - image must be defined'); } const imageWithoutDescription: boolean = !image || !image.modal || !image.modal.description || image.modal.description === ''; switch (configCurrentImageCarousel.description.strategy) { case DescriptionStrategy.HIDE_IF_EMPTY: return imageWithoutDescription ? '' : image.modal.description + ''; case DescriptionStrategy.ALWAYS_HIDDEN: return ''; default: // ----------- DescriptionStrategy.ALWAYS_VISIBLE ----------------- return this.buildTextDescription(image, imageWithoutDescription); } } /** * Method used by Hammerjs to support touch gestures (you can also invert the swipe direction with configCurrentImage.invertSwipe). * @param action String that represent the direction of the swipe action. 'swiperight' by default. */ swipe(action = this.SWIPE_ACTION.RIGHT): void { if (this.id === null || this.id === undefined) { throw new Error('Internal library error - id must be defined'); } const libConfig: LibConfig | undefined = this.configService.getConfig(this.id); if (!libConfig || !libConfig.carouselImageConfig) { throw new Error('Internal library error - libConfig and carouselImageConfig must be defined'); } const configCurrentImageCarousel: CarouselImageConfig = libConfig.carouselImageConfig; switch (action) { case this.SWIPE_ACTION.RIGHT: if (configCurrentImageCarousel.invertSwipe) { this.prevImage(Action.SWIPE); } else { this.nextImage(Action.SWIPE); } break; case this.SWIPE_ACTION.LEFT: if (configCurrentImageCarousel.invertSwipe) { this.nextImage(Action.SWIPE); } else { this.prevImage(Action.SWIPE); } break; // case this.SWIPE_ACTION.UP: // break; // case this.SWIPE_ACTION.DOWN: // break; } } /** * Method to go back to the previous image. * @param action Enum of type `Action` that represents the source * action that moved back to the previous image. `Action.NORMAL` by default. */ prevImage(action: Action = Action.NORMAL): void { // check if prevImage should be blocked if (this.isPreventSliding(0)) { return; } this.changeCurrentImage(this.getPrevImage(), action); this.manageSlideConfig(); this.start$.next(); } /** * Method to go back to the previous image. * @param action Enum of type `Action` that represents the source * action that moved to the next image. `Action.NORMAL` by default. */ nextImage(action: Action = Action.NORMAL): void { // check if nextImage should be blocked if (this.isPreventSliding(this.images.length - 1)) { return; } this.changeCurrentImage(this.getNextImage(), action); this.manageSlideConfig(); this.start$.next(); } /** * Method used in the template to track ids in ngFor. * @param number index of the array * @param Image item of the array * @returns number the id of the item */ trackById(index: number, item: Image): number { return item.id; } /** * Method called when an image preview is clicked and used to update the current image. * @param event an ImageEvent object with the relative action and the index of the clicked preview. */ onClickPreview(event: ImageEvent): void { const imageFound: Image = this.images[event.result as number]; if (!!imageFound) { this.manageSlideConfig(); this.changeCurrentImage(imageFound, event.action); } } /** * Method to play carousel. */ playCarousel(): void { this.start$.next(); } /** * Stops the carousel from cycling through items. */ stopCarousel(): void { this.stop$.next(); } // TODO remove this because duplicated /** * Method to get `alt attribute`. * `alt` specifies an alternate text for an image, if the image cannot be displayed. * @param Image image to get its alt description. If not provided it will be the current image * @returns String alt description of the image (or the current image if not provided) */ getAltDescriptionByImage(image: Image | undefined = this.currentImage): string { if (!image) { return ''; } return image.modal && image.modal.description ? image.modal.description : `Image ${getIndex(image, this.images) + 1}`; } // TODO remove this because duplicated /** * Method to get the title attributes based on descriptions. * This is useful to prevent accessibility issues, because if DescriptionStrategy is ALWAYS_HIDDEN, * it prevents an empty string as title. * @param Image image to get its description. If not provided it will be the current image * @returns String title of the image based on descriptions * @throws an Error if description isn't available */ getTitleToDisplay(image: Image | undefined = this.currentImage): string { if (this.id === null || this.id === undefined) { throw new Error('Internal library error - id must be defined'); } const libConfig: LibConfig | undefined = this.configService.getConfig(this.id); if (!libConfig || !libConfig.carouselImageConfig) { throw new Error('Internal library error - libConfig and carouselImageConfig must be defined'); } const configCurrentImageCarousel: CarouselImageConfig = libConfig.carouselImageConfig; if (!configCurrentImageCarousel || !configCurrentImageCarousel.description) { throw new Error('Description input must be a valid object implementing the Description interface'); } const imageWithoutDescription: boolean = !image || !image.modal || !image.modal.description || image.modal.description === ''; const description: string = this.buildTextDescription(image, imageWithoutDescription); return description; } /** * Method to reset carousel (force image with index 0 to be the current image and re-init also previews) */ // temporary removed because never tested // reset() { // if (this.configPlay && this.configPlay.autoPlay) { // this.stopCarousel(); // } // this.currentImage = this.images[0]; // this.handleBoundaries(0); // if (this.configPlay && this.configPlay.autoPlay) { // this.playCarousel(); // } // this.ref.markForCheck(); // } /** * Method to cleanup resources. In fact, this will stop the carousel. * This is an Angular's lifecycle hook that is called when this component is destroyed. */ ngOnDestroy(): void { this.stopCarousel(); } /** * Method to change the current image, receiving the new image as input the relative action. * @param image an Image object that represents the new image to set as current. * @param action Enum of type `Action` that represents the source action that triggered the change. */ private changeCurrentImage(image: Image, action: Action): void { if (this.id === null || this.id === undefined) { throw new Error('Internal library error - id must be defined'); } this.currentImage = image; const index: number = getIndex(image, this.images); // emit first/last event based on newIndex value this.emitBoundaryEvent(action, index); // emit current visible image index this.showImage.emit(new ImageEvent(this.id, action, index + 1)); } /** * Private method to get the next index. * This is necessary because at the end, when you call next again, you'll go to the first image. * That happens because all modal images are shown like in a circle. */ private getNextImage(): Image { if (!this.currentImage) { throw new Error('Internal library error - currentImage must be defined'); } const currentIndex: number = getIndex(this.currentImage, this.images); let newIndex = 0; if (currentIndex >= 0 && currentIndex < this.images.length - 1) { newIndex = currentIndex + 1; } else { newIndex = 0; // start from the first index } return this.images[newIndex]; } /** * Private method to get the previous index. * This is necessary because at index 0, when you call prev again, you'll go to the last image. * That happens because all modal images are shown like in a circle. */ private getPrevImage(): Image { if (!this.currentImage) { throw new Error('Internal library error - currentImage must be defined'); } const currentIndex: number = getIndex(this.currentImage, this.images); let newIndex = 0; if (currentIndex > 0 && currentIndex <= this.images.length - 1) { newIndex = currentIndex - 1; } else { newIndex = this.images.length - 1; // start from the last index } return this.images[newIndex]; } /** * Private method to build a text description. * This is used also to create titles. * @param Image image to get its description. If not provided it will be the current image. * @param boolean imageWithoutDescription is a boolean that it's true if the image hasn't a 'modal' description. * @returns String description built concatenating image fields with a specific logic. */ private buildTextDescription(image: Image | undefined, imageWithoutDescription: boolean): string { if (this.id === null || this.id === undefined) { throw new Error('Internal library error - id must be defined'); } const libConfig: LibConfig | undefined = this.configService.getConfig(this.id); if (!libConfig || !libConfig.carouselImageConfig) { throw new Error('Internal library error - libConfig and carouselImageConfig must be defined'); } const configCurrentImageCarousel: CarouselImageConfig | undefined = libConfig.carouselImageConfig; if (!configCurrentImageCarousel || !configCurrentImageCarousel.description) { throw new Error('Description input must be a valid object implementing the Description interface'); } if (!image) { throw new Error('Internal library error - image must be defined'); } // If customFullDescription use it, otherwise proceed to build a description if (configCurrentImageCarousel.description.customFullDescription && configCurrentImageCarousel.description.customFullDescription !== '') { return configCurrentImageCarousel.description.customFullDescription; } const currentIndex: number = getIndex(image, this.images); // If the current image hasn't a description, // prevent to write the ' - ' (or this.description.beforeTextDescription) const prevDescription: string = configCurrentImageCarousel.description.imageText ? configCurrentImageCarousel.description.imageText : ''; const midSeparator: string = configCurrentImageCarousel.description.numberSeparator ? configCurrentImageCarousel.description.numberSeparator : ''; const middleDescription: string = currentIndex + 1 + midSeparator + this.images.length; if (imageWithoutDescription) { return prevDescription + middleDescription; } const currImgDescription: string = image.modal && image.modal.description ? image.modal.description : ''; const endDescription: string = configCurrentImageCarousel.description.beforeTextDescription + currImgDescription; return prevDescription + middleDescription + endDescription; } /** * Private method to update both `isFirstImage` and `isLastImage` based on * the index of the current image. * @param number currentIndex is the index of the current image */ private handleBoundaries(currentIndex: number): void { if (this.images.length === 1) { this.isFirstImage = true; this.isLastImage = true; return; } switch (currentIndex) { case 0: // execute this only if infinite sliding is disabled this.isFirstImage = true; this.isLastImage = false; break; case this.images.length - 1: // execute this only if infinite sliding is disabled this.isFirstImage = false; this.isLastImage = true; break; default: this.isFirstImage = false; this.isLastImage = false; break; } } /** * Private method to manage boundary arrows and sliding. * This is based on the slideConfig input to enable/disable 'infinite sliding'. * @param number index of the visible image */ private manageSlideConfig(): void { if (!this.currentImage) { throw new Error('Internal library error - currentImage must be defined'); } let index: number; try { index = getIndex(this.currentImage, this.images); } catch (err) { console.error('Cannot get the current image index in current-image'); throw err; } if (this.infinite === true) { // enable infinite sliding this.isFirstImage = false; this.isLastImage = false; } else { this.handleBoundaries(index); } } /** * Private method to emit events when either the last or the first image are visible. * @param action Enum of type Action that represents the source of the event that changed the * current image to the first one or the last one. * @param indexToCheck is the index number of the image (the first or the last one). */ private emitBoundaryEvent(action: Action, indexToCheck: number): void { if (this.id === null || this.id === undefined) { return; } // to emit first/last event switch (indexToCheck) { case 0: this.firstImage.emit(new ImageEvent(this.id, action, true)); break; case this.images.length - 1: this.lastImage.emit(new ImageEvent(this.id, action, true)); break; } } /** * Private method to check if next/prev actions should be blocked. * It checks if slideConfig.infinite === false and if the image index is equals to the input parameter. * If yes, it returns true to say that sliding should be blocked, otherwise not. * @param number boundaryIndex that could be either the beginning index (0) or the last index * of images (this.images.length - 1). * @returns boolean true if slideConfig.infinite === false and the current index is * either the first or the last one. */ private isPreventSliding(boundaryIndex: number): boolean { if (!this.currentImage) { throw new Error('Internal library error - currentImage must be defined'); } return !this.infinite && getIndex(this.currentImage, this.images) === boundaryIndex; } }
the_stack
import nock from 'nock'; import TerasliceClient from '../src'; import Client from '../src/client'; describe('Teraslice Client', () => { describe('when using the main export function', () => { it('returns a function', () => { expect(typeof TerasliceClient).toEqual('function'); }); it('should not throw an error if constructed with nothing', () => { expect(() => new TerasliceClient()).not.toThrow(); }); it('should have jobs, cluster, and assets', () => { const client = new TerasliceClient(); expect(client.jobs).not.toBeUndefined(); expect(client.cluster).not.toBeUndefined(); expect(client.assets).not.toBeUndefined(); }); }); describe('when using the Client constructor', () => { let client: Client; let scope: nock.Scope; beforeEach(() => { nock.cleanAll(); client = new Client({ baseUrl: 'http://teraslice.example.dev' }); scope = nock('http://teraslice.example.dev/v1'); }); afterEach(() => { nock.cleanAll(); }); describe('->get', () => { describe('when called with nothing', () => { it('should reject with a empty path message', async () => { expect.hasAssertions(); try { // @ts-expect-error await client.get(); } catch (err) { expect(err.message).toEqual('endpoint must not be empty'); } }); }); describe('when called with a non-string value', () => { it('should reject with invalid endpoint error', async () => { expect.hasAssertions(); try { // @ts-expect-error await client.get({ hello: 'hi' }); } catch (err) { expect(err.message).toEqual('endpoint must be a string'); } }); }); describe('when called with a valid path', () => { beforeEach(() => { scope.get('/hello') .reply(200, { example: 'hello' }); }); it('should resolve with the response from the server', async () => { const results = await client.get('/hello'); expect(results).toEqual({ example: 'hello' }); }); }); describe('when called with a path, query and options', () => { beforeEach(() => { scope.get('/hello') .matchHeader('Some-Header', 'yes') .query({ hello: true }) .reply(200, { example: 'hello' }); }); it('should resolve with the response from the server', async () => { const results = await client.get('/hello', { headers: { 'Some-Header': 'yes' }, // @ts-expect-error query: { hello: true } }); expect(results).toEqual({ example: 'hello' }); }); }); describe('when called with a path and plain query options', () => { beforeEach(() => { scope.get('/hello') .query({ hello: true }) .reply(200, { example: 'hello' }); }); it('should resolve with the response from the server', async () => { // @ts-expect-error const results = await client.get('/hello', { query: { hello: true } }); expect(results).toEqual({ example: 'hello' }); }); }); }); describe('->post', () => { describe('when called with nothing', () => { it('should reject with a empty path message', async () => { expect.hasAssertions(); try { // @ts-expect-error await client.post(); } catch (err) { expect(err.message).toEqual('endpoint must not be empty'); } }); }); // TODO: need better story around validations describe('when called with a non-string value', () => { it('should reject with invalid endpoint error', async () => { expect.hasAssertions(); try { // @ts-expect-error await client.post({ hello: 'hi' }); } catch (err) { expect(err.message).toEqual('endpoint must be a string'); } }); }); describe('when called the request throws an error', () => { beforeEach(() => { scope.post('/hello') .replyWithError('Oh no'); }); it('should reject with invalid error', async () => { expect.hasAssertions(); try { await client.post('/hello', null); } catch (err) { expect(err.message).toEqual('Oh no'); } }); }); describe('when called the server replys with an error', () => { beforeEach(() => { scope.post('/hello') .reply(500, { message: 'Oh no', error: 1232 }); }); it('should reject with invalid error', async () => { expect.hasAssertions(); try { await client.post('/hello', null); } catch (err) { expect(err.message).toEqual('Oh no'); expect(err.error).toEqual(1232); expect(err.code).toEqual(1232); expect(err.statusCode).toEqual(1232); } }); }); describe('when called the server replys and the error is a string', () => { beforeEach(() => { scope.post('/hello') .reply(428, { error: 'Uh-oh here is an error' }); }); it('should reject with invalid error', async () => { expect.hasAssertions(); try { await client.post('/hello', null); } catch (err) { expect(err.message).toEqual('Uh-oh here is an error'); expect(err.error).toEqual(428); expect(err.code).toEqual(428); } }); }); describe('when called the server replys with empty error', () => { beforeEach(() => { scope.post('/hello') .reply(500); }); it('should reject with invalid error', async () => { expect.hasAssertions(); try { await client.post('/hello', null); } catch (err) { expect(err.message).toEqual('Internal Server Error'); expect(err.error).toEqual(500); expect(err.code).toEqual(500); } }); }); describe('when called the server replys with an string error', () => { beforeEach(() => { scope.post('/hello') .reply(500, 'Oh no'); }); it('should reject with invalid error', async () => { expect.hasAssertions(); try { await client.post('/hello', null); } catch (err) { expect(err.message).toEqual('Oh no'); expect(err.error).toEqual(500); expect(err.code).toEqual(500); } }); }); describe('when called with a valid path', () => { const data = { example: 'hello' }; beforeEach(() => { scope.post('/hello') .reply(200, data); }); it('should resolve with the response from the server', async () => { const results = await client.post('/hello', null, {}); expect(results).toEqual(data); }); }); describe('when called with a path and query', () => { const data = { example: 'hello' }; beforeEach(() => { scope.post('/hello', { hello: true }) .reply(200, data); }); it('should resolve with the response from the server', async () => { const results = await client.post('/hello', { hello: true }, {}); expect(results).toEqual({ example: 'hello' }); }); }); describe('when called with a path and body', () => { const data = { example: 'hello' }; const strData = JSON.stringify(data); beforeEach(() => { scope.post('/hello', strData) .reply(200, data); }); it('should resolve with the response from the server', async () => { const results = await client.post('/hello', null, { body: strData, responseType: 'text' }); expect(results).toEqual(strData); }); }); describe('when called with a path and headers', () => { beforeEach(() => { scope.post('/hello', { hello: true }) .reply(200, { example: 'hello' }); }); it('should resolve with the response from the server', async () => { const results = await client.post('/hello', { hello: true }, { headers: { SomeHeader: 'hi' } }); expect(results).toEqual({ example: 'hello' }); }); }); describe('when called with a path and a buffer', () => { const response = { message: 'response-hello' }; const strData = JSON.stringify(response); beforeEach(() => { scope.post('/hello', 'hello') .reply(200, response); }); it('should resolve with the response from the server', async () => { const results = await client.post('/hello', Buffer.from('hello'), { responseType: 'text' }); expect(results).toEqual(strData); }); }); }); describe('->put', () => { describe('when called with nothing', () => { it('should reject with a empty path message', async () => { expect.hasAssertions(); try { // @ts-expect-error await client.put(); } catch (err) { expect(err.message).toEqual('endpoint must not be empty'); } }); }); describe('when called with a non-string value', () => { it('should reject with invalid endpoint error', async () => { expect.hasAssertions(); try { // @ts-expect-error await client.put({ hello: 'hi' }); } catch (err) { expect(err.message).toEqual('endpoint must be a string'); } }); }); describe('when called with a path and body', () => { const data = { example: 'hello' }; beforeEach(() => { scope.put('/hello', { hello: true }) .reply(200, data); }); it('should resolve with the response from the server', async () => { const results = await client.put('/hello', { hello: true }); expect(results).toEqual(data); }); }); describe('when called with a path and data', () => { const data = { example: 'hello' }; beforeEach(() => { scope.put('/hello', { hello: true }) .reply(200, data); }); it('should resolve with the response from the server', async () => { const results = await client.put('/hello', { hello: true }); expect(results).toEqual(data); }); }); }); describe('->delete', () => { describe('when called with nothing', () => { it('should reject with a empty path message', async () => { expect.hasAssertions(); try { // @ts-expect-error await client.delete(); } catch (err) { expect(err.message).toEqual('endpoint must not be empty'); } }); }); describe('when called with a non-string value', () => { it('should reject with invalid endpoint error', async () => { expect.hasAssertions(); try { // @ts-expect-error await client.delete({ hello: 'hi' }); } catch (err) { expect(err.message).toEqual('endpoint must be a string'); } }); }); describe('when called with a valid path', () => { const response = { _id: 'someID' }; beforeEach(() => { scope.delete('/hello') .reply(204, response); }); it('should resolve with the response from the server', async () => { const results = await client.delete('/hello'); expect(results).toEqual(response); }); }); describe('when called with a path and query', () => { const response = { _id: 'someID' }; beforeEach(() => { scope.delete('/hello') .query({ hello: true }) .reply(204, response); }); it('should resolve with the response from the server', async () => { // @ts-expect-error const results = await client.delete('/hello', { query: { hello: true } }); expect(results).toEqual(response); }); }); }); }); });
the_stack